Skip to content

Commit 5a5120e

Browse files
committed
Employ magical windows trickery to become foreground window
1 parent 2ee8e94 commit 5a5120e

File tree

1 file changed

+15
-5
lines changed

1 file changed

+15
-5
lines changed

wlines.c

+15-5
Original file line numberDiff line numberDiff line change
@@ -276,6 +276,18 @@ LRESULT CALLBACK editWndProc(HWND wnd, UINT msg, WPARAM wparam, LPARAM lparam)
276276
return CallWindowProc(state->editWndProc, wnd, msg, wparam, lparam);
277277
}
278278

279+
void forceForeground(HWND hwnd)
280+
{
281+
// Use trick from https://stackoverflow.com/a/59659421
282+
const DWORD foregroundThreadId = GetWindowThreadProcessId(GetForegroundWindow(), 0);
283+
const DWORD currentThreadId = GetCurrentThreadId();
284+
AttachThreadInput(foregroundThreadId, currentThreadId, true);
285+
BringWindowToTop(hwnd);
286+
ShowWindow(hwnd, SW_SHOW);
287+
SetForegroundWindow(hwnd);
288+
AttachThreadInput(foregroundThreadId, currentThreadId, false);
289+
}
290+
279291
LRESULT CALLBACK mainWndProc(HWND wnd, UINT msg, WPARAM wparam, LPARAM lparam)
280292
{
281293
state_t *state = (state_t*)GetWindowLongPtrA(wnd, GWLP_USERDATA);
@@ -295,7 +307,7 @@ LRESULT CALLBACK mainWndProc(HWND wnd, UINT msg, WPARAM wparam, LPARAM lparam)
295307
} else if (state->hadForeground) {
296308
exit(1);
297309
} else {
298-
SetForegroundWindow(wnd);
310+
forceForeground(state->mainWnd);
299311
}
300312
}
301313
break;
@@ -498,11 +510,9 @@ void createWindow(state_t *state)
498510
lStyle &= ~WS_OVERLAPPEDWINDOW;
499511
SetWindowLong(state->mainWnd, GWL_STYLE, lStyle);
500512

501-
// Show window and attempt to focus it
502-
ShowWindow(state->mainWnd, SW_SHOW);
513+
// Show and attempt to focus window
503514
ASSERT_WIN32_RESULT(UpdateWindow(state->mainWnd));
504-
SetForegroundWindow(state->mainWnd);
505-
SetActiveWindow(state->mainWnd);
515+
forceForeground(state->mainWnd);
506516
SetFocus(state->editWnd);
507517

508518
// Start foreground timer

0 commit comments

Comments
 (0)