Marek Jedliński
Marek Jedliński

Reputation: 7316

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?

Upvotes: 6

Views: 2546

Answers (2)

Wouter van Nifterick
Wouter van Nifterick

Reputation: 24096

All windows have a z-order, which is a number that windows uses to determine which window should be painted on top of which.

When you activate a program, your application is put on top of the z-list.

When you press alt-tab, windows cycles through that list. So press alt-tab and hold it, to see how stuff is ordered.

Check this out to see how to simulate alt-tab: http://www.swissdelphicenter.ch/torry/showcode.php?id=2103

Upvotes: 0

gabr
gabr

Reputation: 26830

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.

Upvotes: 7

Related Questions