Here is an example C++ code that demonstrates how to implement dragging a window using its client area:
#include <windows.h>
// Global variables
bool isDragging{ false };
POINT mouseOffset;
// WindowProc callback function
LRESULT CALLBACK WindowProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
// Main entry point
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
// Register window class
WNDCLASSEX wc = { sizeof(WNDCLASSEX) };
wc.style = CS_HREDRAW | CS_VREDRAW;
wc.lpfnWndProc = WindowProc;
wc.hInstance = hInstance;
wc.hCursor = LoadCursor(nullptr, IDC_ARROW);
wc.hbrBackground = reinterpret_cast<HBRUSH>(COLOR_WINDOW + 1);
wc.lpszClassName = "MyWindowClass";
RegisterClassEx(&wc);
// Create window
HWND hWnd = CreateWindowEx(0, "MyWindowClass", "My Window", WS_OVERLAPPEDWINDOW | WS_VISIBLE, CW_USEDEFAULT, CW_USEDEFAULT, 640, 480, nullptr, nullptr, hInstance, nullptr);
if (hWnd == nullptr)
{
return -1;
}
// Message loop
MSG msg{};
while (GetMessage(&msg, nullptr, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return static_cast<int>(msg.wParam);
}
// WindowProc callback function implementation
LRESULT CALLBACK WindowProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch (msg)
{
case WM_LBUTTONDOWN:
{
// Record the offset of the mouse from the top-left corner of the window
POINT pos{ GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam) };
RECT rect;
GetClientRect(hWnd, &rect);
ClientToScreen(hWnd, &pos);
mouseOffset = { pos.x - rect.left, pos.y - rect.top };
// Set the flag indicating that the window is being dragged
isDragging = true;
}
return 0;
case WM_MOUSEMOVE:
{
// Check if the window is being dragged
if (isDragging)
{
// Calculate the new position of the window based on the mouse offset
POINT pos{ GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam) };
RECT rect;
GetWindowRect(hWnd, &rect);
MoveWindow(hWnd, pos.x - mouseOffset.x, pos.y - mouseOffset.y, rect.right - rect.left, rect.bottom - rect.top, TRUE);
}
}
return 0;
case WM_LBUTTONUP:
// Unset the flag indicating that the window is being dragged
isDragging = false;
return 0;
case WM_DESTROY:
PostQuitMessage(0);
return 0;
default:
return DefWindowProc(hWnd, msg, wParam, lParam);
}
}
In this example, WM_LBUTTONDOWN, WM_MOUSEMOVE, and WM_LBUTTONUP messages are handled to enable dragging of the window using its client area. The isDragging flag is used to track whether the window is being dragged. The mouseOffset is used to record the offset of the mouse from the top-left corner of the window when the WM_LBUTTONDOWN message is triggered, so that the new position of the window can be calculated correctly when the WM_MOUSEMOVE message is triggered. The MoveWindow function is used to move the window to the new location. Note that the ClientToScreen function is used to convert the mouse position from client coordinates to screen coordinates before calculating the mouse offset.