A191919
A191919

Reputation: 3462

WPF catch user mouse movement

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

Upvotes: 0

Views: 554

Answers (1)

Ben Steele
Ben Steele

Reputation: 414

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?

Upvotes: 1

Related Questions