Getting mouse position in c#
You should use System.Windows.Forms.Cursor.Position: "A Point that represents the cursor's position in screen coordinates."
If you don't want to reference Forms you can use interop to get the cursor position:
using System.Runtime.InteropServices;
using System.Windows; // Or use whatever point class you like for the implicit cast operator
/// <summary>
/// Struct representing a point.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct POINT
{
public int X;
public int Y;
public static implicit operator Point(POINT point)
{
return new Point(point.X, point.Y);
}
}
/// <summary>
/// Retrieves the cursor's position, in screen coordinates.
/// </summary>
/// <see>See MSDN documentation for further information.</see>
[DllImport("user32.dll")]
public static extern bool GetCursorPos(out POINT lpPoint);
public static Point GetCursorPosition()
{
POINT lpPoint;
GetCursorPos(out lpPoint);
// NOTE: If you need error handling
// bool success = GetCursorPos(out lpPoint);
// if (!success)
return lpPoint;
}
Cursor.Position will get the current screen poisition of the mouse (if you are in a Control, the MousePosition property will also get the same value).
To set the mouse position, you will have to use Cursor.Position
and give it a new Point:
Cursor.Position = new Point(x, y);
You can do this in your Main
method before creating your form.