c# - User3 2's ShowWindow doesn' t 按预期行事

标签 c# .net system.diagnostics user32

我正在使用 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;
        }
    }

最佳答案

这样做会容易得多:

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);
    }

关于c# - User3 2's ShowWindow doesn' t 按预期行事,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/444517/

相关文章:

c# - 同一行中的两个 div

c# - 具有异步/等待和处理高负载的简单任务返回异步 HtppListener

.net - HttpContext.Request 和 Request 的区别

c# - 我如何知道最后一个 OutputDataReceived 何时到达?

visual-studio-2010 - Trace.WriteLine 不产生任何输出

c# - Visual Studio 2008 - 运行时卡住,当我尝试调试时显示 "unable to break execution"

c# - 从对象方法中调用管理器/服务类好吗?

C# 分配/强制转换为结构中的对象字段

c# - 列出已应用属性的对象属性

c# - System.SecurityException 错误