共用方式為


How to: Detect Mouse Button State

This example shows how to use mouse button events and the MouseButtonState property to determine whether a specific mouse button is pressed or released.

This example consists of a Extensible Application Markup Language (XAML) file and a code behind file. For the complete sample, see the Detecting Mouse Button State Sample sample.

Example

The following code creates the user interface, which consists of a TextBlock inside a StackPanel, and attaches event handlers for the MouseLeftButtonDown and MouseLeftButtonUp events.

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

The following code behind creates the MouseLeftButtonUp and MouseLeftButtonDown event handlers. When the left mouse button is pressed, the dimensions of the TextBlock are increased. When the left button is released, the dimensions of the TextBlock are restored to the original height and width.

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

}
Partial Public Class Window1
    Inherits Window

    Public Sub New()
        InitializeComponent()
    End Sub
    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

See Also

Concepts

Input Overview

Other Resources

Detecting Mouse Button State Sample