0

A message box created with

MessageBox (NULL, "Text", "Title", MB_ICONINFORMATION | MB_SYSTEMMODAL);

stays on top of other windows, but it loses keyboard focus when the user clicks another window. How could I create a message box (or an Edit box or a dialog box) that never loses keyboard focus, so if I try to switch to another window using [ALT-TAB] or mouse or any other method, or if another application running in a background opens its own Edit box, the keyboard focus would jump back to my message / Edit box? The standard MessageBox function doesn't have such an option, so I tried a custom Edit box. I experimented with WM_SETFOCUS, WM_KILLFOCUS, WM_NCACTIVATE, SetForegroundWindow, SetFocus, but had no luck so far. When I open another window, the keyboard focus stubbornly goes to that window.

1 Answers1

0
RegisterHotKey(0,1,MOD_ALT,VK_TAB); //disables alt+tab until message box returns
SetTimer(hwnd,1,100,0); //0.1 sec is enough for message box window creation
MessageBox(0,"Text","Title",MB_ICONINFORMATION|MB_SYSTEMMODAL); //since it's system modal, main message loop will wait for it to return
ClipCursor(0); //frees cursor
UnregisterHotKey(0,1); //enables alt+tab again

Here we use a timer to clip cursor so that user won't be able to click outside of the message box. I left title part of the messagebox outside of the clip area because clicking there negates cursor clipping.

case WM_TIMER:
{
    KillTimer(hwnd,1);
    RECT rc;
    GetWindowRect(FindWindow(0,"Title"),&rc);
    rc.top+=22; //title area left out of clip area
    ClipCursor(&rc); //user cannot move their mouse outside of the message box
    break;
}

This however can't block Ctrl + Alt + Del but does what you ask.

user814412
  • 70
  • 1
  • 7
  • 1
    @xcvbnm AFAIK, if your application's top level window loses _foreground_ status, you can't make it foreground again within your program. The authorized app to change foreground window is the one that has the _foreground_ window itself. So the question shouldn't be "how to get focus back" IMO, you should guarantee that you never lose focus. So you should get rid of every possibility that might steal focus. You can search for [setting hooks](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-setwindowshookexa) for further info about disabling keypress combinations. – user814412 Jan 10 '21 at 00:19
  • Rather than using a timer, I would use a thread-local hook to be notified when the MessageBox’s window is created/made visible. – Remy Lebeau Jan 10 '21 at 00:24
  • 1
    @xcvbnm "*need the keyboard focus to stay on my window no matter what*" Just saying, but it would be really annoying if Windows allowed an app to do that (reliably). – dxiv Jan 10 '21 at 02:52
  • [What if two programs did this?](https://devblogs.microsoft.com/oldnewthing/20050607-00/?p=35413) – Mark Ransom Jan 13 '21 at 20:23