C#MouseClick事件不会在中键单击或右键单击时触发

Kai*_*ran 7 c# right-click mouseclick-event

这似乎应该有效,但事实并非如此.我在SWITCH语句中设置了一个调试停止.此事件仅在左键单击时触发.没有任何反应,并且在中间或右键单击时不会触发方法.有任何想法吗?PS我已经尝试过使用MouseUp和MouseDown事件以及相同的问题.

这是我的代码:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

Jer*_*son 11

您需要使用MouseDown事件来捕获鼠标中键和右键.Click或MouseClick事件在管道中为时已晚,并且会返回到文本框的默认OS上下文菜单行为.

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;
    }
}
Run Code Online (Sandbox Code Playgroud)