在Windows Forms应用程序中使用C#正确使用OnClick vs. MouseClick事件 [英] Correct usage of OnClick vs. MouseClick events in Windows Forms applications using C#

查看:201
本文介绍了在Windows Forms应用程序中使用C#正确使用OnClick vs. MouseClick事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个自定义控件,并意识到我的代码正在运行两次。这不是一个巨大的问题(它只是一个Focus方法调用)。但是,我想了解它。

I'm currently developing a custom control and realize that my code is being run twice. It is not really a huge issue (it is only a Focus method call). However, I would like to understand it.

从阅读 MSDN描述点击| onclick事件,它指出:


当用户单击对象上的鼠标左键时触发。

Fires when the user clicks the left mouse button on the object.

所以我添加了OnClick事件和MouseClick事件来处理左右点击。但在调试代码之后,我发现OnClick处理左右点击事件。

So I added the OnClick event and the MouseClick events to handle both left and right clicking. But after debugging the code I found that the OnClick handles both left and right click events.

为什么OnClick处理这两个事件,我是否需要将两个事件保留在我的代码中,这是因为我忽视了某些原因?

Why is OnClick handling both and do I need to keep both events in my code for some reason I'm overlooking?

protected override void OnClick(EventArgs e)
{

   this.Focus();
   base.OnClick(e);
}

private void CustomControl_MouseClick(object sender, MouseEventArgs e)
{       
   if (e.Button == MouseButtons.Right)
   {
      rightClickMenu(e);
   }
}


推荐答案

a href =http://msdn.microsoft.com/en-us/library/system.windows.forms.control.click.aspx =noreferrer>根据MSDN ,Click事件是当鼠标点击时,不仅要调用,还可以在按下Enter按钮时调用。如果您只需要处理鼠标点击,我将移动MouseClick事件中的所有代码。您不能这样做,因为Click事件不会告诉您哪个鼠标按钮(如果有)被点击。

According to MSDN, the Click event is called not only when the mouse is clicked, but also when the Enter button is pressed. If you only need to handle mouse clicks, I'd move all of your code in the MouseClick event. You can't do it the other way around because the Click event doesn't tell you which mouse button (if any) was clicked.

这篇关于在Windows Forms应用程序中使用C#正确使用OnClick vs. MouseClick事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆