views:

1469

answers:

5

I have a custom control I'm currently developing and realized that my code was being ran twice. Not really a huge issue (it is only a Focus method call) however I would like to understand it.

From reading the MSDN description 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);
   }
}
A: 

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.

Max Schmeling
For most controls if the user clicked on it the control will already have window focus.
Arnshea
He can't just keep the OnClick because he needs to check if the right mouse button was clicked, and there is no way to know with this event.
Meta-Knight
A: 

In Winforms, the Click event is raised when either mouse key is clicked.

Arnshea
+5  A: 

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.

Meta-Knight
A: 

The OnClick and CustomControl_MouseClick is the same event

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

pixel3cs
No, Click and MouseClick are different events. Control.OnClick calls Click event handlers and Control.OnMouseClick calls MouseClick event handlers.
nightcoder
+2  A: 

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

nightcoder