简体   繁体   中英

How to determine if the current window is the active window?

How can I tell if my window is the current active window? My current guess is to do GetForegroundWindow and compare the HWND with that of my window. Is there a better method than that?

I'm using Win32 API / MFC.

Yes, that's the only way that I'm aware of.

But you have to handle the fact that GFW can return NULL. Typically, this happens when another desktop (eg the screen saver desktop) is active. Note that use of a saver password can affect whether a different desktop is used (this is windows version-dependent and I can't remember the details of how different versions work).

Also this code won't work properly in debug mode under Visual Studio, because you will get VS's window handle.

Other than that everything's peachy :-)

You can try to use WM_ACTIVATEAPP message.
First define a bool variable bool wActive = false , in the WndProc procedure, here is the next piece of code:

case WM_ACTIVATEAPP:
     wActive = (bool)wParam;
return 0;

You can go to MSDN to find more information about WM_ACTIVATEAPP

是的,你是正确的,除非你想要检查每个线程的活动窗口。

I assume that you mean the window which has the input focus when you say "active window"?

In that case, forget the GetForegroundWindow() API. That will return the topmost window - not always the window which has the input focus.

Use GetFocus() instead.

Yea, GetForgroundWindow() is a good way to check, behaves correctly even with a "Always on top" window aka HWND_TOPMOST .

Another way is with GetActiveWindow()

    HWND temp = GetActiveWindow();
    if (temp == hWnd) // Then your current window has focus

Alternatively the following messages report if the focus has changed

    case WM_KILLFOCUS:
        // windowHasFocus = false
    break;

    case WM_SETFOCUS:
        // windowHasFocus = true;
    break;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM