Dave's Brain

Browse - Programming Tips - How do I get the HWND handle for the main Window of my MFC program?

Date: 2008jun6
Updated: 2010feb4
Framework: MFC
Language: C/C++

Q.  How do I get the HWND handle for the main Window of my MFC program?

A.  First use AfxGetMainWnd() to get the CWnd class then
use GetSafeHwnd() on that as this function demonstrates:

// AfxGetMainWnd() is broken in Visual Studio 2005 so here's my own inline CWnd *MyGetMainWnd() { CWinApp *app; if ((app = AfxGetApp()) == NULL) return NULL; return app->m_pMainWnd; } inline HWND GetMainHwnd() { CWnd * wnd; if ((wnd = MyGetMainWnd()) == NULL) return NULL; return wnd->GetSafeHwnd(); }

Add a comment

Sign in to add a comment
Copyright © 2008-2017, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.