0

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)

  • on windows you may use WINAPI native function (`GetCursorPos`) for this – Selvin Oct 14 '20 at 15:28
  • 1
    Does this answer your question? [How do I set the position of the mouse cursor from a Console app in C#?](https://stackoverflow.com/questions/6716275/how-do-i-set-the-position-of-the-mouse-cursor-from-a-console-app-in-c) – maxc137 Oct 14 '20 at 15:30
  • I need to Get it not set it @МаксимКошевой –  Oct 14 '20 at 16:01
  • Yes, but the answer is the same. You can ether add WinForms library into your project and use Cursor.Position (it supports get and set), or use WinApi, but instead of SetCursorPos just use GetCursorPos – maxc137 Oct 14 '20 at 16:08
  • How Do I get the values of "GetCursorPos()" (the X and Y) –  Oct 14 '20 at 16:31

1 Answers1

2

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

Nishan
  • 3,644
  • 1
  • 32
  • 41