我使用User32的ShowWindow方法隐藏用户的窗口(cmd.exe)(主要是为了防止它们关闭它)。当用户打开表单时,进程启动并隐藏,然后当表单关闭时,进程被终止。但是,当表单再次打开时,它不会隐藏窗口(有时不是第一次)有人可以帮助我吗?
[DllImport("User32")]
private static extern int ShowWindow(int hwnd, int nCmdShow); //this will allow me to hide a window
public ConsoleForm(Process p) {
this.p = p;
p.Start();
ShowWindow((int)p.MainWindowHandle, 0); //0 means to hide the window. See User32.ShowWindow documentation SW_HIDE
this.inStream = p.StandardInput;
this.outStream = p.StandardOutput;
this.errorStream = p.StandardError;
InitializeComponent();
wr = new watcherReader(watchProc);
wr.BeginInvoke(this.outStream, this.txtOut, null, null);
wr.BeginInvoke(this.errorStream, this.txtOut2, null, null);
}
private delegate void watcherReader(StreamReader sr, RichTextBox rtb);
private void watchProc(StreamReader sr, RichTextBox rtb) {
string line = sr.ReadLine();
while (line != null && !stop && !p.WaitForExit(0)) {
//Console.WriteLine(line);
line = stripColors(line);
rtb.Text += line + "\n";
line = sr.ReadLine();
}
}
public void start(string[] folders, string serverPath) {
this.inStream.WriteLine("chdir C:\\cygwin\\bin");
//this.inStream.WriteLine("bash --login -i");
this.inStream.WriteLine("");
}
private void ConsoleForm_FormClosed(object sender, FormClosedEventArgs e) {
this.stop = true;
try {
this.p.Kill();
this.p.CloseMainWindow();
} catch (InvalidOperationException) {
return;
}
}
答案 0 :(得分:4)
这会更容易:
public ConsoleForm(Process p) {
this.p = p;
p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
p.StartInfo.CreateNoWindow = true;
p.Start();
this.inStream = p.StandardInput;
this.outStream = p.StandardOutput;
this.errorStream = p.StandardError;
InitializeComponent();
wr = new watcherReader(watchProc);
wr.BeginInvoke(this.outStream, this.txtOut, null, null);
wr.BeginInvoke(this.errorStream, this.txtOut2, null, null);
}
答案 1 :(得分:0)
您是否检查过p.MainWindowHandle
是否为有效句柄?它至少必须是非零的。请尝试拨打IsWindow
进行确认。
MainWindowHandle
之前, MSDN suggests致电WaitForInputIdle
;您可能在新进程创建窗口之前访问该属性。不过,该属性本质上是不稳定的,因为进程实际上没有“主”窗口的概念。所有窗户都得到平等对待。 .Net框架只是将第一个窗口指定为主窗口,但该过程本身不需要考虑这种方式。
另外,您是否考虑过最初只是隐藏进程,而不是启动它然后隐藏在事实之后?设置流程的StartInfo
属性as Scotty2012 demonstrates。