4

我有一个按钮,OnClick只要单击该按钮就会触发。我想知道哪个鼠标按钮点击了那个按钮?

当我使用Mouse.LeftButtonorMouse.RightButton时,两者都告诉我“ realsed ”,这是他们点击后的状态。

我只想知道是哪一个点击了我的按钮。如果我更改EventArgsMouseEventArgs,我会收到错误。

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

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

3 回答 3

6

你可以像下面这样投射:

MouseEventArgs myArgs = (MouseEventArgs) e;

然后通过以下方式获取信息:

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

该解决方案适用于 VS2013,您不必再使用 MouseClick 事件;)

于 2014-09-18T12:20:42.637 回答
2

如果您只是使用 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,可以改用它。尽管您可以包含 System.Windows.Forms 作为获取 SystemInformation 的参考,而不会以任何方式对应用程序产生不利影响。

于 2009-06-10T23:18:24.897 回答
0

没错,何塞,它与 MouseClick 事件有关。但是你必须添加一个小委托:

this.button1.MouseDown += new System.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";
    }
于 2009-06-10T19:23:38.833 回答