c++ 拖动窗口客户区可移动 详细代码 不使用mfc 不使用qt 详细代码
时间: 2024-01-12 12:05:11 浏览: 121
以下是使用 Win32 API 实现拖动窗口客户区可移动的详细代码:
```c++
#include <Windows.h>
// 定义全局变量
HINSTANCE hInst;
HWND hWnd;
POINT ptOffset;
// 定义窗口过程
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_CREATE:
// 获取窗口句柄
::hWnd = hWnd;
break;
case WM_NCHITTEST:
// 判断鼠标位置是否在客户区内
if (DefWindowProc(hWnd, message, wParam, lParam) == HTCLIENT)
{
// 获取鼠标位置
POINT ptMouse = { LOWORD(lParam), HIWORD(lParam) };
// 获取窗口位置
RECT rcWnd;
GetWindowRect(hWnd, &rcWnd);
// 计算鼠标相对于窗口左上角的偏移量
ptOffset.x = ptMouse.x - rcWnd.left;
ptOffset.y = ptMouse.y - rcWnd.top;
// 返回可移动的消息
return HTCAPTION;
}
break;
case WM_DESTROY:
// 退出程序
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
// 程序入口
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
// 初始化全局变量
::hInst = hInstance;
// 注册窗口类
WNDCLASSEX wcex = { 0 };
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = LoadIcon(hInstance, IDI_APPLICATION);
wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wcex.lpszMenuName = NULL;
wcex.lpszClassName = "WindowClass";
wcex.hIconSm = LoadIcon(hInstance, IDI_APPLICATION);
RegisterClassEx(&wcex);
// 创建窗口
HWND hWnd = CreateWindow("WindowClass", "Window Title", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 800, 600, NULL, NULL, hInstance, NULL);
if (!hWnd)
{
return FALSE;
}
// 显示窗口
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
// 消息循环
MSG msg = { 0 };
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return (int)msg.wParam;
}
```
以上代码实现了拖动窗口客户区可移动的功能。当鼠标在窗口的客户区内按下并拖动时,窗口会跟着鼠标移动。
阅读全文