It is not clear what you are asking; you are saying many things and I am not sure if any of the extra stuff is part of the question.
Try the following to get the last active window.
IntPtr lastWindowHandle = GetWindow(Process.GetCurrentProcess().MainWindowHandle, (uint)GetWindow_Cmd.GW_HWNDNEXT);
IntPtr hWndParent = GetParent(lastWindowHandle);
while (!hWndParent.Equals(IntPtr.Zero))
{
lastWindowHandle = hWndParent;
hWndParent = GetParent(lastWindowHandle);
}
Then after the loop lastWindowHandle
will have the handle of the top-level window of the last active application. You will also need the following.
[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);