Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
   }
}
like image 441
Billy Avatar asked Jun 01 '09 20:06

Billy


2 Answers

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.

like image 119
Meta-Knight Avatar answered Sep 28 '22 08:09

Meta-Knight


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().

like image 31
nightcoder Avatar answered Sep 28 '22 09:09

nightcoder