例子来自某书…
目标:会用就OK,达到熟悉Win32 API的目的.
1.1 如何通过HWND获得CWnd指针
CWnd::GetSafeHwnd:
Returns the window handle for a window. Returns NULL if the CWnd is not attached to a window or if it is used with a NULL CWnd pointer.
CWnd::FromHandle:
Returns a pointer to a CWnd object when given a handle to a window. If a CWnd object is not attached to the handle, a temporary CWnd object is created and attached.
//获得当前窗口的句柄
HWND hWnd = GetSafeHwnd();
//通过HWND获得CWnd指针
CWnd* pWnd = CWnd::FromHandle(hWnd);
1.2 如何获得应用程序主窗口的指针
使用AfxGetApp获取应用程序指针
//获得应用程序指针
CDemoApp* pApp = (CDemoApp*)AfxGetApp();
//获得主窗口指针
CWnd* pMainWnd = pApp->m_pMainWnd;
1.3 如何获得指定点的窗口
如下代码:
void CDemoDlg::OnMouseMove(UINT nFlags, CPoint point)
{
//获得指定点的窗口
CWnd* pWnd = WindowFromPoint(point);
if (pWnd != NULL)
{
if (IsChild(pWnd))
{
CString strText = _T("");
pWnd->GetWindowText(strText);
SetWindowText(strText);
}
}
CDialog::OnMouseMove(nFlags, point);
}
方法1:WindowFromPoint
A pointer to the window object in which the point lies. It is NULL if no window exists at the given point. The returned pointer may be temporary and should not be stored for later use.
方法2:IsChild(MFC中每个控件都是一个窗体)
Determines whether the specified window is a child window.
方法3:GetWindowText和SetWindowText
获取和设置窗体标题
当鼠标经过TextBox,则IsChild判断为True,在TextBox范围内鼠标移动则更改窗体标题
1.4 如何最大化和最小化窗口
示例如下:
void CDemoDlg::OnTest1()
{
//最大化窗口
SendMessage(WM_SYSCOMMAND, SC_MAXIMIZE, 0);
}
void CDemoDlg::OnTest2()
{
//最小化窗口
SendMessage(WM_SYSCOMMAND, SC_MINIMIZE, 0);
}
void CDemoDlg::OnTest3()
{
//恢复窗口
SendMessage(WM_SYSCOMMAND, SC_RESTORE, 0);
}
WM_SYSCOMMAND 为系统内置的命令,只需要用SendMessage发送预先设置的命令就可以了
1.5 如何关闭窗口
同上,用SendMessage发送预先设置的命令
void CDemoDlg::OnTest()
{
//关闭窗口
SendMessage(WM_SYSCOMMAND,SC_CLOSE, 0);
}
或者直接发送WM_CLOSE
void CDemoDlg::OnTest()
{
//关闭窗口
SendMessage(WM_CLOSE, 0, 0);
}
关闭前确认:
void CDemoDlg::OnClose()
{
//判断是否关闭
if (IDYES == MessageBox(_T("是否关闭窗口?"), NULL, MB_YESNO))
{
CDialog::OnClose();
}
}