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.

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

}
Was this page helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

ADD
Show:
© 2014 Microsoft