Athiwat Chunlakhan
Athiwat Chunlakhan

Reputation: 7799

Getting mouse position in c#

How do I get the mouse position? I want it in term of screen position.

I start my program I want to set to the current mouse position.

Location.X = ??
Location.Y = ??

Edit: This must happen before the form is created.

Upvotes: 143

Views: 462386

Answers (10)

Serious Angel
Serious Angel

Reputation: 1555

If you need to get current position in form's area (got experimentally), try the following:

Console.WriteLine(
    "Current mouse position in form's area is " + 
    (Control.MousePosition.X - this.Location.X - 8).ToString() +
    "x" + 
    (Control.MousePosition.Y - this.Location.Y - 30).ToString()
);

Although, 8 and 30 integers were found while experimenting. It'd be awesome if someone could explain why exactly these numbers worked.


Also, there's another variant (considering code is in a form's code-behind):

Point cp = PointToClient(Cursor.Position); // Get cursor's position according to form's area
Console.WriteLine("Cursor position: X = " + cp.X + ", Y = " + cp.Y);

Upvotes: 6

Peter Centellini
Peter Centellini

Reputation: 1565

This answer was not eligible at the time the question was asked, but today you can use the static method Mouse.GetPosition(IInputElement) from the namespace System.Windows.Input in the PresentationCore assembly. This is valid from .NET Framework 3.0 and forward. Find more information on https://learn.microsoft.com/en-us/dotnet/api/system.windows.input.mouse.getposition?view=windowsdesktop-6.0#System_Windows_Input_Mouse_GetPosition_System_Windows_IInputElement_

Example:

// displayArea is a StackPanel and txtBoxMousePosition is
// a TextBox used to display the position of the mouse pointer.
Point position = Mouse.GetPosition(displayArea);
txtBoxMousePosition.Text = "X: " + position.X +
    "\n" +
    "Y: " + position.Y;

Upvotes: 1

Mo0gles
Mo0gles

Reputation: 10884

If you don't want to reference Forms you can use interop to get the cursor position:

using System.Runtime.InteropServices;
using System.Windows; // Or use whatever point class you like for the implicit cast operator

/// <summary>
/// Struct representing a point.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct POINT
{
    public int X;
    public int Y;

    public static implicit operator Point(POINT point)
    {
        return new Point(point.X, point.Y);
    }
}

/// <summary>
/// Retrieves the cursor's position, in screen coordinates.
/// </summary>
/// <see>See MSDN documentation for further information.</see>
[DllImport("user32.dll")]
public static extern bool GetCursorPos(out POINT lpPoint);

public static Point GetCursorPosition()
{
    POINT lpPoint;
    GetCursorPos(out lpPoint);
    // NOTE: If you need error handling
    // bool success = GetCursorPos(out lpPoint);
    // if (!success)
        
    return lpPoint;
}

Upvotes: 103

   internal static class CursorPosition {
  [StructLayout(LayoutKind.Sequential)]
  public struct PointInter {
     public int X;
     public int Y;
     public static explicit operator Point(PointInter point) => new Point(point.X, point.Y);       
  }

  [DllImport("user32.dll")]
  public static extern bool GetCursorPos(out PointInter lpPoint);

  // For your convenience
  public static Point GetCursorPosition() {
     PointInter lpPoint;
     GetCursorPos(out lpPoint);
     return (Point) lpPoint;
  }

}

Upvotes: 3

DeathRs
DeathRs

Reputation: 1120

Initialize the current cursor. Use it to get the position of X and Y

this.Cursor = new Cursor(Cursor.Current.Handle);
int posX = Cursor.Position.X;
int posY = Cursor.Position.Y;

Upvotes: 3

James
James

Reputation: 2911

System.Windows.Forms.Control.MousePosition

Gets the position of the mouse cursor in screen coordinates. "The Position property is identical to the Control.MousePosition property."

Upvotes: 15

Benjamin Crouzier
Benjamin Crouzier

Reputation: 41855

To answer your specific example:

// your example
Location.X = Cursor.Position.X;
Location.Y = Cursor.Position.Y;

// sample code
Console.WriteLine("x: " + Cursor.Position.X + " y: " + Cursor.Position.Y);

Don't forget to add using System.Windows.Forms;, and adding the reference to it (right click on references > add reference > .NET tab > Systems.Windows.Forms > ok)

Upvotes: 20

adrianbanks
adrianbanks

Reputation: 82934

Cursor.Position will get the current screen poisition of the mouse (if you are in a Control, the MousePosition property will also get the same value).

To set the mouse position, you will have to use Cursor.Position and give it a new Point:

Cursor.Position = new Point(x, y);

You can do this in your Main method before creating your form.

Upvotes: 26

RichieHindle
RichieHindle

Reputation: 281345

You should use System.Windows.Forms.Cursor.Position: "A Point that represents the cursor's position in screen coordinates."

Upvotes: 214

Kevin LaBranche
Kevin LaBranche

Reputation: 21078

To get the position look at the OnMouseMove event. The MouseEventArgs will give you the x an y positions...

protected override void OnMouseMove(MouseEventArgs mouseEv) 

To set the mouse position use the Cursor.Position property.

http://msdn.microsoft.com/en-us/library/system.windows.forms.cursor.position.aspx

Upvotes: 10

Related Questions