Kairan
Kairan

Reputation: 5542

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;
    }
}

Upvotes: 9

Views: 3730

Answers (3)

Jeremy Thompson
Jeremy Thompson

Reputation: 65534

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;
    }
}

Upvotes: 13

Sasan
Sasan

Reputation: 141

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

It will work.

Upvotes: 3

Sebastian Blumenberg
Sebastian Blumenberg

Reputation: 32

Have you tried setting the stop on event declaration? Also test this with middle mouse button click

if e.Button = 4194304 Then
    a = b //set the stop here
End if

If the event is not triggering even with the stop on the event declaration, something is wrong with the project, make a new one and test.

Upvotes: -1

Related Questions