WPF捕捉用户鼠标移动

本文关键字:鼠标 移动 用户 WPF | 更新日期: 2023-09-27 17:53:16

我有一个程序,移动鼠标异步。在我的程序中,异步进程可以通过按下一个按钮来终止。

如何可以捕获事件时,用户移动鼠标,然后中止运行异步进程?以及当鼠标移动到wpf控件之外时。

Xaml:

<Button Height="20" Width="40" Click="Button_Click" ></Button>
代码:

namespace WpfApplication2
{
    public partial class MainWindow : Window
    {
        WorkWithMouse WWM = new WorkWithMouse();
        public MainWindow()
        {
            InitializeComponent();
            WWM.MouveMouseAsync();
        }
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            WWM.AbortMouseMove();
        }
        private void Window_MouseMove(object sender, MouseEventArgs e)
        {
            Console.WriteLine("Moving");
        }
    }
    public class WorkWithMouse
    {
        CancellationTokenSource cancelTokenSource = new CancellationTokenSource();
        [DllImport("User32.dll")]
        private static extern bool SetCursorPos(int X, int Y);
        public void AbortMouseMove()
        {
            cancelTokenSource.Cancel();
        }
        public void MouveMouseAsync()
        {
            Action<CancellationToken> task = new Action<CancellationToken>(MoveMouse);
            IAsyncResult result = task.BeginInvoke(cancelTokenSource.Token, null, null);
        }
        private void MoveMouse(CancellationToken token)
        {
            int i = 100;
            while (!token.IsCancellationRequested)
            {
                System.Threading.Thread.Sleep(2000);
                SetCursorPos(i, 100);
                i = i + 1;
            }
        }
    }

WPF捕捉用户鼠标移动

您需要通过p/Invoke挂接到全局鼠标事件,因为您可能不会在应用程序中单击。

如何检测鼠标点击?