- 1 year ago
How to get absolute mouse position with WM_INPUT set up?
To obtain the absolute mouse position with WM_INPUT
set up in a Windows application, you can utilize the GET_RAWINPUT_DATA
structure and the GetRawInputData
function. Here's an example:
cpp#include <Windows.h>
#include <iostream>
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
if (uMsg == WM_INPUT)
{
UINT dataSize;
GetRawInputData(reinterpret_cast<HRAWINPUT>(lParam), RID_INPUT, nullptr, &dataSize, sizeof(RAWINPUTHEADER));
if (dataSize > 0)
{
RAWINPUT* rawInput = new RAWINPUT[dataSize];
if (GetRawInputData(reinterpret_cast<HRAWINPUT>(lParam), RID_INPUT, rawInput, &dataSize, sizeof(RAWINPUTHEADER)) == dataSize)
{
if (rawInput->header.dwType == RIM_TYPEMOUSE)
{
LONG xPos = rawInput->data.mouse.lLastX;
LONG yPos = rawInput->data.mouse.lLastY;
// Print absolute mouse position
std::cout << "Absolute mouse position: X=" << xPos << ", Y=" << yPos << std::endl;
}
}
delete[] rawInput;
}
}
return DefWindowProc(hwnd, uMsg, wParam, lParam);
}
int main()
{
// Create a window for receiving input messages
const wchar_t* className = L"RawInputWindowClass";
WNDCLASS wc = {};
wc.lpfnWndProc = WindowProc;
wc.lpszClassName = className;
RegisterClass(&wc);
HWND hwnd = CreateWindow(className, L"Raw Input Window", WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, nullptr, nullptr, nullptr, nullptr);
// Register for raw input
RAWINPUTDEVICE rid;
rid.usUsagePage = 0x01;
rid.usUsage = 0x02;
rid.dwFlags = 0;
rid.hwndTarget = hwnd;
if (RegisterRawInputDevices(&rid, 1, sizeof(RAWINPUTDEVICE)) == FALSE)
{
std::cerr << "Failed to register raw input devices." << std::endl;
return 1;
}
// Enter the message loop
MSG msg;
while (GetMessage(&msg, nullptr, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return 0;
}
This example sets up a basic Windows application with a window and a message loop. It registers for raw input mouse messages using RegisterRawInputDevices
. When the WM_INPUT
message is received, the GetRawInputData
function is used to retrieve the mouse input data.
The mouse position is extracted from the RAWINPUT
structure's data.mouse.lLastX
and data.mouse.lLastY
members, which represent the relative movement of the mouse since the last message. To obtain the absolute mouse position, you can keep track of the accumulated movement over time.
In this example, the absolute mouse position is simply printed to the console. You can modify the code to suit your specific needs, such as updating a UI element or performing additional processing.
Remember to compile the code as a Windows application, link against the necessary libraries (e.g., user32.lib
), and handle any error conditions appropriately.