如何确定在WPF中哪个鼠标按钮引发了click事件?

qmb5sa22  于 2023-05-01  发布在  其他
关注(0)|答案(4)|浏览(162)

我有一个按钮,每当单击该按钮时就会触发OnClick。我想知道鼠标哪个按钮点击了那个按钮?
当我使用Mouse.LeftButtonMouse.RightButton时,两者都告诉我“realsed”,这是它们在点击后的状态。
我只想知道是谁按了我的按钮。如果将EventArgs更改为MouseEventArgs,则会收到错误。

XAML:<Button Name="myButton" Click="OnClick">

private void OnClick(object sender, EventArgs e)
{
//do certain thing. 
}
nuypyhwy

nuypyhwy1#

你可以像下面那样施法:

MouseEventArgs myArgs = (MouseEventArgs) e;

然后使用以下命令获取信息:

if (myArgs.Button == System.Windows.Forms.MouseButtons.Left)
{
    // do sth
}

该解决方案在VS 2013中工作,您不必再使用MouseClick事件;)

kgsdhlau

kgsdhlau2#

如果您只是使用Button的Click事件,那么唯一会触发它的鼠标按钮就是主鼠标按钮。
如果您仍然需要具体知道它是左按钮还是右按钮,那么您可以使用SystemInformation来获取它。

void OnClick(object sender, RoutedEventArgs e)
    {
        if (SystemParameters.SwapButtons) // Or use SystemInformation.MouseButtonsSwapped
        {
            // It's the right button.
        }
        else
        {
            // It's the standard left button.
        }
    }

**编辑:**SystemInformation的WPF等价物是SystemParameters,可以用SystemParameters代替。你可以包括系统。窗体作为引用来获取SystemInformation,而不会以任何方式对应用程序产生不利影响。

zbdgwd5y

zbdgwd5y3#

你说得对,何塞,这是与鼠标点击事件。但你必须添加一个小委托:
this.button1.MouseDown +=新系统。Windows.Forms.MouseEventHandler(this.MyMouseDouwn);
并在表单中使用此方法:

private void MyMouseDouwn(object sender, MouseEventArgs e) 
    {
        if (e.Button == MouseButtons.Right)
           this.Text = "Right";

        if (e.Button == MouseButtons.Left)
            this.Text = "Left";
    }
dxpyg8gm

dxpyg8gm4#

按下鼠标按钮然后松开后调用OnClick。在调用时,密钥已经被释放。有必要记住单击时的状态,并在处理OnClick时以及处理双击后重置状态。

相关问题