Home >Backend Development >C++ >How to Get the Mouse Position in C#?

How to Get the Mouse Position in C#?

Patricia Arquette
Patricia ArquetteOriginal
2025-01-20 04:16:08922browse

How to Get the Mouse Position in C#?

Getting the Mouse Cursor's Location in C#

This guide demonstrates a simple method to retrieve the current mouse coordinates within a C# application. This is useful for tasks such as aligning UI elements with the cursor or triggering actions based on cursor location.

The Cursor class, found within the System.Windows.Forms namespace, provides the Position property. This property returns a Point object containing the X and Y coordinates of the mouse cursor on the screen.

Here's how to capture the initial mouse position and apply it to a form's location:

<code class="language-csharp">int initialX = System.Windows.Forms.Cursor.Position.X;
int initialY = System.Windows.Forms.Cursor.Position.Y;

this.Location = new Point(initialX, initialY);</code>

The above is the detailed content of How to Get the Mouse Position in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn