views:

364

answers:

1

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  A: 

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

Nayan
No the process stays running throughout the life of the Windows App so weeks/months at a time. It is definitely present and running when I look at TaskManager.
m3ntat
You're right. Actually, console or no console, once the process has started, it doesn't work. I have edited the code. You have to use Windows API. :)
Nayan
More info about ShowWindow here http://www.pinvoke.net/default.aspx/user32/ShowWindow.html
Nayan
Awesome that did the trick, thank you @Nayan.
m3ntat