Programming Tips - Win32: tell when a user clicks outside my dialog

Date: 2015aug25 Platform: win32 Language: C/C++ Q. Win32: tell when a user clicks outside my dialog (I want to close my dialog when this occurs) A. Here is some code that does that.
namespace Hook { HWND m_hDlg = NULL; HHOOK m_hHook = NULL; static LRESULT CALLBACK MyMouseProc(int nCode, WPARAM message, LPARAM lParam) { MOUSEHOOKSTRUCT *pInfo = (MOUSEHOOKSTRUCT *) lParam; if (nCode >= 0) { if (message == WM_NCLBUTTONDOWN && pInfo->hwnd == ghMainDlg) { PostMessage(m_hDlg, WM_COMMAND, IDOK, 0); return 1; } } return CallNextHookEx(m_hHook, nCode, message, lParam); } static void Begin() { m_hHook = SetWindowsHookEx(WH_MOUSE, (HOOKPROC) MyMouseProc, NULL, GetCurrentThreadId()); } static void RegisterDialog(const HWND hDlg) { m_hDlg = hDlg; } static void End() { UnhookWindowsHookEx(m_hHook); m_hHook = NULL; } };
Use it by calling surrounding your dialog with Begin and End:
Hook::Begin(); DialogBox(ghInstance, MAKEINTRESOURCE(IDD_EDIT_MYDIALOG), hDlg, (DLGPROC) MyDlgProc); Hook::End();
In the dialog register:
case WM_INITDIALOG: ... Hook::RegisterDialog(hDlg); ..