How to get Main Window Handle of the last active window

While developing a litte application for Windows 7 in C# i encountered the problem that i needed to focus the last window after i started my application. Althought my application was closing after execution immediately, focus was not recurring to the last window because i was starting my application from the windows taskbar. For fixing this side-effect, i needed to find out, which window was active before my programm was “born”. So i did some googling for finding out how to get the previously active window handle in windows 7. In almost every thread, it was recommended to “listen” to window activation changes, and save the previous handle in a variable or so. But in my case, i wanted to avoid, running the programm permanently, or run anything in the background..

After some more research, i found out that Windows API has a list of all windows which is called: the z-order.
Next, i found the WinAPI Method GetWindow (see MSDN for documentation). This method allows you to get a window handle from the list mentoned above. Here how i used it:

IntPtr lastWindowHandle = GetWindow(Process.GetCurrentProcess().MainWindowHandle, (uint)GetWindow_Cmd.GW_HWNDNEXT);

But when trying to set the window with this handle to foreground, nothing came to foreground.. So i found out that the handle returned by this method was not neccessaryly the Main-Window-Handle. Therefore i wrote the following code finding out the parent handle:

while (true)
{
    IntPtr temp = GetParent(lastWindowHandle);
    if (temp.Equals(IntPtr.Zero)) break;
    lastWindowHandle = temp;
}

And finaly to show the window:

SetForegroundWindow(lastWindowHandle);

Here the whole Code with imports:

Imports:

[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr GetWindow(IntPtr hWnd, uint uCmd);
enum GetWindow_Cmd : uint
{
    GW_HWNDFIRST = 0,
    GW_HWNDLAST = 1,
    GW_HWNDNEXT = 2,
    GW_HWNDPREV = 3,
    GW_OWNER = 4,
    GW_CHILD = 5,
    GW_ENABLEDPOPUP = 6
}
[DllImport("user32.dll", ExactSpelling = true, CharSet = CharSet.Auto)]
public static extern IntPtr GetParent(IntPtr hWnd);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool SetForegroundWindow(IntPtr hWnd);

Usage:

 
IntPtr lastWindowHandle = GetWindow(Process.GetCurrentProcess().MainWindowHandle, (uint)GetWindow_Cmd.GW_HWNDNEXT);
while (true)
{
    IntPtr temp = GetParent(lastWindowHandle);
    if (temp.Equals(IntPtr.Zero)) break;
    lastWindowHandle = temp;
}
SetForegroundWindow(lastWindowHandle);

One thought on “How to get Main Window Handle of the last active window

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.