WPF-鼠标移动事件demo

2024-04-23 18:17:12 浏览数 (2)

鼠标事件

MouseEnter鼠标指针移动到该元素上时 MouseLeave鼠标指针离开该元素时 MouseEnter、MouseLeave都是直接事件,不会发生冒泡。 PreviewMouseLeftButtonDown按下鼠标左键 PreviewMouseRightButtonDown按下鼠标右键 PreviewMouseRightButtonDown释放鼠标右键

下面针对鼠标移动事件,实时输出鼠标位置的坐标。 XAML

代码语言:javascript复制
<Window x:Class="MouseEvent.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="446" Width="389">
    <Grid Margin="5">
        <Grid.RowDefinitions>
            <RowDefinition></RowDefinition>
            <RowDefinition Height="Auto"></RowDefinition>
            <RowDefinition Height="Auto"></RowDefinition>
        </Grid.RowDefinitions>
        <Rectangle Name="rect" Fill="LightBlue" MouseMove="Rectangle_MouseMove"></Rectangle>
        <Button Name="capture" Grid.Row="1" Click="Button_Click">Capture the Mouse</Button>
        <TextBlock Name="textBlock" Grid.Row="2"></TextBlock>
    </Grid>
</Window>

逻辑代码

代码语言:javascript复制
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace MouseEvent
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Rectangle_MouseMove(object sender, MouseEventArgs e)
        {
            Point pt = e.GetPosition(this);
            this.textBlock.Text = ("You are at ("   pt.X   ","   pt.Y   ") in window coordinates");
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Mouse.Capture(this.rect);
            this.capture.Content = "Mouse is now captured ...";

        }
    }
}

效果图,红点为点击的位置.

这里写图片描述这里写图片描述

0 人点赞