WPF捕获用户的鼠标移动 [英] WPF catch user mouse movement
本文介绍了WPF捕获用户的鼠标移动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有使鼠标异步移动的程序.在我的程序中,可以通过按一个按钮来中止异步过程.
I have program that moving mouse asynchronous. In my program async process can be aborted by pressing on a button.
如何在用户移动鼠标并中止运行异步过程时捕获事件?以及当鼠标移到wpf控件之外时.
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>
代码:
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;
}
}
}
推荐答案
您可能需要通过P/Invoke挂接全局Mouse事件,因为您可能没有在应用程序中单击.
You would need to hook into the global Mouse events via P/Invoke as you may not be clicking within the application.
这篇关于WPF捕获用户的鼠标移动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文