Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect what window was active just before my app activates

In Delphi XE, I'm trying to use GetForegroundWindow to detect the window that was active immediately before my application was activated. "Activated" means that the app may have been restored from iconic state, or it was switched to via alt+tab, or brought up by activaton hotkey, etc.

The problem is that all the available application events (OnActivate, OnRestore) come too late, so that GetForegroundWindow returns my own form's handle. The main form's events are even less useful. Processing WM_ACTIVATEAPP in the main form happens too late, too.

One way would be to keep checking the active window on timer while my application is not active, but this seems rather wasteful. A much better solution would be to subclass TApplication.WndProc and do my thing before WM_ACTIVATEAPP is processed, but I don't think TApplication can be subclassed.

Is there a better way?

like image 321
Marek Jedliński Avatar asked Jan 26 '11 03:01

Marek Jedliński


1 Answers

When your application activates, it becomes the topmost window. IOW, it jumps to the top Z-order position.

With this, previous topmost window is demoted to the "just below the new topmost window" position. IOW, it becomes second in the Z-order position.

Calling GetNextWindow and passing it the handle of your form and GW_HWNDNEXT may give you just the result you need.

like image 55
gabr Avatar answered Sep 30 '22 16:09

gabr