简体   繁体   中英

C# Move Mouse Cursor to a Specific Position on Screen for Windows 10 64bit

I tried this but I think it's for 32bit Windows only.

How to move mouse cursor using C#?

I am getting lots of red underline errors like "Cursor does not contain a definition for Position" and "Rectangle does not contain a constructor that takes 2 arguments"

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

Searched older threads but I think the code is outdated and doesn't work in Windows 64 bit OS. So I'm looking for new code if there is any.

The example you are referencing is for moving the cursor by a specific amount, it is over-engineered if you just want to move the mouse to a specific position.

The code works on a 64 bit OS, but you need access to Windows Forms which is not available in every version of .NET.

At the top of the file you need to add

using System.Windows.Forms;
using System.Drawing;

You also need to add a reference to System.Windows.Forms to your project if it is not already included. The Cursor class is in System.Windows.Forms and the Point class is in System.Drawing .

The code is also supposed to exist inside a Form class, like if you created a new form through the IDE and then added some code to it. That is why it assumes a Cursor property already exists.

If all you want to do is move the cursor to a specific position on screen, you only need this one line and it doesn't need to be inside a Form:

Cursor.Position = new Point(x, y);

Replace x and y with the coordinates you need or set them as int variables. Position is a static property so you don't need to create an instance of Cursor first. But Cursor is still a class in System.Windows.Forms so you still need to be using it and have a reference to it in your project.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM