问题
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