lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]

Hi everyone,
I've been researching this for a while now, and finally I've found a solution 
for console I/O in a GUI Windows program (32 bit). This allows using programas 
that call write() and read() without a FILE* argument under Windows in GUI mode.
I'm not completely satisfied with it, I have no control where the console 
window pops up, for instance, but it works.
The following code illustrates how to do the trick. The OpenCon() function 
should be called prior to running any Lua code that uses stdin/stdout/stderr.
The CloseCon() should be called after program completion.
The CtrlHandler() function avoids misbehaving of the program when Ctrl-C is hit 
on the console window.
Hope this helps others, and I'd appreciate feedback, especially on how to 
control the console window.

/* --------------------------------------------------------------------
 Begin of sample code - all error checking funcs were left out,
 but they're necessary - check the Win32 sdk help on how to do this.
   -------------------------------------------------------------------- */

HANDLE  Console;

BOOL CtrlHandler(DWORD fdwCtrlType)
    if (fdwCtrlType == CTRL_C_EVENT) // ignore Ctrl-C
        return TRUE;
        return FALSE;

void OpenCon(void)
	HANDLE  Console = CreateConsoleScreenBuffer(GENERIC_READ|GENERIC_WRITE, 
	SetConsoleCtrlHandler((PHANDLER_ROUTINE)CtrlHandler, TRUE);
    SetConsoleTitle("Lua Console");
    freopen("CON", "wt", stdout);
    freopen("CON", "wt", stderr);
    freopen("CON", "rt", stdin);

void CloseCon(void)
Kenneth Rochel de Camargo, Jr. MD PhD
Associate Professor - Social Medicine Institute
Rio de Janeiro State U. - Brazil