简体   繁体   中英

C# checkbox and mouse click event

I am self teaching myself C# and ran into a problem I haven't seem to find an answer too. I have a Form that when I mouse click the check box the state goes to true but also immediately triggers the mouse click event I have code follows:

private void uxCheckBoxMouseClick(object sender, MouseEventArgs e)
{
    //MouseEventArgs me = (MouseEventArgs) e;
    if (uxMouseCopyCheckBox.Checked)
    {
        MessageBox.Show("Test");
        uxMouseCopyCheckBox.Checked = false;

    }
}

I have searched the stack overflow and Google and found similar items but not in C# but no luck on the fixed solution. What I want to do it use the first click to change the check box to true without triggering the mouse click event. I want to delay the event to the 2nd mouse click and not the first.

I have tried the following:

  • for loop
  • Clicks == 2 with if statement
  • subscribing but at a loss on what to use

Just use a boolean variable as a flag.

private bool wasAlreadyClickedOnce;

private void uxCheckBoxMouseClick(object sender, MouseEventArgs e)
{
    if (!wasAlreadyClickedOnce)
    {
        wasAlreadyClickedOnce = true;
        return;
    }

    if (uxMouseCopyCheckBox.Checked)
    {
        MessageBox.Show("Test");
        uxMouseCopyCheckBox.Checked = false;

    }
}

Instead of the Click event you could subsribe to the CheckedChanged event :

The Handler will look look exactly like yours :

private void uxMouseCopyCheckBox_CheckedChanged(object sender, EventArgs e)
{
    if (!uxMouseCopyCheckBox.Checked)
    {
        MessageBox.Show("Test");
        uxMouseCopyCheckBox.Checked = false;
    }
}

The only difference is that we want the Message box to be shwon only on the second click so when you will uncheck the checkbox.

Be careful though, if you change the default state of the checkbox, it will no longer work.

If you want a really robust solution Grant's one is IMHO the best, mine was just here to show you how to adapt your code for it to work

尝试使用Click事件而不是CheckedChanged事件来选中或取消选中CheckBox ,然后可以将MouseClick事件用于其他内容。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM