Windows forms 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.

asked Aug 22, 2009 at 18:34

Athiwat Chunlakhan's user avatar

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

Mo0gles's user avatar

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's user avatar

ljs

37.3k36 gold badges106 silver badges124 bronze badges

answered Aug 22, 2009 at 18:47

adrianbanks's user avatar

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 Crouzier's user avatar

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

Artfaith's user avatar

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

Carlos Alberto Flores Onofre's user avatar

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

DeathRs's user avatar

DeathRsDeathRs

1,10017 silver badges22 bronze badges

brony

77 / 57 / 4

Регистрация: 02.01.2012

Сообщений: 521

1

Как получить координаты курсора мыши

08.06.2012, 16:58. Показов 114722. Ответов 19


Студворк — интернет-сервис помощи студентам

1) как получить координаты курсора мыши?
2) как скрыть отображение мыши?
3) как установить положение курсора?



0



CIRWOS

51 / 37 / 6

Регистрация: 16.04.2012

Сообщений: 51

Записей в блоге: 5

08.06.2012, 17:07

2

Лучший ответ Сообщение было отмечено как решение

Решение

C#
1
2
3
4
5
6
7
8
9
10
11
//Получаем координаты курсора
int CursorX = Cursor.Position.X;
int CursorY = Cursor.Position.Y;
 
textBox.Text = CursorX.ToString() + "   " + CursorY.ToString();
 
//Скрываем курсор
Cursor.Hide();
 
//Установка положения курсора
Cursor.Position = new Point(128, 128);



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» и в обработчик занесём код:

C#
1
label3.Text = e.X.ToString() + " " + e.Y.ToString();

Здесь е.Х и е.У — горизонтальные и вертикальные координаты указателя мыши



0



ncuX1

brony

77 / 57 / 4

Регистрация: 02.01.2012

Сообщений: 521

08.06.2012, 17:27

 [ТС]

5

Цитата
Сообщение от Goal
Посмотреть сообщение

MouseMove подходит

У меня форма без бордюра, разтянута на весь экран.

C#
1
2
3
4
5
6
7
8
   
public RC_form()
        {
            InitializeComponent();
          
            ...
            this.MouseHover += new System.EventHandler(this.RC_form_MouseHover);
        }
C#
1
2
3
4
        private void RC_form_MouseMove(object sender, MouseEventArgs e)
        {
MessageBox.Show("move");
        }

в Form1.Designer.cs

C#
1
2
3
4
5
6
7
8
9
10
11
    private void InitializeComponent()
        {
           ...
            // 
            // RC_form
            // 
            ...
            this.MouseMove += new System.Windows.Forms.MouseEventHandler(this.RC_form_MouseMove);
            ...
 
        }

После включения приложения при вождении мыши по пространству формы ничего не происходит, следовательно: либо я делаю что-то не так, либо не тот ивент



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

Цитата
Сообщение от Goal
Посмотреть сообщение

мб я и не прав, но моусмув отвечает за передвижение курсора именно в форме, попробуй

Вот странно, на пустом проекте работает, на моём- нет.



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

Свою старую лабу нашла, может поможет!

Delphi
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
unit Unit1;
 
interface
 
uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;
 
type
  TForm1 = class(TForm)
    Label1: TLabel;
    Label2: TLabel;
    Label3: TLabel;
    Label4: TLabel;
    Label5: TLabel;
    Label6: TLabel;
    procedure FormMouseMove(Sender: TObject; Shift: TShiftState; X,
      Y: Integer);
    procedure FormMouseDown(Sender: TObject; Button: TMouseButton;
      Shift: TShiftState; X, Y: Integer);
  private
    { Private declarations }
  public
    { Public declarations }
  end;
 
var
  Form1: TForm1;
 
implementation
 
{$R *.dfm}
 
procedure TForm1.FormMouseMove(Sender: TObject; Shift: TShiftState; X,
  Y: Integer);
begin
Label5.Caption := IntToStr(x);
Label6.Caption := IntToStr(y);
end;
 
procedure TForm1.FormMouseDown(Sender: TObject; Button: TMouseButton;// определяет какой кнопкой //щелкнули
  Shift: TShiftState; X, Y: Integer);
begin
case button  of
mbLeft:Label4.Caption:='левая';
mbRight:Label4.Caption:='правая';
end;
end;
 
end.



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

C#
1
2
3
4
5
6
7
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
     int CursorX = Cursor.Position.X;
     int CursorY = Cursor.Position.Y;
 
     this.Text = CursorX.ToString() + "   " + CursorY.ToString();
}



0



Goal

Футболист

532 / 434 / 142

Регистрация: 31.10.2011

Сообщений: 1,010

09.06.2012, 00:34

16

Цитата
Сообщение от Goal
Посмотреть сообщение

MouseMove подходит

Активируем событие «MouseMove» и в обработчик занесём код:

C#
1
label3.Text = e.X.ToString() + " " + e.Y.ToString();

Здесь е.Х и е.У — горизонтальные и вертикальные координаты указателя мыши

вот так(в форме)

Добавлено через 54 секунды

Цитата
Сообщение от CIRWOS
Посмотреть сообщение

C#
1
2
3
4
5
6
7
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
     int CursorX = Cursor.Position.X;
     int CursorY = Cursor.Position.Y;
 
     this.Text = CursorX.ToString() + "   " + CursorY.ToString();
}

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

Цитата
Сообщение от ncuX1
Посмотреть сообщение

Это делфи. Как то совсем не в тему.

Не знаю как для вас, но для меня важен алгоритм, а переделать можно и под любой язык!



0



3 / 3 / 1

Регистрация: 26.06.2013

Сообщений: 14

25.12.2013, 14:31

19

Мне товарищ на днях предложил написать бота для свей игрушки вк.
Я сделал большую форму, втулил туда браузер. Когда водишь по форме — событие срабатывает (МаусМув).
Но когда курсор переходит на браузер (втуленый в форму), то событие уже не срабатывает. Можно как-то решить это?



0



ICanHelpU

Заблокирован

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

Athiwat Chunlakhan's user avatar

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

Mo0gles's user avatar

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's user avatar

ljs

37.3k36 gold badges106 silver badges124 bronze badges

answered Aug 22, 2009 at 18:47

adrianbanks's user avatar

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 Crouzier's user avatar

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

Artfaith's user avatar

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

Carlos Alberto Flores Onofre's user avatar

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

DeathRs's user avatar

DeathRsDeathRs

1,10017 silver badges22 bronze badges

  1. Windows Form Application
  2. Get Mouse Position on the Screen Using C#

Get Mouse Position 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:

C# Get Mouse Position - Step 1

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:

C# Get Mouse Position - Output 1

C# Get Mouse Position - Output 2

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#

  • Windows forms c примеры программ
  • Windows forms c для чайников
  • Windows forms c график функции
  • Windows forms c всплывающее окно
  • Windows flight simulator скачать торрент