Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to move mouse cursor using C#?

I want to simulate mouse movement every x seconds. For that, I'll use a timer (x seconds) and when the timer ticks I'll make the mouse movement.

But, how can I make the mouse cursor move using C#?

like image 510
aF. Avatar asked Nov 08 '11 13:11

aF.


People also ask

What is a cursor in C?

1) A cursor is the position indicator on a computer display screen where a user can enter text. In an operating system with a graphical user interface (GUI), the cursor is also a visible and moving pointer that the user controls with a mouse, touch pad, or similar input device.


2 Answers

Take a look at the Cursor.Position Property. It should get you started.

private void MoveCursor() {    // Set the Current cursor, move the cursor's Position,    // and set its clipping rectangle to the form.      this.Cursor = new Cursor(Cursor.Current.Handle);    Cursor.Position = new Point(Cursor.Position.X - 50, Cursor.Position.Y - 50);    Cursor.Clip = new Rectangle(this.Location, this.Size); } 
like image 174
James Hill Avatar answered Oct 03 '22 10:10

James Hill


First Add a Class called Win32.cs

public class Win32 {      [DllImport("User32.Dll")]     public static extern long SetCursorPos(int x, int y);      [DllImport("User32.Dll")]     public static extern bool ClientToScreen(IntPtr hWnd, ref POINT point);      [StructLayout(LayoutKind.Sequential)]     public struct POINT     {         public int x;         public int y;          public POINT(int X, int Y)         {             x = X;             y = Y;         }     } } 

You can use it then like this:

Win32.POINT p = new Win32.POINT(xPos, yPos);  Win32.ClientToScreen(this.Handle, ref p); Win32.SetCursorPos(p.x, p.y); 
like image 45
user3290286 Avatar answered Oct 03 '22 09:10

user3290286