user13381500
user13381500

Reputation:

How to move mouse cursor using C# using while infinite loop?

I found a solution to move the cursor via this URL in my Windows-Form app.
How to move mouse cursor using C#? but as i want to run infinitely but with a break so that when i want to stop it, it should stop here is what i'm trying to achieve.

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

It works but freezes my code. I just want to run it, and whenever i want to stop it, it should stop not freeze.

Upvotes: 0

Views: 2235

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1062780

Ultimately, the answer here is: "don't".

Windows forms are based on a message pump. If you have an event-handler from one message (like "click") that loops forever, it will never get around to processing other messages (like "draw"), so: your app is now unresponsive.

Instead of an infinite loop: use a Timer, and move the position in the callback. In this case, a System.Windows.Forms.Timer would be most appropriate.

Upvotes: 9

Related Questions