Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Question
Thursday, August 3, 2017 8:24 PM
I'm interested in opening and closing a console before creating and showing a normal window. I opened a console window using AllocConsole() in my WinMain function, then using a snippet someone gave me from a previous question I asked, I redirected standard streams so I could use functions like printf and scanf. Then I tried FreeConsole() and checked if it returned 0 to see if it failed. Then I created a normal window with a message loop.
When I ran the program, everything worked fine, but FreeConsole() returned 0 (meaning it shouldn't have failed) while not closing the console.
Here's a snippet of the C code I wrote. Does anyone know if I used FreeConsole incorrectly in this snippet, and have any corrections? I'm pretty sure from the FreeConsole docs, that since I used FreeConsole and there was only one process using the console, it should've been destroyed, but I'm not getting that result.
int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine,
int nCmdShow)
{
AllocConsole();
FILE *fpstdin = stdin, *fpstdout = stdout, *fpstderr = stderr;
freopen_s(&fpstdin, "CONIN$", "r", stdin);
freopen_s(&fpstdout, "CONOUT$", "w", stdout);
freopen_s(&fpstderr, "CONOUT$", "w", stderr);
printf("Input a value.\n");
int val = 0;
scanf_s("%i", &val);
printf("The value inputted was %i", val);
if (FreeConsole() == 0) {
MessageBox(NULL, "FreeConsole failed", "", MB_OK);
}
//...
//Register class...
//Create HWND with CreateWindowEx...
//Run Message Loop...
}
Here's a visual of what the program looks like so far. The console window is still open when I thought FreeConsole() should've closed it.
All replies (4)
Thursday, August 3, 2017 9:51 PM âś…Answered | 1 vote
Close the standard handles (stdin,stdout, stderr) before you call FreeConsole.
Thursday, August 3, 2017 11:43 PM
Thanks, didn't notice that. 'fclose(stdin)', 'fclose(stdout)', and 'fclose(stderr)' worked for me.
Thursday, August 3, 2017 11:57 PM | 1 vote
Closing the standard handles wasn't included in the snippet to which I referred you because in that question the poster wanted to access the console available when the application was started from a command prompt. That's also the reason why the snippet in that post used AttachConsole instead of AllocConsole.
Friday, August 4, 2017 1:18 AM
That makes sense. Closing the handles of cmd would not make sense and cause an error, from what I've seen testing it. With something like 'AttachConsole(ATTACH_PARENT_PROCESS)', the process would look to its parent for a console, which would be the cmd, and then direct output there. Anyways, that's pretty neat, thanks for the extra info.