Click here to Skip to main content
15,881,802 members
Please Sign up or sign in to vote.
3.67/5 (3 votes)
How can I use the FreeConsole() to close a console? Currently I have done all coding related to directing the output in a button click event. How do I call this to ensure that my form doesn't close when console closes? Please advice. Done in C#.
Posted
Comments
PIEBALDconsult 5-Apr-14 21:23pm    
Sooo... where's the code?
mayooran99 5-Apr-14 22:43pm    
[DllImport("kernel32.dll",
EntryPoint = "GetStdHandle",
SetLastError = true,
CharSet = CharSet.Auto,
CallingConvention = CallingConvention.StdCall)]
private static extern IntPtr GetStdHandle(int nStdHandle);
[DllImport("kernel32.dll",
EntryPoint = "AllocConsole",
SetLastError = true,
CharSet = CharSet.Auto,
CallingConvention = CallingConvention.StdCall)]
private static extern int AllocConsole();
private const int STD_OUTPUT_HANDLE = -11;
private const int MY_CODE_PAGE = 437;
AllocConsole();
IntPtr stdHandle = GetStdHandle(STD_OUTPUT_HANDLE);
SafeFileHandle safeFileHandle = new SafeFileHandle(stdHandle, true);
FileStream fileStream = new FileStream(safeFileHandle, FileAccess.Write);
Encoding encoding = System.Text.Encoding.GetEncoding(MY_CODE_PAGE);
StreamWriter standardOutput = new StreamWriter(fileStream, encoding);
standardOutput.AutoFlush = true;
Console.SetOut(standardOutput);

One option is to post a WM_QUIT message

PostMessage(consoleWindow, WM_CLOSE, 0, 0);
 
Share this answer
 
There is another way I found that works. You just hide the console. Next time, you don't even need to 'unhide' it, but just to open it as usual.

HWND console = GetConsoleWindow();
ShowWindow(console,1);
 
Share this answer
 
Comments
Richard MacCutchan 11-Jan-24 6:22am    
You do realise this question is almost 10 years old.
0x01AA 11-Jan-24 10:48am    
Michael Haephrati 11-Jan-24 7:36am    
As I explain many times in the past, there is nothing wrong with that. I will keep on answering any question that is relevant today, and this one is. I stumbled upon the question while looking for the same solution myself and that was yesterday.
0x01AA 11-Jan-24 12:51pm    
Which is very ok according to Answering old questions[^] ;)
Therefore my small +5 as a small compensation to the down votes.
Michael Haephrati 11-Jan-24 15:17pm    
Yes, as I see it, if a topic became irrelevant, even if the question is relatively new, I won't post an answer, but if the question is still relevant today, I will. Thanks 0x01AA.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900