I am making a sudoku game on C# .NET desktop.
The sudokupanel consists of 81 labels. I define their number on the board with a algorithm.
Now what I want to do is basically this:
foreach(Label l in panel1.Controls.OfType<Label>())
{
if(l.MouseEnter == true)
{
l.ForeColor = Color.White;
}
}
But it doesn't work. Are there any solutions for this? Sorry I don't know how to use events in if statements.
EDIT: I've decided to just use the event MouseEnter for every label one by one. I know that CS 8.0 should support using events inside foreach stuff but not sure.
CodePudding user response:
It's not intended to be used this way.
You should subscribe to the MouseEnter event for each label, you can use the same event handler method for all of them and use sender property to know the activated label. You can subscribe directly in VS Properties window if the label are created with the designer, or you can do it programmatically using the = operator.
Please see https://docs.microsoft.com/en-us/dotnet/standard/events/ or any online tutorial about events.
CodePudding user response:
events are things that tell you when something has happened. They do not tell you the state of something. So there are a few options
Attach an event to each label for entering/leaving the label. You can use the same eventhandler/method to handle the events for each label, and cast the sender object to your label and set the color. Something like this. Note that this should be run once, in the constructor.
foreach(Label l in panel1.Controls.OfType<Label>())
{
l.MouseEnter = (o, e) => ((Label)o).ForeColor = Color.White;
l.MouseLeave = (o, e) => ((Label)o).ForeColor = Color.Black;
}
Or you could use a loop that checks the mouse cursor position and check if this is inside each label. But you would have to run the loop for the colors to change, and running it all the time would be wasteful of CPU resources.
