c++ 拖动窗口客户区可移动 详细代码 不使用mfc 不使用qt
时间: 2023-12-29 20:06:09 浏览: 91
一个关于窗口拖放的C++程序
如果不使用MFC或Qt等框架,可使用Windows API来实现拖动窗口客户区可移动的效果。以下是一个简单的实现示例:
1. 在窗口类中添加以下代码:
```
// 定义一个变量来记录鼠标是否按下
bool isDragging = false;
// 定义一个变量来记录鼠标按下位置
POINT lastMousePos;
// 处理鼠标按下事件
case WM_LBUTTONDOWN:
// 如果鼠标按下位置在窗口客户区内,则开始拖动
if (PtInRect(&rcClient, pt))
{
isDragging = true;
lastMousePos = pt;
SetCapture(hWnd);
}
break;
// 处理鼠标移动事件
case WM_MOUSEMOVE:
if (isDragging)
{
// 计算鼠标移动的距离
int dx = pt.x - lastMousePos.x;
int dy = pt.y - lastMousePos.y;
// 移动窗口
RECT rcWindow;
GetWindowRect(hWnd, &rcWindow);
rcWindow.left += dx;
rcWindow.top += dy;
MoveWindow(hWnd, rcWindow.left, rcWindow.top, rcWindow.right - rcWindow.left, rcWindow.bottom - rcWindow.top, TRUE);
// 记录当前鼠标位置
lastMousePos = pt;
}
break;
// 处理鼠标释放事件
case WM_LBUTTONUP:
if (isDragging)
{
isDragging = false;
ReleaseCapture();
}
break;
```
2. 在窗口消息处理函数中添加以下代码:
```
case WM_LBUTTONDOWN:
case WM_MOUSEMOVE:
case WM_LBUTTONUP:
OnMouseEvent(hWnd, message, wParam, lParam);
break;
```
3. 实现 `OnMouseEvent` 函数:
```
void OnMouseEvent(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_LBUTTONDOWN:
OnLButtonDown(hWnd, wParam, lParam);
break;
case WM_MOUSEMOVE:
OnMouseMove(hWnd, wParam, lParam);
break;
case WM_LBUTTONUP:
OnLButtonUp(hWnd, wParam, lParam);
break;
}
}
void OnLButtonDown(HWND hWnd, WPARAM wParam, LPARAM lParam)
{
POINT pt = { GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam) };
// 如果鼠标按下位置在窗口客户区内,则开始拖动
if (PtInRect(&rcClient, pt))
{
isDragging = true;
lastMousePos = pt;
SetCapture(hWnd);
}
}
void OnMouseMove(HWND hWnd, WPARAM wParam, LPARAM lParam)
{
if (isDragging)
{
POINT pt = { GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam) };
// 计算鼠标移动的距离
int dx = pt.x - lastMousePos.x;
int dy = pt.y - lastMousePos.y;
// 移动窗口
RECT rcWindow;
GetWindowRect(hWnd, &rcWindow);
rcWindow.left += dx;
rcWindow.top += dy;
MoveWindow(hWnd, rcWindow.left, rcWindow.top, rcWindow.right - rcWindow.left, rcWindow.bottom - rcWindow.top, TRUE);
// 记录当前鼠标位置
lastMousePos = pt;
}
}
void OnLButtonUp(HWND hWnd, WPARAM wParam, LPARAM lParam)
{
if (isDragging)
{
isDragging = false;
ReleaseCapture();
}
}
```
这样,当用户在窗口客户区内按下鼠标左键并移动时,窗口就会跟随鼠标移动。注意,上述代码中的 `rcClient` 需要在窗口类中定义为成员变量或全局变量。
阅读全文