Search code examples
c#winapifocusz-ordertopmost

focus lost after making another app's window topmost


I'm making another app's window topmost to ensure that a click in my app brings the other's dialog into views. The problem I'm having is that I don't get focus back to my app after the call. If the other app has more windows one of them ends up with focus, and otherwise no window (looking at the taskbar only) gets focus. Where should I start investigating the issue?

My code for making the other app topmost is:

Process p = Process.GetProcessById(trackedProcessID);
IntPtr h = p.MainWindowHandle;
uint TOPMOST_FLAGS = SWP_NOMOVE | SWP_NOSIZE | SWP_ASYNCWINDOWPOS;
SetWindowPos(h, HWND_TOPMOST, 0, 0, 0, 0, TOPMOST_FLAGS);

with constants as

public static readonly uint SWP_NOMOVE = 0x0002;
public static readonly uint SWP_NOSIZE = 0x0001;
public static readonly uint SWP_ASYNCWINDOWPOS = 0x4000;
public static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);

Solution

  • Related: Unexpected behaviour of Process.MainWindowHandle

    Basically MainWindowHandle gives you the current top-most window of the process despite what the documentation says.

    That explains why the main window of your other process doesn't necessarily get focus.

    Your other problem is because you are not returning focus to your app after giving it away.

    Actually, the correct term for what you are doing is establishing z-order.

    Instead of trying to control z-order - which cannot be guaranteed - you might be better off sending messages to the other process.