139

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.

Athiwat Chunlakhan
  • 7,589
  • 14
  • 44
  • 72

10 Answers10

208

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

RichieHindle
  • 272,464
  • 47
  • 358
  • 399
100

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;
}
Mo0gles
  • 10,517
  • 2
  • 21
  • 15
  • 2
    How to refer POINT type? – Manish Dubey Jul 19 '16 at 11:49
  • 2
    Add reference to System.Drawing – Bose_geek Jun 04 '17 at 10:09
  • 1
    awesome solution. But you dont need to declare struct POINT. Just use Win32Interop.Structs namespace. – Manpreet Singh Dhillon Apr 04 '20 at 21:51
  • @ManpreetSinghDhillon Is Win32Interop.Structs available in .Net Core? If yes, under which nuget package / system reference? – Kappacake Jun 01 '20 at 14:35
  • @ManpreetSinghDhillon Using your own struct allows you to implicit cast it to whatever Point you use in your code, it's a bit smoother. If Win32Interop.Structs is enough for you then go sure go ahead and use it instead! – Mo0gles Jun 08 '20 at 07:40
  • @Bose_geek sorry if it isn't clear but if you want to use another Point struct you just change that part of the code and reference whatever Point structure/class you want. – Mo0gles Jun 08 '20 at 07:42
25

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.

ljs
  • 37,275
  • 36
  • 106
  • 124
adrianbanks
  • 81,306
  • 22
  • 176
  • 206
20

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)

Benjamin Crouzier
  • 40,265
  • 44
  • 171
  • 236
15
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."

James
  • 2,812
  • 3
  • 22
  • 33
  • 4
    No need to be rude. This is an alternative to the primary answer. I just prefer this one because the other 'Cursor.Position' sounds like a text type cursor IMHO and 'MousePosition' is more obvious. – James Mar 05 '13 at 14:16
  • 3
    @Jan Dvorak sure, and yes I thought it maybe helpful. I would have said something like this "Please could you include a little further information so I can see how this may differ from the answers given previously?" – James Mar 05 '13 at 14:41
  • @JanDvorak If you think one-liners don't help (btw, they do) then its not dependent on if the question is 1 day old or 3 yr old. +1 for alternative approach. – nawfal May 07 '13 at 07:48
10

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

Kevin LaBranche
  • 20,908
  • 5
  • 52
  • 76
6

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);
Artfaith
  • 1,183
  • 4
  • 19
  • 29
4
   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;
  }

}

3

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;
DeathRs
  • 1,100
  • 17
  • 22
1

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;
Peter Centellini
  • 1,287
  • 3
  • 10
  • 11