- 1 year ago
How to determine when a child dialog, or one of its children, gains and loses focus
Comment
1 / 1
To determine when a child dialog, or one of its children, gains or loses focus in Windows, you can handle the WM_SETFOCUS
and WM_KILLFOCUS
messages. Here's an example of how you can do this using the Win32 API and C++:
- Define the message handlers: Add the following message handlers to your dialog's message handler function:
cppLRESULT CALLBACK DialogProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch (msg)
{
case WM_SETFOCUS:
// Child dialog or child control has gained focus
// Handle the focus gained event
break;
case WM_KILLFOCUS:
// Child dialog or child control has lost focus
// Handle the focus lost event
break;
// Other message handlers...
default:
return DefWindowProc(hwnd, msg, wParam, lParam);
}
return 0;
}
- Assign the dialog procedure: Set the dialog procedure by calling
SetWindowLongPtr
with theDWLP_DLGPROC
flag. Make sure to call this before displaying the dialog.
cpp// Create the dialog
HWND hDlg = CreateDialog(hInstance, MAKEINTRESOURCE(IDD_DIALOG), hWndParent, DialogProc);
// Set the dialog procedure
SetWindowLongPtr(hDlg, DWLP_DLGPROC, reinterpret_cast<LONG_PTR>(DialogProc));
// Show the dialog
ShowWindow(hDlg, SW_SHOW);
- Handle focus events: Within the
WM_SETFOCUS
andWM_KILLFOCUS
message handlers, you can add your code to handle the focus gained and focus lost events for the child dialog or its children.
Note that in the WM_SETFOCUS
and WM_KILLFOCUS
messages, wParam
contains the handle of the window gaining or losing focus. You can use this handle to identify the specific child dialog or control that is receiving or losing focus.
By implementing these message handlers in your dialog procedure, you can determine when a child dialog or one of its children gains or loses focus in Windows using the Win32 API.