Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting mouse position in c#

People also ask

What displays the current position of the cursor?

The cursor position is represented by the line number and the character number and signifies where the next character will be displayed. For example, cursor position 1,1 always indicates the upper-leftmost corner position on the terminal. Cursor position 10,30 indicates the 30th character position on the 10th line.

How do you get the mouse position in Qt?

To set or get the position of the mouse cursor use the static methods QCursor::pos() and QCursor::setPos().

What is cursor in C?

1) A cursor is the position indicator on a computer display screen where a user can enter text. In an operating system with a graphical user interface (GUI), the cursor is also a visible and moving pointer that the user controls with a mouse, touch pad, or similar input device.


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


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;
}

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.


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)


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."