How do I bring an unmanaged application window to front, and make it the active window for (simulated) user input

Gerald Davis picture Gerald Davis · Jun 3, 2011 · Viewed 18.1k times · Source

I am assuming I need to use pinvoke but I am not sure which function calls are needed.

Scenario: a legacy application will be running, I will have Handle for that application.

I need to:

  1. bring that application to the top (in front of all other windows)
  2. make it the active window

Which Windows function calls are needed?

Answer

user703016 picture user703016 · Jun 3, 2011

If you don't have a handle to the window, use this before :

[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

Now assuming you have a handle to the application window :

[DllImport("user32.dll", SetLastError = true)]
static extern bool SetForegroundWindow(IntPtr hWnd);

This will make the taskbar flash if another window has keyboard focus.

If you want to force the window to come to the front, use ForceForegroundWindow (sample implementation).