如何使用无限循环使用 C# 移动鼠标光标?
How to move mouse cursor using C# using while infinite loop?
我在我的 Windows-Form 应用程序中找到了通过此 URL 移动光标的解决方案。
How to move mouse cursor using C#?
但是因为我想无限地运行但是有一个休息所以当我想停止它时,它应该停止在这里就是我想要实现的。
private void btnMove_Click(object sender, EventArgs e)
{
//int i = 0;
while (true)
{
//i++;
Cursor = new Cursor(Cursor.Current.Handle);
Cursor.Position = new Point(Cursor.Position.X - 40, Cursor.Position.Y - 40);
Thread.Sleep(5000);
Cursor.Position = new Point(Cursor.Position.X + 40, Cursor.Position.Y + 40);
}
//Task t = new Task(() =>
//{
//});
//t.Start();
}
它有效但冻结了我的代码。我只想运行它,每当我想停止它时,它应该停止而不是冻结。
最终,这里的答案是:“不要”。
Windows 表单基于消息泵。如果一条消息(如“点击”)的 event-handler 永远循环,它永远不会处理其他消息(如“绘制”),因此:你的应用程序现在没有响应。
而不是无限循环:使用 Timer
,并在回调中移动位置。在这种情况下,System.Windows.Forms.Timer
是最合适的。
我在我的 Windows-Form 应用程序中找到了通过此 URL 移动光标的解决方案。
How to move mouse cursor using C#?
但是因为我想无限地运行但是有一个休息所以当我想停止它时,它应该停止在这里就是我想要实现的。
private void btnMove_Click(object sender, EventArgs e)
{
//int i = 0;
while (true)
{
//i++;
Cursor = new Cursor(Cursor.Current.Handle);
Cursor.Position = new Point(Cursor.Position.X - 40, Cursor.Position.Y - 40);
Thread.Sleep(5000);
Cursor.Position = new Point(Cursor.Position.X + 40, Cursor.Position.Y + 40);
}
//Task t = new Task(() =>
//{
//});
//t.Start();
}
它有效但冻结了我的代码。我只想运行它,每当我想停止它时,它应该停止而不是冻结。
最终,这里的答案是:“不要”。
Windows 表单基于消息泵。如果一条消息(如“点击”)的 event-handler 永远循环,它永远不会处理其他消息(如“绘制”),因此:你的应用程序现在没有响应。
而不是无限循环:使用 Timer
,并在回调中移动位置。在这种情况下,System.Windows.Forms.Timer
是最合适的。