1

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?

Masoud Mohammadi
  • 1,721
  • 1
  • 23
  • 41
KalanyuZ
  • 672
  • 6
  • 15

1 Answers1

1

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.

Roger Rowland
  • 25,885
  • 11
  • 72
  • 113