user14376826
user14376826

Reputation:

Get Mouse Cursor position in a C# console app

So I need to get the mouse position in a C# Console app. Not the cursor in the app. Like say the cursor was at the top corner of the screen it would output 0,0. and i need to save the X and Y to int variables

But the mouse pointer anywhere out or in the app.

EDIT:

How Do I get the values of "GetCursorPos()" (the X and Y)

Upvotes: 1

Views: 5268

Answers (1)

Nishan
Nishan

Reputation: 4421

This program will get X, Y position of mouse on screen each 1 second

using System;
using System.Runtime.InteropServices;
using System.Drawing;
using System.Threading;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            while (true)
            {
                // New point that will be updated by the function with the current coordinates
                Point defPnt = new Point();

                // Call the function and pass the Point, defPnt
                GetCursorPos(ref defPnt);

                // Now after calling the function, defPnt contains the coordinates which we can read
                Console.WriteLine("X = " + defPnt.X.ToString());
                Console.WriteLine("Y = " + defPnt.Y.ToString());
                Thread.Sleep(1000);
            }
        }

        // We need to use unmanaged code
        [DllImport("user32.dll")]

        // GetCursorPos() makes everything possible
        static extern bool GetCursorPos(ref Point lpPoint);
    }
}

Source

Upvotes: 4

Related Questions