This documentation is archived and is not being maintained.

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" 
  <TextBlock>Click on Me</TextBlock>

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()

    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;