简体   繁体   English

C#复选框和鼠标单击事件

[英]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. 我正在自学C#,遇到了一个我似乎也找不到答案的问题。 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: 我有一个窗体,当我单击鼠标复选框时,状态变为true,但也会立即触发鼠标单击事件,我的代码如下:

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. 我已经搜索了堆栈溢出和Google,发现了类似的项目,但不是在C#中,但是在固定解决方案上没有运气。 What I want to do it use the first click to change the check box to true without triggering the mouse click event. 我要执行的操作是使用第一次单击将复选框更改为true,而不会触发鼠标单击事件。 I want to delay the event to the 2nd mouse click and not the first. 我想将事件延迟到第二次鼠标单击而不是第一次单击。

I have tried the following: 我尝试了以下方法:

  • for loop for循环
  • Clicks == 2 with if statement 使用if语句单击== 2
  • 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 : 除了Click事件,您还可以订阅CheckedChanged事件:

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 如果您想要一个真正健壮的解决方案,格兰特(Grant)的解决方案是最好的恕我直言,我只是在这里向您展示如何调整代码以使其工作

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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