- 1 year ago
Set mouse position in C# and .Net Core
In C# and .NET Core, you can set the mouse position using the System.Windows.Forms.Cursor
class. To achieve this, you'll need to import the System.Windows.Forms
namespace.
Here's a simple example of how to set the mouse position in C# using .NET Core:
csharpusing System;
using System.Runtime.InteropServices;
using System.Windows.Forms;
public class Program
{
[DllImport("user32.dll")]
private static extern bool SetCursorPos(int X, int Y);
public static void Main()
{
// Coordinates to set the mouse position to
int x = 200;
int y = 300;
// Set the mouse position
SetMousePosition(x, y);
}
public static void SetMousePosition(int x, int y)
{
// Set the mouse position using Cursor class
Cursor.Position = new System.Drawing.Point(x, y);
// Alternatively, you can use the SetCursorPos method from user32.dll
// SetCursorPos(x, y);
}
}
In this example, we define a SetMousePosition
method that takes the X and Y coordinates as parameters. Inside the method, we use the Cursor.Position
property to set the mouse position.
Note that the SetCursorPos
method from user32.dll
is commented out in the example. You can use either Cursor.Position
or SetCursorPos
to set the mouse position. The SetCursorPos
method provides the same functionality and might be useful when you want to avoid referencing System.Windows.Forms
.
Keep in mind that setting the mouse position programmatically can have implications on user experience and may not be allowed or appropriate in all scenarios. Use this functionality carefully and consider user interactions and accessibility aspects.