web-dev-qa-db-ja.com

C#を使用してマウスカーソルを移動する方法は?

X秒ごとにマウスの動きをシミュレートしたい。そのために、タイマー(x秒)を使用し、タイマーが作動するとマウスを動かします。

しかし、C#を使用してマウスカーソルを移動させるにはどうすればよいですか?

69
aF.

Cursor.Position Property を見てください。開始する必要があります。

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);
}
68
James Hill

最初のクラスの追加(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);
28
user3290286