【问题标题】:How to move mouse cursor using C# using while infinite loop?如何使用 C# 使用 while 无限循环移动鼠标光标?
【发布时间】:2021-01-04 06:32:30
【问题描述】:

我在我的 Windows 窗体应用程序中找到了通过此 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();
    }

它可以工作,但会冻结我的代码。我只想运行它,当我想停止它时,它应该停止而不是冻结。

【问题讨论】:

  • @OlivierRogier 每次有人建议DoEvents() 来“解决”这样的问题,世界都会流泪
  • @Nyerguds 这里真的不需要多线程; “每 5 秒做一次”是一个简单的计时器
  • @OlivierRogier 可以考虑:一个人可以喜欢坏事
  • @Nyerguds 在System.Threading 中有一个 another oneWindows.Forms 中有一个
  • @Nyerguds 有多种Timer 类型;我在这里提倡的是System.Windows.Forms.Timer,它通过sync-context 调用回UI 上下文线程;因此,虽然可能会短暂涉及一个池线程,但消费者看不到该实现细节:从他们的角度来看,只涉及 UI 线程

标签: c# winforms mouse-cursor


【解决方案1】:

最终,这里的答案是:“不要”。

Windows 窗体基于消息泵。如果您的一条消息(如“click”)的事件处理程序永远循环,它将永远无法处理其他消息(如“draw”),因此:您的应用现在无响应。

而不是无限循环:使用Timer,并在回调中移动位置。在这种情况下,System.Windows.Forms.Timer 是最合适的。

【讨论】:

    猜你喜欢
    • 2011-12-24
    • 2018-03-31
    • 2021-09-20
    • 1970-01-01
    • 1970-01-01
    • 2018-01-28
    • 1970-01-01
    相关资源
    最近更新 更多