Как переместить курсор мыши с помощью C#?

Я хочу имитировать движение мыши каждые x секунд. Для этого я буду использовать таймер (X секунд), и когда таймер тикает, я сделаю движение мыши.

но как я могу заставить курсор мыши двигаться с помощью C#?

2 ответов


посмотри Cursor.Position свойства. Это должно помочь тебе начать.

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

Сначала Добавьте Класс (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;
    }
}

затем вызовите его из события:

Win32.POINT p = new Win32.POINT();
p.x = Convert.ToInt16(txtMouseX.Text);
p.y = Convert.ToInt16(txtMouseY.Text);

Win32.ClientToScreen(this.Handle, ref p);
Win32.SetCursorPos(p.x, p.y);