Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Window Title Changed Event

If a window, for e.g. Firefox, changes its title, from Firefox to Stack Overflow - Firefox then I want my app to record that Firefox changed its title.

Is this possible without the use of a hook and loop (EnumWindows)? If can be only done with a hook, which type of hook?

like image 698
Elmo Avatar asked Jan 06 '12 20:01

Elmo


2 Answers

WinEvents is the way to go here. The API you need is SetWinEventHook() - if you care about a specific window, use GetWindowThreadProcessId() to get the HWND's threadId and then listen to events only from that specific thread. For window title changes, you'll want the EVENT_OBJECT_NAMECHANGE event.

You can hook either "in context" or "out of context" - the latter is the simplest, and means the event gets delivered back to your own process, so you don't need a separate DLL - which makes it possible to do it all in C#; but the thread that calls SetWinEventHook must have a message loop (GetMessage/TranslateMessage/DispatchMessage), since the events are delivered using a form of messages behind the scenes.

In your WinEvent callback, you'll need to check that the HWND is the one you care about, since you'll get name changes for any UI on that target thread, possibly including child window name changes, or other things you don't care about.

--

By the way, you can check this answer for some sample C# code that uses WinEvents; it's using them to track foreground window changes across all windows on the desktop; but should just take a few simple modifications outlined above to track name changes on a specific window.

like image 170
BrendanMcK Avatar answered Nov 06 '22 06:11

BrendanMcK


You will need a hook (or the polling technique you mentioned in your question).

Basically in the Windows API, to change the "window caption" -- or more precisely the text of a window -- you send WM_SETTEXT, so your hook needs to intercept that message. The hook type you need is WH_CALLWNDPROC and just check if the message you're receiving is WM_SETTEXT and the hWnd is the main window for the application you're looking at (so you don't get false positives like the application trying to set the text of children windows).

Small note here: While this is probably not the case here, be aware that the title you see can actually just be drawn there manually, not going through the usual Windows API. Use Spy++ or something to see what's going on before going too far down this route, you might spend a lot of time for nothing.

like image 41
Blindy Avatar answered Nov 06 '22 07:11

Blindy