通过HWND获得CWnd指针

来源:互联网 发布:初请失业金数据公布 编辑:程序博客网 时间:2024/05/22 12:06
1
2
3
4
5
6
7
//获得当前窗口的句柄
HWND hWnd = GetSafeHwnd();
//通过HWND获得CWnd指针
CWnd *pWnd = CWnd::FromHandle(hWnd);
CString strText = _T("");
strText.Format("pWnd = 0x%X\nthis = 0x%X\n", pWnd, this);
AfxMessageBox(strText);

 

1、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。

这个函数用途很广,很多函数的参数要求是HWND,这时就需要使用GetSafeHwnd函数了。如:

?
1
2
3
4
5
HWND hwnd;
CWnd* pWnd;
pWnd=((CFrameWnd*)(AfxGetApp()->m_pMainWnd))->GetActiveView();
hwnd=pWnd->GetDlgItem(IDC_EDIT2)->GetSafeHwnd();
::SetWindowText(hwnd,m_strResult);

  其它的一些情况:

AfxWinInit         被WinMain调用的一个函数,用做MFC GUI程序初始化的一部份

AfxBeginThread     开始一个新的执行线程

AfxEndThread       结束一个旧的执行线程

AfxMessageBox      类似Windows API 函数MessageBox

AfxGetApp          取得application object(CWinApp衍生对象)的指针

AfxGetMainWnd      取得程序主窗口的指针

AfxGetInstance     取得程序的instance handle

AfxRegisterClass   以自定的WNDCLASS 注册窗口类别

2、FromHandle方法:FromHandle(HANDLE h) 先查找由用户定义的内核对象对象的封装类, 如果找到直接返回,没有找到构造一个临时对象返回.

Life is like a box of chocolate, you never know what you are going to get.
原创粉丝点击