- Mouse. Get Position(IInputElement) Метод
- Определение
- Параметры
- Возвращаемое значение
- Примеры
- Комментарии
- Control. Mouse Position Свойство
- Определение
- Значение свойства
- Примеры
- Комментарии
- Getting mouse position in a Windows application
- 1 Answer 1
- Getting mouse cursor position and button state on Windows
- 2 Answers 2
- How do I get the current mouse screen coordinates in WPF?
- 8 Answers 8
Mouse. Get Position(IInputElement) Метод
Определение
Получает позицию указателя мыши относительно заданного элемента. Gets the position of the mouse relative to a specified element.
Параметры
Пространство координат для вычисления позиции указателя мыши. The coordinate space in which to calculate the position of the mouse.
Возвращаемое значение
Позиция указателя мыши относительно параметра relativeTo . The position of the mouse relative to the parameter relativeTo .
Примеры
В следующем примере показано, как использовать GetPosition для определения позиции указателя мыши. The following example shows how to use GetPosition to determine the position of the mouse pointer. Расположение указателя мыши хранится в Point структуре. The position of the mouse pointer is stored in a Point structure. XЗначения и Y Point объекта отображаются в TextBox . The X and Y values of the Point object are displayed in a TextBox.
Комментарии
Положение указателя мыши вычисляется относительно указанного элемента с верхним левым углом элемента, равным точке происхождения, 0, 0. The position of the mouse pointer is calculated relative to the specified element with the upper-left corner of element being the point of origin, 0,0.
Во время операций перетаскивания не удается надежно определить расположение мыши с помощью GetPosition . During drag-and-drop operations, the position of the mouse cannot be reliably determined through GetPosition. Это связано с тем, что управление мышью (возможно, включая захват) удерживается исходным элементом перетаскивания до тех пор, пока не завершится перетаскивание, и большая часть поведения управляется базовыми вызовами Win32. This is because control of the mouse (possibly including capture) is held by the originating element of the drag until the drop is completed, with much of the behavior controlled by underlying Win32 calls. Вместо этого попробуйте выполнить следующие подходы. Try the following approaches instead:
Вызовите GetPosition метод объекта DragEventArgs , который передается в события перетаскивания ( DragEnter , DragOver , DragLeave ). Call the GetPosition method of the DragEventArgs that is passed to the drag events (DragEnter, DragOver, DragLeave).
Вызовите жеткурсорпос, используя P/Invoke. Call GetCursorPos, using P/Invoke.
Control. Mouse Position Свойство
Определение
Возвращает позицию указателя мыши в экранных координатах. Gets the position of the mouse cursor in screen coordinates.
Значение свойства
Объект Point содержит координаты указателя мыши относительно левого верхнего угла экрана. A Point that contains the coordinates of the mouse cursor relative to the upper-left corner of the screen.
Примеры
Следующий пример кода помещает TreeNode метку в изменяемое состояние, когда пользователь нажимает ALT + E, когда указатель мыши находится над узлом дерева. The following code example puts a TreeNode label into an editable state when the user presses ALT+E while the mouse cursor is over the tree node. После того как пользователь закончит редактирование метки, метки нельзя будет изменить, пока не будет нажата комбинация клавиш ALT + E. After the user is done editing the label, the labels cannot be edited again until the ALT+E key combination is pressed again. В этом примере требуется наличие TreeView в Form . This example requires that you have a TreeView on a Form. Представление в виде дерева также должно иметь по крайней мере одно значение TreeNode в Nodes коллекции. The tree view should also have at least one TreeNode in its Nodes collection.
Комментарии
MousePositionСвойство возвращает объект Point , представляющий позицию курсора мыши во время ссылки на свойство. The MousePosition property returns a Point that represents the mouse cursor position at the time the property was referenced. Координаты указывают позицию на экране, а не относительно элемента управления и возвращаются, независимо от того, наведен ли курсор на элемент управления. The coordinates indicate the position on the screen, not relative to the control, and are returned regardless of whether the cursor is positioned over the control. Координаты левого верхнего угла экрана равны 0, 0. The coordinates of the upper-left corner of the screen are 0,0.
Getting mouse position in a Windows application
I’m coding a simple game engine with DirectX11 and I’m using Win32 API to create a window and process user input. I’m implementing a ray casting routine to pick and place entities on a terrain, and all works fine except that when I try to place something on the ground it has a weird offset to the top and to the left:
After quite a bit of debugging I found out that my code works fine, and the issue is with the window coordinates that I send to the ray casting class/function:
The coordinates of the mouse cursor are not between 0 and the window width/height (1024 X 768 in my case), but the maximum width is 1004 and the maximum height is 718 (more or less when I click on the bottom right corner of the window), that’s what I read when I debug the application.
A final prove of that is that if I use those width and height in my code, objects are placed where they should. So my question is, how come the coordinates don’t cover the whole window size? Am I missing something/ doing something wrong? How can I get correct coordinates?
EDIT
my function requires client area coordinates, the coordinates of the mouse cursor INSIDE the window, of course.
EDIT EDIT
this is the code I use to create the window
1 Answer 1
The coordinates you receive from WM_LBUTTONDOWN are client coordinates, and are correct. The real issue here stems from the difference between the window area and client area.
The window area contains the whole window, including the title bar and borders. The RECT you would get from GetWindowRect is exactly large enough to cover every pixel of your window, such that superimposing a black box of that size on the screen would cause your entire window, title bar and borders included, to disappear.
The client area, however, is the area inside the borders Windows creates for you. The RECT you would get from GetClientRect is just large enough that, again, superimposing a black box of that size on the screen would cover your entire 3D scene, but leave the title bar and borders visible.
The theory and definitions here are all well and good, but now we need to solve the problem. It turns out, the code you have in your window procedure, aside from the API compliance issues noted by Remy Lebeau (use GET_X_LPARAM() / GET_Y_LPARAM() instead of shifting), is perfectly fine, and needs no modification. The actual point where you introduce the error is during your window creation code.
The nWidth and nHeight parameters to CreateWindow specify the width and height of the window, not the client area. As such, your client area will be smaller. However, you want the client area to have those widths.
Turns out, this is such a common occurence that Windows 2000 added a function to generate the proper window width and height for a given client area: AdjustWindowRect . To use it, change your CreateWindow call to the following:
This will offset your coordinates to ensure that the client area is exactly the size the DisplayManager thinks it should be.
EDIT
If you have an extended window style, AdjustWindowRectEx allows you to specify those extended window styles as an additional fourth argument to the function.
Getting mouse cursor position and button state on Windows
What is the most appropriate way of getting the mouse cursor position or button state on Windows (Windows 7 and above)? I previously used DirectInput, but I am not longer using it and do not wish to. I saw there is GetCursorPos, however, I do not see anything for getting mouse button states. I have read previously that just reading the window messages (such as WM_LBUTTONUP) was considered «slow» for real time applications, so I do not know of any other option.
2 Answers 2
If you want to poll/query the current cursor position, you can use GetCursorPos. To see the button states, use GetAsyncKeyState.
If you are implementing a message loop in a window, the notification you will get for a mouse movement is WM_MOUSEMOVE. You will be notified of mouse inputs through the notifications listed here.
WM_LBUTTONUP is as good as any window message, for windowed games is great because it is generated only when the mouse clicks the client area, so you can resize and move the window freely.
As an alternative to direct input, you can use raw inputs which take up some more code to initialize, but it’s the best way to go with the mouse movement since WM_INPUT is generated when the physical mouse moves, not the cursor, so you can clip the cursor in the client area without worrying that the user may hit the side of the clip rect and the mouse movement messages won’t be generated anymore. link
How do I get the current mouse screen coordinates in WPF?
How to get current mouse coordination on the screen? I know only Mouse.GetPosition() which get mousePosition of element, but I want to get the coordination without using element.
8 Answers 8
To follow up on Rachel’s answer.
Here’s two ways in which you can get Mouse Screen Coordinates in WPF.
1.Using Windows Forms. Add a reference to System.Windows.Forms
Or in pure WPF use PointToScreen.
Sample helper method:
Do you want coordinates relative to the screen or the application?
If it’s within the application just use:
If not, I believe you can add a reference to System.Windows.Forms and use:
If you try a lot of these answers out on different resolutions, computers with multiple monitors, etc. you may find that they don’t work reliably. This is because you need to use a transform to get the mouse position relative to the current screen, not the entire viewing area which consists of all your monitors. Something like this. (where «this» is a WPF window).
This works without having to use forms or import any DLLs:
You may use combination of TimerDispatcher (WPF Timer analog) and Windows «Hooks» to catch cursor position from operational system.
Point is a light struct . It contains only X, Y fields.
This solution is also resolving the problem with too often or too infrequent parameter reading so you can adjust it by yourself. But remember about WPF method overload with one arg which is representing ticks not milliseconds .
If you’re looking for a 1 liner, this does well.