How to move mouse cursor using C#?

杀马特。学长 韩版系。学妹 提交于 2019-12-17 00:45:10

问题


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#?


回答1:


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



回答2:


First Add Class (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;
    }
}

Then Call it From event :

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


来源:https://stackoverflow.com/questions/8050825/how-to-move-mouse-cursor-using-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!