关闭控制台后,防止应用程序退出 [英] Prevent the application from exiting when the Console is closed

查看:74
本文介绍了关闭控制台后,防止应用程序退出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 AllocConsole()在winform应用程序中打开控制台.

I use AllocConsole() to open a Console in a winform application.

关闭控制台后,如何防止应用程序退出?

How can I prevent the application from exiting when the Console is closed?

编辑

我不希望在控制台中显示的是不时完成率百分比的更新

The update of completionpercentage from time to time is what I want to show in console

    void bkpDBFull_PercentComplete(object sender, PercentCompleteEventArgs e)
    {
        AllocConsole();
        Console.Clear();
        Console.WriteLine("Percent completed: {0}%.", e.Percent);
    }

我尝试了richtextBox作为替代方案

I tried the richtextBox as the alternative

       s =(e.Percent.ToString());
       richTextBox1.Clear();
       richTextBox1.AppendText("Percent completed:  " +s +"%");

但是我看不到完成率更新的时间.它仅在完成100%时显示.

But I can't see the completionpercentage update time to time. It only appears when it is 100% complete.

还有其他选择吗?

推荐答案

我知道这是一个很少出现的任务,但是我遇到了类似的问题,因此决定进行一些修改.

I know this is a task that seldom pops up but I had something similar and decided to go with a couple hacks.

-禁用自定义控制台应用程序上的关闭"按钮.

-Disable the "Close" button on a custom console application.

您的文本框解决方案也应该可以正常工作.这听起来很像是您从主线程中调用一个函数,该函数绑定了也在主线程上的表单,并在更新文本框时使您感到悲伤.考虑创建一个新线程,或者一个事件处理程序来更新您的文本框,或者使用新线程中的invokeMethodinvoker来更新文本框.下面是有关如何完成此操作的已回答问题的链接.

You're textbox solution should work as well. It sounds a lot like your calling a function from the main thread that is tying up the form which is also on the main thread and is causing you grief when updating your textbox. Consider creating a new thread and either an event handler to update your textbox or use the invoke methodinvoker from the new thread to update the textbox. Link below from an already answered question on how to complete this.

如何从另一个更新主线程中的文本框线程?

public class MainForm : Form {
    public MainForm() {
        Test t = new Test();

        Thread testThread = new Thread((ThreadStart)delegate { t.HelloWorld(this); });
        testThread.IsBackground = true;
        testThread.Start();
    }

    public void UpdateTextBox(string text) {
        Invoke((MethodInvoker)delegate {
            textBox1.AppendText(text + "\r\n");
        });
    }
}

public class Test {
    public void HelloWorld(MainForm form) {
        form.UpdateTextBox("Hello World"); 
    }
}

这篇关于关闭控制台后,防止应用程序退出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆