Created
December 29, 2022 19:21
-
-
Save chaojian-zhang/79cd45a46b351a44c53a6f0091297825 to your computer and use it in GitHub Desktop.
CursorPos #C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Drawing; | |
using System.Runtime.InteropServices; | |
using System.Windows; // Or use whatever point class you like for the implicit cast operator | |
namespace CursorPos | |
{ | |
class Program | |
{ | |
/// <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; | |
} | |
static void Main(string[] args) | |
{ | |
while (true) | |
{ | |
Point p = GetCursorPosition(); | |
Console.WriteLine($"X: {p.X}, Y: {p.Y}"); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment