Wpf-mouse

提供:Dev Guides
移動先:案内検索

WPF-マウス

MouseDown、MouseEnter、MouseLeaveなど、さまざまなタイプのマウス入力があります。 次の例では、マウス入力の一部を処理します。

  • WPFMouseInput という名前の新しいWPFプロジェクトを作成しましょう。
  • 長方形と3つのテキストブロックをスタックパネルにドラッグし、次のXAMLファイルに示すように、次のプロパティとイベントを設定します。
<Window x:Class = "WPFMouseInput.MainWindow"
   xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml"
   xmlns:d = "http://schemas.microsoft.com/expression/blend/2008"
   xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006"
   xmlns:local = "clr-namespace:WPFMouseInput"
   mc:Ignorable = "d" Title = "MainWindow" Height = "350" Width = "604">

   <StackPanel>
      <Rectangle x:Name = "mrRec" Fill = "AliceBlue"
         MouseEnter = "OnMouseEnter" MouseLeave = "OnMouseLeave"
         MouseMove = "OnMouseMove" MouseDown = "OnMouseDown" Height = "100" Margin = "20">
      </Rectangle>

      <TextBlock x:Name = "txt1" Height = "31" HorizontalAlignment = "Right"
         Width = "250" Margin = "0,0,294,0"/>
      <TextBlock x:Name = "txt2" Height = "31" HorizontalAlignment = "Right"
         Width = "250" Margin = "0,0,294,0"/>
      <TextBlock x:Name = "txt3" Height = "31" HorizontalAlignment = "Right"
         Width = "250" Margin = "0,0,294,0"/>

   </StackPanel>

</Window>

さまざまなマウスイベントが処理されるC#コードを次に示します。

using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Shapes;

namespace WPFMouseInput {

   public partial class MainWindow : Window {

      public MainWindow() {
         InitializeComponent();
      }

      private void OnMouseEnter(object sender, MouseEventArgs e) {
         Rectangle source = e.Source as Rectangle;

         if (source != null) {
            source.Fill = Brushes.SlateGray;
         }

         txt1.Text = "Mouse Entered";
      }

      private void OnMouseLeave(object sender, MouseEventArgs e) {

        //Cast the source of the event to a Button.
         Rectangle source = e.Source as Rectangle;

        //If source is a Button.
         if (source != null) {
            source.Fill = Brushes.AliceBlue;
         }

         txt1.Text = "Mouse Leave";
         txt2.Text = "";
         txt3.Text = "";
      }

      private void OnMouseMove(object sender, MouseEventArgs e) {
         Point pnt = e.GetPosition(mrRec);
         txt2.Text = "Mouse Move: " + pnt.ToString();
      }

      private void OnMouseDown(object sender, MouseButtonEventArgs e) {
         Rectangle source = e.Source as Rectangle;
         Point pnt = e.GetPosition(mrRec);
         txt3.Text = "Mouse Click: " + pnt.ToString();

         if (source != null) {
            source.Fill = Brushes.Beige;
         }
      }

   }
}

上記のコードをコンパイルして実行すると、次のウィンドウが生成されます-

マウスの出力

マウスが長方形の内部に入ると、長方形の色が自動的に変わります。 さらに、マウスが座標とともに入力されたというメッセージが表示されます。

マウスが長方形の内側に進入します

長方形の内側をクリックすると、色が変わり、マウスがクリックされた座標が表示されます。

長方形の内側のマウスクリック

マウスが長方形を離れると、マウスが離れたというメッセージが表示され、長方形はデフォルトの色に変わります。

マウスが長方形を残す