clicked mouse position in the console in csharp

Here's a sample C# console application that will print the x and y coordinates of the mouse when a click event occurs:

main.cs
using System;
using System.Runtime.InteropServices;

public class MouseClick
{
    [StructLayout(LayoutKind.Sequential)]
    public struct POINT
    {
        public int X;
        public int Y;
    }

    [DllImport("user32.dll")]
    public static extern bool GetCursorPos(out POINT lpPoint);

    static void Main(string[] args)
    {
        while (true)
        {
            // Wait for a mouse click event
            while (Console.KeyAvailable)
            {
                Console.ReadKey(true);
            }

            Console.WriteLine("Click somewhere...");

            while (Console.ReadKey(true).Key != ConsoleKey.Escape)
            {
                // Check for a mouse click event
                if (Console.KeyAvailable)
                {
                    Console.ReadKey(true); // Clear the key input
                    POINT point;

                    // Get the cursor position
                    if (GetCursorPos(out point))
                    {
                        Console.WriteLine($"Mouse clicked at ({point.X}, {point.Y})");
                    }

                    break; // Stop waiting for key presses
                }
            }

            Console.WriteLine("Press ESC to exit or click again...");
        }
    }
}
1274 chars
50 lines

This code uses P/Invoke to call the GetCursorPos function in the Windows user32.dll library. This function returns the current position of the mouse cursor, which is printed to the console when a click event is detected.

gistlibby LogSnag