MFC获取窗口句柄号的六种方法

时间:2021-07-06 00:18:22

今年有一门Windows程序设计课程,老师要求我们找几种获取窗口句柄号的方法,做了一下总结:

CClientDC dc(this);
CString fun1;
//直接获得
fun1.Format("%ld", AfxGetMainWnd()->m_hWnd);
fun1 = "AfxGetMainWnd()->
m_hWnd方法获取句柄号 = " + fun1;
dc.TextOut(20, 50, fun1);
//通过AfxGetApp()间接获得
fun1.Format("
%ld", AfxGetApp()->GetMainWnd()->m_hWnd);
fun1 = "
AfxGetApp()->GetMainWnd()->m_hWnd方法获取句柄号 = " + fun1;
dc.TextOut(20, 70, fun1);
//当前窗口
fun1.Format("
%ld", GetForegroundWindow()->m_hWnd);
fun1 = "
GetForegroundWindow()->m_hWnd 方法获取句柄号 = " + fun1;
dc.TextOut(20, 90, fun1);
//当前活动的窗口句柄
fun1.Format("
%ld", GetActiveWindow()->m_hWnd);
fun1 = "
GetActiveWindow->m_hWnd方法获取句柄号 = " + fun1;
dc.TextOut(20, 110, fun1);
//窗口名
AfxGetMainWnd()->SetWindowText("
我的程序");
CWnd *hwnd = FindWindow(NULL, "
我的程序");
if (hwnd)
{
fun1.Format("
%ld", hwnd->m_hWnd);
fun1 = "
FindWindow(\"GetWinHwnd\" , NULL)->m_hWnd 方法获取句柄号 = " + fun1;
dc.TextOut(20, 130, fun1);
}

//利用GetSafeHwnd()
// CWnd *hwnd = FindWindow(NULL, "我的程序");
if (hwnd)
{
fun1.Format("%ld", hwnd->GetSafeHwnd());
fun1 = "GetSafeHwnd() 方法获取句柄号 = " + fun1;
dc.TextOut(20, 150, fun1);
}