1

I am trying to open simple .net exe/notepad.exe using process.start in hidden mode. and I need the process handle later to make the application.exe to make it visible after some time.

  1. Able to get handle only in WindowStyle.Minimized, WindowStyle.Maximized, WindowStyle.Normal. In Hidden style, it gives me 0 always.

  2. How to get handle without using Thread.Sleep. It requires us to wait few seconds, to get handle. some exe requires more wait time, based on its performance(huge data).

    public static void LaunchExe()
    {
        var proc = new Process
        {
            StartInfo =
            {
                FileName = "Notepad.exe", //or any simple .net exe
                WindowStyle = ProcessWindowStyle.Hidden
            }
        };
    
        proc.Start();
    
        proc.WaitForInputIdle(800); //is it possible to avoid this.
        Thread.Sleep(3000); //is it possible to avoid this.
    
        Console.WriteLine("handle {0}", proc.MainWindowHandle);
    
    
        //ShowWindowAsync(proc.MainWindowHandle, 1); //planned to use, to make it visible.
    }
    
anand
  • 307
  • 3
  • 14

1 Answers1

0

You can do something like this:

        IntPtr ptr = IntPtr.Zero;
        while ((ptr = proc.MainWindowHandle) == IntPtr.Zero)
        { proc.WaitForInputIdle(1 * 60000); Thread.Sleep(10); }   // (1*60000 = 1min, will give up after 1min)

That way you're not wasting any more time than you need to.

You can't get the handle of a hidden process.

According to MS: A process has a main window associated with it only if the process has a graphical interface. If the associated process does not have a main window, the MainWindowHandle value is zero. The value is also zero for processes that have been hidden, that is, processes that are not visible in the taskbar.

I think your only choice would be to start it normally, get the handle, then set it hidden.
This might cause some flicker, but it should work. To mitigate the flicker, you could start it minimized...

Scott Solmer
  • 3,871
  • 6
  • 44
  • 72
  • Yes that would help. Is there any option to get handle of hidden process? – anand Sep 02 '14 at 18:05
  • thanks. My actual requirement is opening an exe developed by team developer, get the handle and show the exe inside the .net winform. minimized option is not working for that exe. but it works for winform.exe, notepad. – anand Sep 02 '14 at 18:25
  • If you have control of the other application (as in someone in your company is making it) I would recommend to use some form of [IPC](http://msdn.microsoft.com/en-us/library/windows/desktop/aa365574%28v=vs.85%29.aspx) to pass handles / commands / etc. It's much cleaner. – Scott Solmer Sep 02 '14 at 18:28