Get screen cursor coordinates

Learn how to retrieve the mouse cursor coordinates not just inside the form, but also when the cursor is located outside of the form, such as on the desktop or when a different application has the focus. We use the GetCursorPos() function from the Windows API.

Form-wide coordinates versus screen coordinates

Using .NET Framework 1.1 or 2.0, retrieving the mouse coordinates is pretty easy, by making use of a couple of properties, as I proven in the tutorial named Mouse Coordinates.

However, .NET Framework doesn't offer us the possibility to retrieve the mouse coordinates when the mouse leaves the form, and thus the coordinates that are relative to the screen.

There are many cases in which you'll want them to retrieve the overall cursor coordinates: starting from the upper-left edge of the screen, to the most extreme point, which is the lower-right edge. There is a function in the Windows API which allows us to do just that: GetCursorPos().

Below is a screenshot of the application that I built for this tutorial and which you can download from the link at the top of the project. It's compiled using .NET 2.0, but you can compile the code with a .NET 1.1 compiler without any changes whatsoever.

Using GetCursorPos() to retrieve the coordinates

To retrieve the global mouse coordinates we need to use unmanaged code, thus add the following using statement:

using System.Runtime.InteropServices;

GetCursorPost() is located inside user32.dll, so we need to define the attribute:

// We need to use unmanaged code

[DllImport("user32.dll")]

// GetCursorPos() makes everything possible

static extern bool GetCursorPos(refPoint lpPoint);

Add two labels to the form (lblCoordX and lblCoordY), where the X and Y coordinates will be displayed. Also add a timer and set its interval (the Interval property) to 10.

But why do we need a timer anyway?

Well, there doesn't seem to be a MouseMove event that fires when the cursor is moving, indifferent of the focused application. There is such an event in .NET, but it's only effective while the mouse hovers the form or some other control in it. So to continously monitor the cursor position we use a timer that gets the mouse cursor coordinates at a short interval (such as 10 milliseconds).

After adding the timer, double click it so that we get to its single event - Tick - and use the following piece of code which calls the Windows API function and updates the two labels:

// New point that will be updated by the function with the current coordinates

Point defPnt = newPoint();

// Call the function and pass the Point, defPnt

GetCursorPos(ref defPnt);

// Now after calling the function, defPnt contains the coordinates which we can read

lblCoordX.Text = "X = " + defPnt.X.ToString();

lblCoordY.Text = "Y = " + defPnt.Y.ToString();

Counting traveled pixels

Trying to make this application fun, I decided to calculate the total pixels the mouse travels, more exactly to make a counter.

First declare 5 more variables:

static protected long totalPixels = 0;

static protected int currX;

static protected int currY;

static protected int diffX;

static protected int diffY;

Add one more label to the Form (lblTravel), and a button (btnReset). Now inside the Tick event of the Timer, after the labels showing the X and Y coordinates are updated, use the following code:

// If the cursor has moved at all

if (diffX != defPnt.X | diffY != defPnt.Y)

{

// Calculate the distance of movement (in both vertical and horizontal movement)

diffX = (defPnt.X - currX);

diffY = (defPnt.Y - currY);

// The difference will be negative if the cursor was moved left or up

// and if it is so, make the number positive

if (diffX < 0)

{

diffX *= -1;

}

if (diffY < 0)

{

diffY *= -1;

}

// Add to the "pixels traveled" counter

totalPixels += diffX + diffY;

// And display inside a label

lblTravel.Text = "You have traveled " + totalPixels + " pixels";

}

// We need this to see the difference of pixels between two mouse movements

currX = defPnt.X;

currY = defPnt.Y;

Now to complete the application, double click the btnReset button to get to the Click event , and use the following line to reset the counter variable:

if (diffX != defPnt.X | diffY != defPnt.Y)
is wrong, should be:
if (currX != defPnt.X | currY != defPnt.Y)
Otherwise it runs every time once the timer has started.

by James on Friday, September 29th 2006 at 12:57 PM

Could this be converted to a console app and have the output displayed to the console window?

Thanks.

by Andrei Pociu on Friday, September 29th 2006 at 01:35 PM

Yes, since this does not retrieve the coordinates relative to a form, but relative to the entire desktop via GetCursorPos().

by Bojan Gajic on Wednesday, May 2nd 2007 at 02:03 PM

did you try low-level hooks?
http://www.codeproject.com/csharp/globalhook.asp

by tan th on Thursday, August 23rd 2007 at 02:21 AM

how do you have the coordinates (X, Y) with decimal places, instead of being a integer?

by Andrei Pociu on Thursday, August 23rd 2007 at 09:20 AM

The coordinates are exact integers as they relate to the number of pixels on the screen. Therefore you will never have a coordinate that is 879.31 for instance, so you don't need to retrieve the decimal places. The decimal places will always be zeros.

by prabhat singh on Friday, April 4th 2008 at 08:47 AM

Can I add SetcurPos() in a similar way to change cursor position with my code?
what namespaces do i need to use?
.NET C# VS 2008

by Josh on Sunday, September 7th 2008 at 08:18 AM

Yes, you can use SetCursorPos In a very similar way. pinvoke.net has a nice example page:

http://www.pinvoke.net/default.aspx/user32/SetCursorPos.html

by andi on Monday, March 9th 2009 at 08:51 AM

i need to get the cursor position depending on my C# form, not the hole screen; So i need the x and y to be 0, when i go in the left upper corner of the form, not the screen..is that posible?

by Durgesh on Tuesday, April 14th 2009 at 05:23 AM

I need to click button which is on another url in windows application. how can we do this ? i think by taking the co ordinates, it will be helpful ?
Please give some suggestions..

by Mike on Thursday, August 13th 2009 at 06:01 PM

very nice job, congratulations XD

bye

by Jegan on Monday, October 12th 2009 at 06:45 AM

can we get the mouse position without user32.dll because it does not works in patially trusted application.

by Jamel on Thursday, January 28th 2010 at 09:36 PM

timer1.Start();

to show mouse coords as it moves. Put it in Form1().

Thanks for this really helped

by sahani on Wednesday, March 24th 2010 at 09:17 AM

how do i record the mouse path and replay it?? can i store all coordinates that mouse move and replay it??

by Yogesh on Thursday, May 20th 2010 at 04:11 PM

I need to get the text of icon under focus of mouse or under click in c#, what is class and method for this

by Yogesh Bhamare on Thursday, May 20th 2010 at 04:11 PM

I need to get the text of icon under focus of mouse or under click in c#, what is class and method for this

by Navtej Singh on Saturday, June 26th 2010 at 05:53 AM

great code ....
very helpful ....

by sivakumar on Friday, December 24th 2010 at 12:43 AM

Thank you very much,

This is what i want, Excellent!!

by Waqas Mahmood on Thursday, March 31st 2011 at 07:22 AM

Many Thank Andrew .. Works Perfect for me too..

by chaima on Monday, May 2nd 2011 at 06:53 AM

verry good job , thx a loot :)

by chethan on Saturday, August 6th 2011 at 09:45 AM

hi i get this one... but i want the tool tip information when any mouse event happn outside my application like click or hover events.. plz help me..

by chethan on Tuesday, August 9th 2011 at 11:07 AM

plz help me.. if my curser pointer go on any icon or any button means that name is stored in that tooltip how can i get that name to my program in c#.net ...

plz plz help me....

by apply for credit card on Monday, December 12th 2011 at 05:26 AM

Use System.Windows.Forms.Cursor.Position to get the cursor position in screen coordinates.I admire the important information you offer within your content. I'll bookmark your web site and have my kids examine up the following typically.

by on Saturday, January 14th 2012 at 02:11 AM

Once you have recreated the problem and captured these steps, you can save them to a file and send it to your support person, who can then open it up and view