Reliable bring external process window to foreground with C#

If you want to reliable bring the main window of an external process to the foreground in C#, use the “simulate alt key” technique found at:

Just start Notepad, then run the following test in Visual Studio.

It should bring Notepad as a maximized window in the foreground.

namespace Research.EndToEndTests
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
public class ResearchTester
public void Test()
public void Reliable_set_window_to_forground()
Process[] processes = Process.GetProcesses();
foreach (Process proc in processes)
if (ProcessIsNotepad(proc))
public bool ProcessIsNotepad(Process proc) 
return proc.MainWindowTitle.EndsWith("Notepad", StringComparison.InvariantCultureIgnoreCase);
private const int ALT = 0xA4;
private const int EXTENDEDKEY = 0x1;
private const int KEYUP = 0x2;
private const int SHOW_MAXIMIZED = 3;
private static extern IntPtr GetForegroundWindow();
private static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, int dwExtraInfo);
private static extern bool SetForegroundWindow(IntPtr hWnd);
private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
public static void ActivateWindow(IntPtr mainWindowHandle)
// Guard: check if window already has focus.
if (mainWindowHandle == GetForegroundWindow()) return;
// Show window maximized.
ShowWindow(mainWindowHandle, SHOW_MAXIMIZED);
// Simulate an "ALT" key press.
keybd_event((byte)ALT, 0x45, EXTENDEDKEY | 0, 0);
// Simulate an "ALT" key release.
keybd_event((byte)ALT, 0x45, EXTENDEDKEY | KEYUP, 0);
// Show window in forground.


  1. Piyush Ratan Sharma

    It is working only notepad . when Main window handle is greater than Max set point. this not working . showwindow method not working . any solution .

  2. VK

    is there a way to get this to work with windows 10 marketplace apps (or the new universal apps?)

    the switch to window works fine with classic windows desktop apps but i cant seem to bring windows 10/marketplace apps to the foreground.

  3. Stephan

    Thanks this works great for me.
    After trying a few things that did not work I tried this.
    I wanted to popup a winforms over chrome browser that was in kiosk mode and it worked.
    Thanks for sharing.

Leave a Reply

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