How to Get Mouse Position Using C#

Naila Saad Siddiqui Feb 02, 2024
  1. Windows Form Application
  2. Get Mouse Position on the Screen Using C#
How to Get Mouse Position Using C#

This brief programming tutorial is about getting a mouse position in C# Windows Form Applications.

Windows Form Application

An application created specifically to run on a computer is the Windows Form application. It won’t function in a web browser as it is a desktop-based application.

There can be numerous controls on a Windows Form application. It can consist of interconnected screens containing different controls like buttons, text boxes, labels, etc.

Get Mouse Position on the Screen Using C#

Sometimes, in scenarios where interactivity is the highest priority, we often need to get the mouse cursor’s current position. Our screen is measured in x and y coordinates, so we can get the mouse position by obtaining the x-coordinate and the y-coordinate of the mouse pointer position.

In C#, we can use the class Cursor to get the mouse pointer position. This will return the current position of the mouse pointer as compared to the whole screen.

If we need to get the position specific to that current window, we can call the function ScreenToClient(). This function takes in a Point object containing the x and y coordinates and returns a Point object with respect to the current window screen.

First, create a new Windows Form application in Visual Studio.

In that application, Form1.cs will be created by default. In that file, create two text boxes like this:

C# Get Mouse Position - Step 1

In the corresponding cs file, i.e., Form1.cs, we can write the code for getting the mouse position like this:

Point p = PointToClient(Cursor.Position);
textBox1.Text = p.X.ToString();
textBox2.Text = p.Y.ToString();

This function will set the value basis on the pointer position when the function is called. Later on, if we move the mouse pointer, it will not change its value.

To do so, we can write this code in an onMouseMove event handler.

protected override void OnMouseMove(MouseEventArgs e) {
  Point p = PointToClient(Cursor.Position);
  textBox1.Text = p.X.ToString();
  textBox2.Text = p.Y.ToString();
}

The effect will be that the value will (accordingly) change whenever we have the pointer after running the app.

Let us attach two instances of the output screen:

C# Get Mouse Position - Output 1

C# Get Mouse Position - Output 2

You can see from both the output screens that the position value changes while moving the cursor. This position value is with respect to the current screen.

This way, we can get the current mouse position in a C# .NET code and use it for further programming tasks.

Related Article - Csharp Mouse