我有程序移动鼠标异步。在我的程序中,可以通过按下按钮来中止异步过程。
当用户移动鼠标而不是中止运行异步进程时,如何捕获事件?而且当鼠标移动到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;
}
}
}