Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
334 views
in Technique[技术] by (71.8m points)

c++ - A message box that never loses focus

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.

question from:https://stackoverflow.com/questions/65646817/a-message-box-that-never-loses-focus

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...