MFC 对话框上绘制可拖拽放大缩小的框
要在 MFC 对话框上自由绘制多个框并实现点击拖拽和放大缩小,可以按照以下步骤进行:
-
在资源视图中添加一个自定义控件(例如,IDC_CUSTOM_CONTROL),用于绘制框。
-
在对话框类的头文件中添加成员变量来保存绘制框的位置和大小信息:
CRect m_rect; // 绘制框的位置和大小
bool m_bDragging; // 是否正在拖拽
- 在对话框类的 OnInitDialog() 函数中初始化成员变量:
m_rect.SetRectEmpty();
m_bDragging = false;
- 在对话框类的头文件中添加以下成员函数来处理绘制框和鼠标事件:
afx_msg void OnPaint(); // 绘制框
afx_msg void OnLButtonDown(UINT nFlags, CPoint point); // 鼠标左键按下
afx_msg void OnLButtonUp(UINT nFlags, CPoint point); // 鼠标左键释放
afx_msg void OnMouseMove(UINT nFlags, CPoint point); // 鼠标移动
- 在对话框类的源文件中添加消息映射:
BEGIN_MESSAGE_MAP(CMyDialog, CDialogEx)
ON_WM_PAINT()
ON_WM_LBUTTONDOWN()
ON_WM_LBUTTONUP()
ON_WM_MOUSEMOVE()
END_MESSAGE_MAP()
- 在对话框类的源文件中实现成员函数:
void CMyDialog::OnPaint()
{
CPaintDC dc(this);
if (!m_rect.IsRectEmpty())
{
dc.Rectangle(m_rect);
}
}
void CMyDialog::OnLButtonDown(UINT nFlags, CPoint point)
{
if (m_rect.PtInRect(point))
{
m_bDragging = true;
SetCapture();
}
}
void CMyDialog::OnLButtonUp(UINT nFlags, CPoint point)
{
if (m_bDragging)
{
m_bDragging = false;
ReleaseCapture();
}
}
void CMyDialog::OnMouseMove(UINT nFlags, CPoint point)
{
if (m_bDragging)
{
CRect rectClient;
GetClientRect(&rectClient);
ClientToScreen(&rectClient);
m_rect.MoveToXY(
max(rectClient.left, min(rectClient.right - m_rect.Width(), point.x)),
max(rectClient.top, min(rectClient.bottom - m_rect.Height(), point.y))
);
Invalidate();
}
}
- 在 OnInitDialog() 函数中设置自定义控件的风格为可重绘(重写 OnEraseBkgnd() 函数):
CWnd* pCustomControl = GetDlgItem(IDC_CUSTOM_CONTROL);
pCustomControl->SetWindowLong(pCustomControl->GetSafeHwnd(), GWL_STYLE, WS_VISIBLE | WS_CHILD | WS_CLIPCHILDREN | WS_CLIPSIBLINGS);
- 在对话框类的源文件中重写 OnEraseBkgnd() 函数以避免闪烁:
BOOL CMyDialog::OnEraseBkgnd(CDC* pDC)
{
return TRUE;
}
这样,你就可以在 MFC 对话框上自由绘制多个框,并实现点击拖拽和放大缩小的功能了。
原文地址: https://www.cveoy.top/t/topic/o4rt 著作权归作者所有。请勿转载和采集!