Improve console allocation.

This commit is contained in:
dlbuhtig4096 2024-10-24 16:35:54 +08:00
parent 28f5c76035
commit ff84815acb
2 changed files with 25 additions and 11 deletions

View File

@ -119,6 +119,8 @@ void OpenConsole()
//stdout is already connected to something. keep using it and dont let the console interfere
bool shouldRedirectStdout = fileType == FILE_TYPE_UNKNOWN;
bool attached = false;
#if 0
if (!AllocConsole())
{
HMODULE lib = LoadLibrary("kernel32.dll");
@ -143,6 +145,9 @@ void OpenConsole()
SetConsoleCP(GetACP());
SetConsoleOutputCP(GetACP());
}
#else
attached = AttachConsole(-1) || AllocConsole();
#endif
//newer and improved console title:
SetConsoleTitleW(SkipEverythingButProgramInCommandLine(GetCommandLineW()).c_str());

View File

@ -30,7 +30,7 @@
#include <io.h>
#define BUFFER_SIZE 100
HANDLE hConsole;
HANDLE hConsole = NULL;
void OpenConsole()
{
COORD csize;
@ -41,27 +41,33 @@ void OpenConsole()
//dont do anything if we're already attached
if (hConsole) return;
#if 0
//attach to an existing console (if we can; this is circuitous because AttachConsole wasnt added until XP)
//remember to abstract this late bound function notion if we end up having to do this anywhere else
bool attached = false;
HMODULE lib = LoadLibrary("kernel32.dll");
if(lib)
// kernel32.dll is always loaded on windows.
HMODULE lib = GetModuleHandleA("kernel32.dll"); // LoadLibrary("kernel32.dll");
if (lib)
{
typedef BOOL (WINAPI *_TAttachConsole)(DWORD dwProcessId);
_TAttachConsole _AttachConsole = (_TAttachConsole)GetProcAddress(lib,"AttachConsole");
if(_AttachConsole)
if (_AttachConsole)
{
if(_AttachConsole(-1))
attached = true;
attached = (bool)_AttachConsole(-1);
}
FreeLibrary(lib);
// You cannot free kernel32.dll
// FreeLibrary(lib);
}
//if we failed to attach, then alloc a new console
if(!attached)
if (!attached)
{
AllocConsole();
}
#else
if (!AttachConsole(-1)) { AllocConsole(); }
#endif
hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
@ -91,9 +97,12 @@ void OpenConsole()
srect.Right = srect.Left + 99;
srect.Bottom = srect.Top + 64;
SetConsoleWindowInfo(GetStdHandle(STD_OUTPUT_HANDLE), TRUE, &srect);
SetConsoleCP(GetACP());
SetConsoleOutputCP(GetACP());
if(attached) printf("\n");
// Use default code page.
// SetConsoleCP(GetACP());
// SetConsoleOutputCP(GetACP());
if (attached) printf("\n");
printf("%s\n",_TITLE);
printf("- compiled: %s %s\n\n",__DATE__,__TIME__);
}