Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I tell if a window has focus? (Win32 API)

Using the Win32 API (in C, but that's inconsequential), how can I tell if a given window (identified by HWND) has focus?

I'm hooking an application watching for an event, and when that event occurs I want to check if the application already has focus. If it doesn't, I want to flash the window until they give focus to it.

Alternately, does the FlashWindowEx struct flag FLASHW_TIMERNOFG that flashes until the window has focus just not flash if the window already has focus?

I cannot test this now since I am not in my development environment, but I was under the impression that it would flash anyways, which is what I'm trying to avoid.

Also, if it matters, the application uses DirectX in this window.

like image 780
Daniel Jennings Avatar asked Jan 21 '09 18:01

Daniel Jennings


People also ask

How do you check if a window is focused?

hasFocus() The hasFocus() method of the Document interface returns a boolean value indicating whether the document or any element inside the document has focus. This method can be used to determine whether the active element in a document has focus.

How do I fetch the Windows ID of the current focused window?

Call GetForegroundWindow to get the handle of the focused window, and then call GetWindowThreadProcessId to get the ID of the process that created that window. What you do with that ID is up to you. Save this answer.

Is Win32 a window?

Win32 is the 32-bit application programming interface (API) for versions of Windows from 95 onwards. The API consists of functions implemented, as with Win16, in system DLLs. The core DLLs of Win32 are kernel32. dll, user32.

What is Win32 API used for?

The Win32 API (also called the Windows API) is the native platform for Windows apps. This API is best for desktop apps that require direct access to system features and hardware. The Windows API can be used in all desktop apps, and the same functions are generally supported on 32-bit and 64-bit Windows.


2 Answers

GetActiveWindow will return the top-level window that is associated with the input focus. GetFocus will return the handle of the window that has the input focus.

This article might help:
http://www.microsoft.com/msj/0397/Win32/Win320397.aspx

like image 169
gkrogers Avatar answered Sep 21 '22 02:09

gkrogers


Besides gkrogers answer using GetActiveWindow, you can also maintain a boolean variable for the window you want to know if it has focus or not by trapping the WM_SETFOCUS and WM_KILLFOCUS events, or WM_ACTIVATE:

WndProc() .. case WM_SETFOCUS:   puts( "Got the focus" ) ;   break ;  case WM_KILLFOCUS:   puts( "Lost the focus" ) ;   break;  case WM_ACTIVATE:   if( LOWORD(wparam) == WA_INACTIVE )     puts( "I AM NOW INACTIVE." ) ;   else // WA_ACTIVE or WA_CLICKACTIVE     puts( "MEGAZORD ACTIVATED kew kew kew (flashy-eyes)" ) ;   break ; 
like image 35
bobobobo Avatar answered Sep 18 '22 02:09

bobobobo