次の方法で共有


方法 : マウス ボタンの状態を検出する

更新 : 2007 年 11 月

マウス ボタン イベントと MouseButtonState プロパティを使用して、特定のマウス ボタンが押されたのか、または離されたのかを判別する方法を次の例に示します。

この例は、Extensible Application Markup Language (XAML) ファイルと分離コード ファイルで構成されています。サンプル全体については、「マウス ボタンの状態の検出のサンプル」を参照してください。

使用例

StackPanel 内部の TextBlock で構成されるユーザー インターフェイスを作成し、MouseLeftButtonDown イベントおよび MouseLeftButtonUp イベントのイベント ハンドラを割り当てるコードを次に示します。

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

次の分離コードでは、MouseLeftButtonUp および MouseLeftButtonDown イベント ハンドラを作成します。マウスの左ボタンを押すと、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;
        }
    }

}

参照

処理手順

マウス ボタンの状態の検出のサンプル

概念

入力の概要