Search code examples
c#winapishowwindow

ShowWindow spawns unexpected windows/application


I'm trying to pop notepad window in my c# Application using this code:

Process[] Processes = Process.GetProcessesByName("notepad");
IntPtr hWnd = IntPtr.Zero;
Debug.WriteLine("Processes: " + Processes.Length);

// do something
foreach(Process p in Processes)
{
    Console.WriteLine(p.ProcessName);
    SetForegroundWindow(p.Handle);
    ShowWindow(p.Handle, ShowWindowEnum.Show);
    //SetActiveWindow(p.Handle);

    //p.Kill();
}

The console logs "notepad" just fine. I can even kill notepad process. However, for some reason, showWindow works randomly. Most of the time it spawns something like GDI+server titled empty windows and etc and rarely pops the notepad.

What am I doing wrong?


Solution

  • ShowWindow expects a window handle, not a process handle.

    Try passing the MainWindowHandle instead.

    SetForegroundWindow(p.MainWindowHandle);
    ShowWindow(p.MainWindowHandle, ShowWindowEnum.Show);
    

    This should be ok for Notepad.exe, but won't be generally reliable for applications that have multiple top level windows.