Toggle Process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden at runtime

前端 未结 3 933
醉话见心
醉话见心 2020-12-11 09:02

I want to toggle a process\'s visibility at runtime, I have a Windows Form app that starts via a process another console app hidden by default but I\'d like

相关标签:
3条回答
  • 2020-12-11 09:46

    You have to use Win32 API for this.

        [DllImport("user32.dll")]
        static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
    
        ProcessWindowStyle state = ProcessWindowStyle.Normal;
    
        void toggle()
        {
            if (cvarDataServiceProcess.HasExited)
            {
                MessageBox.Show("terminated");
            }
            else
            {
                if (cvarDataServiceProcess.MainWindowHandle != IntPtr.Zero)
                {
                    if (state == ProcessWindowStyle.Hidden)
                    {
                        //normal
                        state = ProcessWindowStyle.Normal;
                        ShowWindow(cvarDataServiceProcess.MainWindowHandle, 1);
                    }
                    else if (state == ProcessWindowStyle.Normal)
                    {
                        //hidden
                        state = ProcessWindowStyle.Hidden;
                        ShowWindow(cvarDataServiceProcess.MainWindowHandle, 0);
                    }
                }
            }
        }
    

    This, however, will not work when the process is started hidden, because the window will not be created and the handle to main window will be zero (invalid).
    So, maybe you can start the process normally and then hide it after that. :)

    0 讨论(0)
  • 2020-12-11 09:47

    Instead of using Process.StartInfo.WindowStyle after the process is started, you use Process.ShowWindow() to change the window style. However, as stated above, if you start the process hidden, you can never show the process window. IMHO, this is a very annoying bug that Microsoft should fix, but alas, I just work around it by showing the window then hiding it. Not as clean, and leaves a little user interface (or task bar) flashes, but at least it works.

    0 讨论(0)
  • 2020-12-11 09:56

    Regarding the problem, that once a process is started as hidden it is not possible to show the console window.

    It works for me when i call the showWindow command twice.
    First time nothing happens. Second time the window of a hidden process appears.

    Maybe someone can confirm?

        [DllImport("kernel32.dll")]
        static extern IntPtr GetConsoleWindow();
    
        DllImport("user32.dll")]
        static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
    
    ...
    ...
    ...
         ShowWindow(handle, 5); //nothing happens
         ShowWindow(handle, 5); //console window appears
    
    0 讨论(0)
提交回复
热议问题