我使用来自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;
}
}发布于 2009-01-14 20:24:43
要做到这一点会容易得多:
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);
}发布于 2009-01-14 20:35:05
你检查过p.MainWindowHandle是否是有效的句柄吗?它至少必须是非零的。试着打电话给IsWindow确认。
在检查MainWindowHandle之前调用WaitForInputIdle;您可能会在新进程创建其窗口之前访问该属性。不管怎样,这个属性本质上是不稳定的,因为进程实际上并没有“主”窗口的概念。所有窗口都一视同仁。.Net框架简单地将第一个窗口指定为主窗口,但流程本身并不需要这样考虑。
此外,您是否考虑过在开始时简单地隐藏流程,而不是启动流程,然后在事实发生后隐藏起来?设置进程的StartInfo属性as Scotty2012 demonstrates。
https://stackoverflow.com/questions/444517
复制相似问题