首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >User32的ShowWindow没有按照预期运行

User32的ShowWindow没有按照预期运行
EN

Stack Overflow用户
提问于 2009-01-14 20:19:44
回答 2查看 3K关注 0票数 1

我使用来自User32的ShowWindow方法向用户隐藏一个窗口(cmd.exe) (主要是为了防止他们关闭它)。当用户打开表单时,进程启动,并隐藏,然后当表单关闭时,进程被终止。但是,当窗体再次打开时,它不会隐藏窗口(有时第一次也不会),有人能帮我吗?

代码语言:javascript
复制
    [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;
        }
    }
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2009-01-14 20:24:43

要做到这一点会容易得多:

代码语言:javascript
复制
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);
    }
票数 4
EN

Stack Overflow用户

发布于 2009-01-14 20:35:05

你检查过p.MainWindowHandle是否是有效的句柄吗?它至少必须是非零的。试着打电话给IsWindow确认。

在检查MainWindowHandle之前调用WaitForInputIdle;您可能会在新进程创建其窗口之前访问该属性。不管怎样,这个属性本质上是不稳定的,因为进程实际上并没有“主”窗口的概念。所有窗口都一视同仁。.Net框架简单地将第一个窗口指定为主窗口,但流程本身并不需要这样考虑。

此外,您是否考虑过在开始时简单地隐藏流程,而不是启动流程,然后在事实发生后隐藏起来?设置进程的StartInfo属性as Scotty2012 demonstrates

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/444517

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档