Proper Use of OnClick vs. Events MouseClick in Windows Forms Applications Using C #

I am currently developing a custom control and realize that my code runs twice. This is not a very big problem (this is just a call to the Focus method). However, I would like to understand this.

From reading MSDN description for click | onclick , he claims that:

It is executed when the user presses the left mouse button on the object.

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

Why does OnClick handle this, and I need both events in my code to be skipped for some reason?

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); } } 
+4
source share
6 answers

According to MSDN , the Click event is raised not only when the mouse is clicked, but also when the Enter button is pressed. If you only need to handle mouse clicks, I would move all your code to the MouseClick event. You cannot do this the other way around because the Click event does not tell you which mouse button (if any) was pressed.

+11
source

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

+6
source

You do not need to have both events ... Just keep OnClick.

Also, I have not done Windows Forms for quite some time, but I think there is a better way to accept the focus than manually setting it to the click event, but I can’t say exactly what it is ... I think there is something.

0
source

In Winforms, the Click event is incremented when any mouse button is pressed.

0
source

If my memory serves me correctly, press both the mouseclick and 'Enter' keys, or even adjust the focus on the control using the Tab key, and then use the Spacebar or Enter to click.

If this behavior is acceptable / desirable, you can do the following.

I had this workaround for the 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

0
source

OnClick and CustomControl_MouseClick are the same event

You can specify how many methods you want to bind to the event (this.Click + = ...)

-3
source

All Articles