Eksperiment626
Eksperiment626

Reputation: 1007

How to move cursor in windows form application?

I'm writing an application where I need to move the cursor programmatically. I've tried writing:

Cursor.Position = new Point(50, 50);

But it doesn't work. Im writing an windows form application in c#.

I hope someone can help me :) Thanks in advance :)

Upvotes: 1

Views: 3557

Answers (2)

PersyJack
PersyJack

Reputation: 1964

Assuming you want it with button click:

First add InteropServices namespace:

using System.Runtime.InteropServices;

then create your button click event

[DllImport("User32.Dll")]
public static extern long SetCursorPos(int x, int y);
private void button1_Click(object sender, EventArgs e)
{
    SetCursorPos(50,50);
}

Take a look at this:

[https://stackoverflow.com/questions/647236/moving-mouse-cursor-programmatically][1]

Upvotes: 2

Aflred
Aflred

Reputation: 4593

Drag a button on to the form and double click.

then you should get a code behind.

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Cursor.Position = new Point(50, 50);
        }
    }
}

once you click the button the function - button1_Click fires and moves your cursor. Perhaps write here what you want to do exactly, i suspect you will need a loop

ALSO

this might help in your endevours.

  Cursor.Position = 
new Point(Form1.MousePosition.X + 50, Form1.MousePosition.Y + 50);

Form1.MousePosition is the current position of the mouse on the form.

so the code above would move the mouse 50 units right and 50 units down from its current position.

Also theres a form1_load event, double click the form and use that.

Upvotes: 0

Related Questions