Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# MouseClick Event Doesn't Fire On Middle Click or Right Click

This seems like it it should work but its not. I put a debug stop on the SWITCH statement. This event is only getting triggered on left click. Nothing happens and method is not fired on middle or right click. Any ideas? P.S. I already tried using MouseUp and MouseDown events and same issue.

Here is my code:

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

private void textBox1_MouseClick(object sender, MouseEventArgs e)
{
    switch (e.Button)
    {
        case MouseButtons.Left:
            // Left click
            textBox1.Text = "left";
            break;

        case MouseButtons.Right:
            // Right click
            textBox1.Text = "right";
            break;

        case MouseButtons.Middle:
            // Middle click
            textBox1.Text = "middle";
            break;
    }
}
like image 386
Kairan Avatar asked Oct 06 '18 13:10

Kairan


2 Answers

You need to use the MouseDown event to trap Middle and Right mouse clicks. The Click or MouseClick events are too late in the pipeline and are referred back to default OS Context Menu behaviour for textboxes.

private void textBox1_MouseDown(object sender, MouseEventArgs e)
{
    switch (e.Button)
    {
        case MouseButtons.Left:
            // Left click
            txt.Text = "left";
            break;

        case MouseButtons.Right:
            // Right click
            txt.Text = "right";
            break;

        case MouseButtons.Middle:
            // Middle click
            txt.Text = "middle";
            break;
    }
}
like image 191
Jeremy Thompson Avatar answered Oct 21 '22 01:10

Jeremy Thompson


You only need to set the attribute ShortcutsEnabled to False for that Textbox and write your code on MouseDown event.

It will work.

like image 4
Sasan Avatar answered Oct 21 '22 00:10

Sasan