正如前面的几节中我们讲述的, Windows是由一系列的窗体组合而成,而Windows在对一个窗体操作前需要得到这个窗体的句柄,那如何读取一个窗休的句柄呢,Windows提供了许多的函数来达到这样的目的,今天我们先了学习最常用和直接的二个方法:
(一) 函数声明
HWND FindWindowEx(HWND hwndParent, HWND hwndChildAfter, LPCTSTR lpszClass, LPCTSTR lpszWindow );
获取与窗体的类名和窗体名相匹配的窗休句柄,此函数在搜索子窗体时以指定的子窗体句柄开始进行, 当后三参数都为NULL时返回此窗体的第一个子窗体
HWND FindWindow(LPCTSTR lpClassName, LPCTSTR lpWindowName );
获取与窗体的类名和窗体名相匹配的窗休句柄,此函数只用于查找顶层窗体,它是FindWindowEx更高级的版本
Code1: 以下代码演示了:
1. 通过FindWindow查找NotePad主窗体(顶层窗体)
2. 从NotePad主窗体中查找其子控件Edit;
3. 发送字串文本到NotePad子控件Edit中.
HWND hWndNotePad = FindWindow(_T("Notepad"), NULL);
if (NULL != hWndNotePad && IsWindow(hWndNotePad))
{
SetWindowText(hWndNotePad, _T("I come from Demo0024"));
HWND hWndEdit = FindWindowEx(hWndNotePad, NULL, _T("Edit"), NULL);
if (NULL != hWndEdit && IsWindow(hWndEdit))
{
const TCHAR* szText = _T("This string is writed by Demo0024 program");
SendMessage(hWndEdit, WM_SETTEXT, (WPARAM)_tcslen(szText) * sizeof(TCHAR), (LPARAM)szText);
MessageBox(hWndNotePad, _T("Demo0024 rename for me"), _T("I come from Demo0024"), MB_OK);
}
}
if (NULL != hWndNotePad && IsWindow(hWndNotePad))
{
SetWindowText(hWndNotePad, _T("I come from Demo0024"));
HWND hWndEdit = FindWindowEx(hWndNotePad, NULL, _T("Edit"), NULL);
if (NULL != hWndEdit && IsWindow(hWndEdit))
{
const TCHAR* szText = _T("This string is writed by Demo0024 program");
SendMessage(hWndEdit, WM_SETTEXT, (WPARAM)_tcslen(szText) * sizeof(TCHAR), (LPARAM)szText);
MessageBox(hWndNotePad, _T("Demo0024 rename for me"), _T("I come from Demo0024"), MB_OK);
}
}