MFC 无边框窗体实现用鼠标拖动窗体边缘实现窗体大小变化
时间: 2024-05-18 10:18:45 浏览: 8
你可以重载MFC窗体类的`OnNcHitTest`函数,该函数用于处理非客户区的鼠标消息。具体实现如下:
```cpp
UINT CMyWnd::OnNcHitTest(CPoint point)
{
UINT nHitTest = CWnd::OnNcHitTest(point);
// 如果鼠标在窗口边缘,设置对应的nHitTest值
CRect rc;
GetWindowRect(&rc);
if (point.x >= rc.left && point.x <= rc.left + m_nBorderWidth)
{
if (point.y >= rc.top && point.y <= rc.top + m_nBorderWidth)
nHitTest = HTTOPLEFT; // 左上角
else if (point.y >= rc.bottom - m_nBorderWidth && point.y <= rc.bottom)
nHitTest = HTBOTTOMLEFT; // 左下角
else
nHitTest = HTLEFT; // 左侧
}
else if (point.x >= rc.right - m_nBorderWidth && point.x <= rc.right)
{
if (point.y >= rc.top && point.y <= rc.top + m_nBorderWidth)
nHitTest = HTTOPRIGHT; // 右上角
else if (point.y >= rc.bottom - m_nBorderWidth && point.y <= rc.bottom)
nHitTest = HTBOTTOMRIGHT; // 右下角
else
nHitTest = HTRIGHT; // 右侧
}
else if (point.y >= rc.top && point.y <= rc.top + m_nBorderWidth)
{
nHitTest = HTTOP; // 顶部
}
else if (point.y >= rc.bottom - m_nBorderWidth && point.y <= rc.bottom)
{
nHitTest = HTBOTTOM; // 底部
}
return nHitTest;
}
```
然后你可以在窗体的`OnNcLButtonDown`和`OnMouseMove`消息中处理鼠标拖动事件,具体实现如下:
```cpp
void CMyWnd::OnNcLButtonDown(UINT nHitTest, CPoint point)
{
if (nHitTest == HTTOP || nHitTest == HTBOTTOM || nHitTest == HTLEFT ||
nHitTest == HTRIGHT || nHitTest == HTTOPLEFT || nHitTest == HTTOPRIGHT ||
nHitTest == HTBOTTOMLEFT || nHitTest == HTBOTTOMRIGHT)
{
// 设置捕获鼠标
SetCapture();
// 获取当前窗口大小和鼠标位置
GetWindowRect(&m_rcWnd);
GetCursorPos(&m_ptCursor);
// 记录当前窗口大小和鼠标位置
m_nHitTest = nHitTest;
m_nWidth = m_rcWnd.Width();
m_nHeight = m_rcWnd.Height();
m_ptLast = m_ptCursor;
}
else
{
CWnd::OnNcLButtonDown(nHitTest, point);
}
}
void CMyWnd::OnMouseMove(UINT nFlags, CPoint point)
{
if (GetCapture() == this)
{
// 获取鼠标位置
GetCursorPos(&m_ptCursor);
// 计算窗口大小和位置
int dx = m_ptCursor.x - m_ptLast.x;
int dy = m_ptCursor.y - m_ptLast.y;
CRect rcNew = m_rcWnd;
switch (m_nHitTest)
{
case HTTOP:
rcNew.top += dy;
break;
case HTBOTTOM:
rcNew.bottom += dy;
break;
case HTLEFT:
rcNew.left += dx;
break;
case HTRIGHT:
rcNew.right += dx;
break;
case HTTOPLEFT:
rcNew.left += dx;
rcNew.top += dy;
break;
case HTTOPRIGHT:
rcNew.right += dx;
rcNew.top += dy;
break;
case HTBOTTOMLEFT:
rcNew.left += dx;
rcNew.bottom += dy;
break;
case HTBOTTOMRIGHT:
rcNew.right += dx;
rcNew.bottom += dy;
break;
}
// 限制窗口最小大小为100x100
int nWidth = max(rcNew.Width(), 100);
int nHeight = max(rcNew.Height(), 100);
// 设置窗口大小和位置
SetWindowPos(NULL, rcNew.left, rcNew.top, nWidth, nHeight, SWP_NOZORDER);
m_ptLast = m_ptCursor;
}
else
{
CWnd::OnMouseMove(nFlags, point);
}
}
```
这样就可以通过鼠标拖动窗口边缘来改变窗口大小了。