5

I have a button on a form and want to handle both left and right clicks.

I am handling the MouseClick event, but this is only raised on a left click.

Is this a problem somewhere in my code (a setting that I have missed) or the intended functionality?

If this is not possible to fix, what is the best workaround - to handle the MouseUp event?

The reason I would like to use MouseClick is so that double clicks are automatically recognised.

Thanks for any feedback.

Mark
  • 1,649
  • 4
  • 25
  • 43
  • Only the focused control receives input events. Perhaps it changes somewhere? – foowtf Nov 18 '11 at 09:53
  • Surely clicking on the button would make it the focused control? – Mark Nov 18 '11 at 11:25
  • 1
    No, lots of controls can't get the focus, like a Label or PictureBox. Don't keep the type of control you're clicking a secret. – Hans Passant Nov 18 '11 at 12:02
  • Ok, I didn't realise. Thanks. But why would you have a button that can't generate click events unless previously focused? Do you think this might be the problem and if so, how can this be overcome? – Mark Nov 18 '11 at 12:32
  • `OnClick` handles both left and right click events http://msdn.microsoft.com/en-us/library/system.windows.forms.control.click.aspx – Matt Evans Nov 18 '11 at 09:29
  • Surely that link says that for Buttons, right click does not call the `Click` event? – Mark Nov 18 '11 at 11:40

3 Answers3

12

Use MouseUp !!

    private void button6_MouseUp(object sender, MouseEventArgs e)
    {
        if (e.Button == System.Windows.Forms.MouseButtons.Left)
        {
            MessageBox.Show("LEFT");
        }
        if (e.Button == System.Windows.Forms.MouseButtons.Right)
        {
            MessageBox.Show("RIGHT");
        }
    }
Vova Popov
  • 1,027
  • 11
  • 11
5

Its hard to answer without code but in general, it should work.

 private void Form1_MouseClick(object sender, MouseEventArgs e)
{
  if (e.Button == System.Windows.Forms.MouseButtons.Left)
  {
    MessageBox.Show("LEFT");
  }
  if (e.Button == System.Windows.Forms.MouseButtons.Right)
  {
    MessageBox.Show("RIGHT");
  }
}

// EventHandler

 this.MouseClick += new System.Windows.Forms.MouseEventHandler(this.Form1_MouseClick);

Edit: There is a MouseDoubleClick Event you might want to use to recognize double clicks. Works both, for left and right musebuttons.

Alex
  • 7,343
  • 1
  • 38
  • 52
  • That is basically what I have - except even simpler (I don't check which button - I just have a messagebox on every `MouseClick` event), but it is only raised when I use the right mouse button. – Mark Nov 18 '11 at 11:43
4

Apparently the answer to this is that OnClick does not handle right click events for Buttons. The solution was therefore to use MouseUp/MouseDown and check for double clicks/clicks where the mouse moves on/off halfway through manually.

Mark
  • 1,649
  • 4
  • 25
  • 43