Prevent the application from exiting when the Console is closed

无人久伴 提交于 2021-02-08 14:38:17

问题


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

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

EDIT

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

I tried the richtextBox as the alternative

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

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

Any alternative?


回答1:


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

http://social.msdn.microsoft.com/Forums/vstudio/en-US/545f1768-8038-4f7a-9177-060913d6872f/disable-close-button-in-console-application-in-c

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

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.

How to update textboxes in main thread from another thread?

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



回答2:


Refer to the answers over here. As mentioned in the answers, there is no way to stop the application from getting closed.

But as a workaround, you can have your own text output solution described in one of the answers.




回答3:


You can build first the console application that recieves arguments and writes it to the console. Place it, where the main application starts. From main application you can first kill process and then reopen it with a new argument.
It's the altarnative way.



来源:https://stackoverflow.com/questions/18036021/prevent-the-application-from-exiting-when-the-console-is-closed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!