1

I'm starting internet explorer process. the problem is that it always return zero in p.MainWindowHandle. my objective is to get mainwindowHandler and minimize that particular window which is just started. the same code is working with chrome browser. but in internet explorer it's not working. my code is below.

Process p = Process.Start("IEXPLORE.EXE", "www.google.com");
ShowWindow(p.MainWindowHandle, 2);

ShowWindow is a method resize window.

  • 2
    Duplicate http://stackoverflow.com/questions/16185217/c-sharp-process-mainwindowhandle-always-returns-intptr-zero Shortcut: Call the Refresh() method before looking at MainWindowHandle – CathalMF Jun 15 '16 at 14:44
  • 2
    If you want to create the process with a minimized window, a better approach is to use [`ProcessStartInfo.WindowStyle`](https://msdn.microsoft.com/library/system.diagnostics.processstartinfo.windowstyle). In fact, the MSDN sample happens to use `iexplore.exe`. – Jeroen Mostert Jun 15 '16 at 14:46
  • I've called refresh method but still problem is there. – Nafees abbasi Jun 15 '16 at 14:48
  • p.Refresh(); IntPtr ptr = p.MainWindowHandle; – Nafees abbasi Jun 15 '16 at 14:49
  • It takes time for a browser to initialize and create its window of course. You must at least use p.WaitForInputIdle(). But that isn't enough, you must loop until you get a non-zero value. Sleep for a bit after each attempt, don't loop forever. – Hans Passant Jun 15 '16 at 14:52

1 Answers1

2

Among the many other reasons (see comments to the question), you have to wait for process to create the main window:

  // Process is IDisposable, wrap it into using
  using (Process p = Process.Start("IEXPLORE.EXE", "www.google.com")) {
    ...
    // wait till the process creates the main window
    p.WaitForInputIdle();

    // Main window (if any) has been created, so we can ask for its handle
    ShowWindow(p.MainWindowHandle, 2);
  }
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215