简体   繁体   中英

Correct usage of OnClick vs. MouseClick events in Windows Forms applications using C#

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.

From reading the MSDN description for click |onclick event , it states that:

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

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.

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);
   }
}

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.

First of all, your link is incorrect, it links to HTML and DHTML Reference, not WinForms :) Correct link is Control.MouseClick event
You need to override only one method. If you want to handle only mouse clicks - override OnMouseClick() and don't handle MouseClick event, otherwise - override OnClick() and don't override OnMouseClick().

If my memory serves me right, click does both mouseclick and the 'Enter' key or even setting focus on the control using the 'Tab' key and then using 'Space' or 'Enter' to "click" it.

If such behaviour is acceptable/desired, you may do the following.

I had this workaround for a DoubleClick event...

void ControlClick(object sender, EventArgs e)
{
    MouseEventArgs mEvt=e as MouseEventArgs; // or (MouseEventArgs)e;

    // now mEvt has the same properties as 'e' in MouseClick event
}

Hope this helps.

-Nurchi

You shouldn't need to have both events... Just keep the OnClick.

Also, I haven't done Windows Forms in quite a while, but I think there's a better way to accept focus than manually setting it on the click event, but I can't tell you specifically what it is... I think there's a property for it or something.

在 Winforms 中,单击任一鼠标键时都会引发 Click 事件。

The OnClick and CustomControl_MouseClick is the same event

You can have how many methods you want attached to an event ( this.Click += ...)

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