m3n*_*tat 3 c# process window-style
我想在运行时切换进程的可见性,我有一个Windows窗体应用程序,通过一个进程启动默认隐藏的另一个控制台应用程序但我想允许管理员用户通过复选框切换此状态并显示控制台应用程序他们选择.
我有这个,但它不起作用:
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;
}
Run Code Online (Sandbox Code Playgroud)
你必须使用Win32 API.
[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);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
但是,当启动进程时,这将不起作用hidden,因为将不会创建窗口并且主窗口的句柄将为零(无效).
所以,也许你可以正常启动这个过程然后隐藏它.:)