如何:检测鼠标按钮状态

更新:2007 年 11 月

此示例演示如何使用鼠标按钮事件和 MouseButtonState 属性来确定某个特定的鼠标按钮上是处于按下状态还是释放状态。

本示例包括一个可扩展应用程序标记语言 (XAML) 文件和一个代码隐藏文件。有关完整的示例,请参见检测鼠标按钮状态的示例示例。

示例

下面的代码创建了用户界面(它在 StackPanel 中包括了 TextBlock),并附加了 MouseLeftButtonDownMouseLeftButtonUp 事件的事件处理程序。

<StackPanel Height="100" Width="100" 
    MouseLeftButtonDown="HandleButtonDown" 
    MouseLeftButtonUp="HandleButtonDown" 
    Background="#d08080"
    DockPanel.Dock="Left"
    >
  <TextBlock>Click on Me</TextBlock>
</StackPanel>

下面的代码隐藏创建了 MouseLeftButtonUpMouseLeftButtonDown 事件处理程序。 当按鼠标左键时,TextBlock 的维度将增加。 当释放鼠标左键时,TextBlock 的维度将恢复到原始的高度和宽度。

Partial Public Class Window1
    Inherits Window

    Public Sub New()
        InitializeComponent()
    End Sub
    Private Sub HandleButtonDown(ByVal sender As Object, ByVal e As MouseButtonEventArgs)

        ' Casting the source to a StackPanel
        Dim sourceStackPanel As StackPanel = CType(e.Source, StackPanel)

        ' If the button is pressed then make dimensions larger.
        If e.ButtonState = MouseButtonState.Pressed Then
            sourceStackPanel.Width = 200
            sourceStackPanel.Height = 200

            ' If the button is released then make dimensions smaller.
        ElseIf e.ButtonState = MouseButtonState.Released Then
            sourceStackPanel.Width = 100
            sourceStackPanel.Height = 100
        End If
    End Sub

End Class
    public Window1()
    {
        InitializeComponent();
    }

    void HandleButtonDown(object sender, MouseButtonEventArgs e)
    {
        //Casting the source to a StackPanel
        StackPanel sourceStackPanel = e.Source as StackPanel;

        //If the button is pressed then make dimensions larger.
        if (e.ButtonState == MouseButtonState.Pressed)
        {
            sourceStackPanel.Width = 200;
            sourceStackPanel.Height = 200;
        }

        //If the button is released then make dimensions smaller.
        else if (e.ButtonState == MouseButtonState.Released)
        {
            sourceStackPanel.Width = 100;
            sourceStackPanel.Height = 100;
        }
    }

}

请参见

任务

检测鼠标按钮状态的示例

概念

输入概述