Compartir a través de


Cómo: Detectar el estado de un botón del mouse

Actualización: noviembre 2007

En este ejemplo se muestra cómo utilizar eventos de botón del mouse y la propiedad MouseButtonState para determinar si un botón del mouse concreto está presionado o no.

Este ejemplo consta de un archivo Lenguaje de marcado de aplicaciones extensible (XAML) y de un archivo de código subyacente. Para obtener el ejemplo de código completo, vea Ejemplo Detecting Mouse Button State.

Ejemplo

En el código siguiente se crea la interfaz de usuario, que está compuesta de un control TextBlock dentro de un control StackPanel, y se asocian los controladores de eventos para los eventos MouseLeftButtonDown y MouseLeftButtonUp.

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

En el siguiente código subyacente se crean los controladores de eventos MouseLeftButtonUp y MouseLeftButtonDown. Cuando se presiona el botón primario, se aumentan las dimensiones de TextBlock. Cuando se suelta el botón primario, las dimensiones de TextBlock se restauran a su alto y ancho originales.

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

}

Vea también

Tareas

Ejemplo Detecting Mouse Button State

Conceptos

Información general sobre acciones del usuario