WPF catch user mouse movement

♀尐吖头ヾ 提交于 2019-12-25 06:49:53

问题


I have program that moving mouse asynchronous. In my program async process can be aborted by pressing on a button.

How it can be possible to catch event when user moving mouse and than abort running async process? And also when mouse moving outside of wpf control.

Xaml:

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

Code:

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;
            }
        }
    }

回答1:


You would need to hook into the global Mouse events via P/Invoke as you may not be clicking within the application.

How to detect mouse clicks?



来源:https://stackoverflow.com/questions/38120848/wpf-catch-user-mouse-movement

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!