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

北城以北 提交于 2020-01-09 08:11:28

问题


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 to allow the admin user to toggle this state via a checkbox and show the console app if they choose.

I have this but it's not working:

private void checkBox1_CheckedChanged(object sender, EventArgs e)
    {
        ProcessWindowStyle state = cvarDataServiceProcess.StartInfo.WindowStyle;
        if (state == ProcessWindowStyle.Hidden)
            cvarDataServiceProcess.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
        else if (state == ProcessWindowStyle.Normal)
            cvarDataServiceProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;            
    }

回答1:


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. :)




回答2:


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.



来源:https://stackoverflow.com/questions/2647820/toggle-process-startinfo-windowstyle-processwindowstyle-hidden-at-runtime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!