I was trying to set up a system to check if the mouse is clicked in a winforms application and have ended up doing this
private void lblChips_MouseDown(object sender, MouseEventArgs e)
{
mouseDown = true;
}
private void lblChips_MouseUp(object sender, MouseEventArgs e)
{
mouseDown = false;
}
eight times over (for each label).
Does anyone know if there's a more efficient way of doing this? I tried using
private void frmGame4_MouseDown(object sender, MouseEventArgs e)
{
mouseDown = true;
}
private void frmGame4_MouseUp(object sender, MouseEventArgs e)
{
mouseDown = false;
}
but that doesnt work. Any help would be greatly appreciated.
CodePudding user response:
You could make two methods, one for mouse up and one for mouse down, like this:
private void labels_mouseDown(object sender, MouseEventArgs e)
{
mouseDown = true;
}
private void labels_mouseUp(object sender, MouseEventArgs e)
{
mouseDown = false;
}
Then, link all the labels to these methods. You can also do this from Code:
label.mouseDown = labels_mouseDown;
label.mouseUp = labels_mouseUp;
This has to be done somewhere under the InitializeComponent(); method. You still have to do this for every label but in the end it's less code.
CodePudding user response:
Combine all control events.
public Form1()
{
InitializeComponent();
foreach (Control control in this.Controls)
{
control.MouseDown = All_MouseDown;
control.MouseUp = All_MouseUp;
}
this.MouseDown = All_MouseDown;
this.MouseUp = All_MouseUp;
}
private void All_MouseUp(object sender, MouseEventArgs e)
{
this.Text = "up";
}
private void All_MouseDown(object sender, MouseEventArgs e)
{
this.Text = "down";
}