WPF学习笔记——10)鼠标输入

鼠标输入也是一种常见的WPF事件类型,主要通过鼠标的操作来触发事件。

常见的鼠标事件有MouseEnter和MouseLeave,分别是在鼠标移动到组件上和离开组件时触发的,这两个事件都是直接事件,尽在某个元素上触发,不会传播到别的元素上。

除了这两种比较简单的直接时间,也包括一些冒泡路由事件和隧道路由事件,比如:PreviewMouseMove、MouseMove等

我们以MouseMove为例,设计可以自动获取鼠标当前位置信息的程序:

<Window x:Class="_10.Mouse_Input.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MouseEvent" Height="350" Width="350">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition></RowDefinition>
            <RowDefinition Height="Auto"></RowDefinition>
            <RowDefinition Height="Auto"></RowDefinition>
        </Grid.RowDefinitions>
        
        <Rectangle Name="rect" Fill="LightBlue" MouseMove="rect_MouseMove"></Rectangle>
        <Button Grid.Row="1" Name="cmdCapture">捕获鼠标位置</Button>
        <TextBlock Name="posInfo" Grid.Row="2"></TextBlock>
    </Grid>
</Window>
        private void rect_MouseMove(object sender, MouseEventArgs e)
        {
            Point pt = e.GetPosition(this);
            posInfo.Text = "鼠标位置:" + pt.ToString();
        }

 效果如下:

1、鼠标单击

鼠标单击分为鼠标左键和鼠标右键的单击,常见的鼠标单击事件会触发以下事件:

  • PreviewMouseLeftButtonDown
  • PreviewMouseRightButtonDown
  • MouseLeftButtonDown
  • MouseRightButtonDown
  • PreviewMouseLeftButtonUp
  • PreviewMouseRightButtonUp
  • MouseLeftButtonUp
  • MouseRightButtonUp

2、捕获鼠标

如果我们希望只能某个组件独占鼠标,那么我们利用鼠标捕获,让该组件捕获鼠标,从而鼠标点击其他组件时无法进入到响应函数中。

        private void cmdCapture_Click(object sender, RoutedEventArgs e)
        {
            Mouse.Capture(this.rect);
            this.cmdCapture.Content = "鼠标已捕获";
        }

           

3、鼠标拖放

鼠标拖放就是将窗口内某个元素拖离原来位置并放置到窗口的其他位置上,一般拖放分为三个步骤:

1)鼠标单击选择要拖放的元素;

2)鼠标左键按住不放移动元素使其位置发生变化;

3)鼠标松开左键将元素放置在某个位置。

我们以两个Label组件为例,将一个Label的内容拖放到另一个Label中。

<Window x:Class="_10.Mouse_Input.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="DragAndDrop" 
        Height="350" Width="350">
    <Grid>
        <Label Content="源数据" Height="28" HorizontalAlignment="Left" Name="label1" Margin="50,134,0,149" Background="LawnGreen" Width="88" MouseDown="label1_MouseDown" />
        <Label Content="" Height="28"  Margin="189,134,41,150" Name="label2" Background="LawnGreen" AllowDrop="True" Drop="label2_Drop" />
    </Grid>
</Window>

然后分别设置拖放的源和接收的组件

        private void label1_MouseDown(object sender, MouseButtonEventArgs e)
        {
            //初始化拖放的源元素
            Label lbl = (Label)sender;
            DragDrop.DoDragDrop(lbl, lbl.Content, DragDropEffects.Copy);
        }

        private void label2_Drop(object sender, DragEventArgs e)
        {
            //设置拖放的接收元素
            ((Label)sender).Content = e.Data.GetData(DataFormats.Text);
        }

下面是效果:

 

 

猜你喜欢

转载自blog.csdn.net/weixin_39478524/article/details/106301763