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.
asked Aug 22, 2009 at 18:34
1
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;
}
answered Apr 7, 2011 at 7:36
Mo0glesMo0gles
10.5k2 gold badges21 silver badges15 bronze badges
6
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.3k36 gold badges106 silver badges124 bronze badges
answered Aug 22, 2009 at 18:47
adrianbanksadrianbanks
81.4k22 gold badges176 silver badges206 bronze badges
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)
answered Oct 15, 2012 at 19:55
Benjamin CrouzierBenjamin Crouzier
40.4k44 gold badges172 silver badges236 bronze badges
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);
answered Dec 17, 2018 at 6:26
ArtfaithArtfaith
1,1824 gold badges19 silver badges29 bronze badges
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;
}
}
answered Nov 24, 2017 at 21:42
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;
answered Jul 14, 2016 at 13:21
DeathRsDeathRs
1,10017 silver badges22 bronze badges
brony 77 / 57 / 4 Регистрация: 02.01.2012 Сообщений: 521 |
|
1 |
|
Как получить координаты курсора мыши08.06.2012, 16:58. Показов 114722. Ответов 19
1) как получить координаты курсора мыши?
0 |
CIRWOS 51 / 37 / 6 Регистрация: 16.04.2012 Сообщений: 51 Записей в блоге: 5 |
||||
08.06.2012, 17:07 |
2 |
|||
Сообщение было отмечено как решение Решение
10 |
brony 77 / 57 / 4 Регистрация: 02.01.2012 Сообщений: 521 |
|
08.06.2012, 17:17 [ТС] |
3 |
Какой обработчик событий надо поставить что бы отлавливать любое перемещение курсора в области формы? Судя по всему, MouseMove не для этого.
0 |
Goal Футболист 532 / 434 / 142 Регистрация: 31.10.2011 Сообщений: 1,010 |
||||
08.06.2012, 17:22 |
4 |
|||
MouseMove подходит Активируем событие «MouseMove» и в обработчик занесём код:
Здесь е.Х и е.У — горизонтальные и вертикальные координаты указателя мыши
0 |
ncuX1 brony 77 / 57 / 4 Регистрация: 02.01.2012 Сообщений: 521 |
||||||||||||
08.06.2012, 17:27 [ТС] |
5 |
|||||||||||
MouseMove подходит У меня форма без бордюра, разтянута на весь экран.
в Form1.Designer.cs
После включения приложения при вождении мыши по пространству формы ничего не происходит, следовательно: либо я делаю что-то не так, либо не тот ивент
0 |
Футболист 532 / 434 / 142 Регистрация: 31.10.2011 Сообщений: 1,010 |
|
08.06.2012, 17:33 |
6 |
мб я и не прав, но моусмув отвечает за передвижение курсора именно в форме, попробуй
0 |
brony 77 / 57 / 4 Регистрация: 02.01.2012 Сообщений: 521 |
|
08.06.2012, 17:39 [ТС] |
7 |
мб я и не прав, но моусмув отвечает за передвижение курсора именно в форме, попробуй Вот странно, на пустом проекте работает, на моём- нет.
0 |
Футболист 532 / 434 / 142 Регистрация: 31.10.2011 Сообщений: 1,010 |
|
08.06.2012, 17:42 |
8 |
Создай новый проект
0 |
brony 77 / 57 / 4 Регистрация: 02.01.2012 Сообщений: 521 |
|
08.06.2012, 19:32 [ТС] |
9 |
всем спасибо за помощь
0 |
6 / 6 / 2 Регистрация: 08.05.2012 Сообщений: 116 |
|
08.06.2012, 23:18 |
10 |
а как сделать, чтобы он постоянно отслеживал положение?
0 |
51 / 37 / 6 Регистрация: 16.04.2012 Сообщений: 51 Записей в блоге: 5 |
|
08.06.2012, 23:21 |
11 |
а как сделать, чтобы он постоянно отслеживал положение? Поработайте с таймером или с Form_MouseMove.
1 |
_Катерина_ 0 / 0 / 0 Регистрация: 08.06.2012 Сообщений: 3 |
||||
08.06.2012, 23:25 |
12 |
|||
Свою старую лабу нашла, может поможет!
0 |
6 / 6 / 2 Регистрация: 08.05.2012 Сообщений: 116 |
|||||
08.06.2012, 23:41 |
13 |
||||
Этот код разве языка C#? О_о
0 |
brony 77 / 57 / 4 Регистрация: 02.01.2012 Сообщений: 521 |
|
08.06.2012, 23:53 [ТС] |
14 |
Это делфи. Как то совсем не в тему.
0 |
CIRWOS 51 / 37 / 6 Регистрация: 16.04.2012 Сообщений: 51 Записей в блоге: 5 |
||||
09.06.2012, 00:02 |
15 |
|||
0 |
Goal Футболист 532 / 434 / 142 Регистрация: 31.10.2011 Сообщений: 1,010 |
||||||||
09.06.2012, 00:34 |
16 |
|||||||
MouseMove подходит Активируем событие «MouseMove» и в обработчик занесём код:
Здесь е.Х и е.У — горизонтальные и вертикальные координаты указателя мыши вот так(в форме) Добавлено через 54 секунды
MouseEventArgs e тут зачем по твоему?
0 |
51 / 37 / 6 Регистрация: 16.04.2012 Сообщений: 51 Записей в блоге: 5 |
|
09.06.2012, 00:58 |
17 |
Извиняюсь, тупанул.
0 |
0 / 0 / 0 Регистрация: 08.06.2012 Сообщений: 3 |
|
09.06.2012, 08:43 |
18 |
Это делфи. Как то совсем не в тему. Не знаю как для вас, но для меня важен алгоритм, а переделать можно и под любой язык!
0 |
3 / 3 / 1 Регистрация: 26.06.2013 Сообщений: 14 |
|
25.12.2013, 14:31 |
19 |
Мне товарищ на днях предложил написать бота для свей игрушки вк.
0 |
Заблокирован |
|
11.03.2014, 23:21 |
20 |
Добавить в браузер тот же ивент
0 |
IT_Exp Эксперт 87844 / 49110 / 22898 Регистрация: 17.06.2006 Сообщений: 92,604 |
11.03.2014, 23:21 |
20 |
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.
asked Aug 22, 2009 at 18:34
1
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;
}
answered Apr 7, 2011 at 7:36
Mo0glesMo0gles
10.5k2 gold badges21 silver badges15 bronze badges
6
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.3k36 gold badges106 silver badges124 bronze badges
answered Aug 22, 2009 at 18:47
adrianbanksadrianbanks
81.4k22 gold badges176 silver badges206 bronze badges
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)
answered Oct 15, 2012 at 19:55
Benjamin CrouzierBenjamin Crouzier
40.4k44 gold badges172 silver badges236 bronze badges
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);
answered Dec 17, 2018 at 6:26
ArtfaithArtfaith
1,1824 gold badges19 silver badges29 bronze badges
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;
}
}
answered Nov 24, 2017 at 21:42
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;
answered Jul 14, 2016 at 13:21
DeathRsDeathRs
1,10017 silver badges22 bronze badges
- Windows Form Application
- Get Mouse Position on the Screen 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:
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:
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.
Maybe the most simple way is setting Capture
property of a form to true
, then handle click event and convert the position (that is position related to top left point of form) to screen position using PointToScreen
method of form.
For example you can put a button on form and do:
private void button1_Click(object sender, EventArgs e)
{
//Key Point to handle mouse events outside the form
this.Capture = true;
}
private void MouseCaptureForm_MouseDown(object sender, MouseEventArgs e)
{
this.Activate();
MessageBox.Show(this.PointToScreen(new Point(e.X, e.Y)).ToString());
//Cursor.Position works too as RexGrammer stated in his answer
//MessageBox.Show(this.PointToScreen(Cursor.Position).ToString());
//if you want form continue getting capture, Set this.Capture = true again here
//this.Capture = true;
//but all clicks are handled by form now
//and even for closing application you should
//right click on task-bar icon and choose close.
}
But more correct (and slightly difficult) way is using global hooks.
If you really need to do it, you can take a look at this links:
- Processing Global Mouse and Keyboard Hooks in C#
- Low-Level Mouse Hook in C#
- Application and Global Mouse and Keyboard Hooks .Net Libary in C#