static int enableRawMode(struct current *current) {
DWORD n;
INPUT_RECORD irec;
current->outh = GetStdHandle(STD_OUTPUT_HANDLE);
current->inh = GetStdHandle(STD_INPUT_HANDLE);
if (!PeekConsoleInput(current->inh, &irec, 1, &n)) {
return -1;
if (getWindowSize(current) != 0) {
return -1;
if (GetConsoleMode(current->inh, &orig_consolemode)) {
SetConsoleMode(current->inh, ENABLE_PROCESSED_INPUT);
return 0;
}
OOP Simple Examples
static void installsighandler()
#ifndef _WIN32
signal(SIGHUP,sighandler);
signal(SIGUSR1,sighandler);
signal(SIGPIPE,sighandler);
#endif
signal(SIGINT,sighandler);
#ifdef _WIN32
SetConsoleCtrlHandler(ConsoleCtrlHandler,true);
HANDLE hs=GetStdHandle(STD_INPUT_HANDLE);
DWORD mode;
if (GetConsoleMode(hs,&mode)) {
mode|=ENABLE_PROCESSED_INPUT;
SetConsoleMode(hs,mode);
#endif
}
extern void ConsoleInit(void)
CONSOLE_CURSOR_INFO cci;
int i;
/* コンソール標準出力画面のハンドルを取得。プログラム終了時にアクティブ化 */
m_hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
if (m_hStdOut == INVALID_HANDLE_VALUE)
fprintf(stderr, "error: Console: InitConsole: hStdOut: %ld\n", GetLastError());
/* コンソールスクリーンの作成と初期化 */
for (i=0; i<NUM_SCREEN_MAX; i++)
m_hScreen[i] = CreateConsoleScreenBuffer(
GENERIC_READ | GENERIC_WRITE,
NULL,
CONSOLE_TEXTMODE_BUFFER,
if (m_hScreen[i] == INVALID_HANDLE_VALUE)
fprintf(stderr, "error: Console: InitConsole: %ld\n", GetLastError());
/* カーソル情報の初期化 */
GetConsoleCursorInfo(m_hScreen[i], &cci);
cci.bVisible = FALSE;// カーソルの非表示
SetConsoleCursorInfo(m_hScreen[i], &cci);
/* ウィンドウサイズの初期化 */
SetWindowSize(m_hScreen[i], NUM_WINDOW_HEIGHT, NUM_WINDOW_WIDTH);
/* コンソールモードの初期化 */
SetConsoleMode(m_hScreen[i], ENABLE_PROCESSED_OUTPUT);
m_hScreenIndex = 0;
m_hOut = m_hScreen[1];
m_hWork = m_hScreen[0];
SetConsoleActiveScreenBuffer(m_hOut);// 出力スクリーンをアクティブ化
}
/* initialize console */
void oss_con_init(void)
DWORD new_console_mode;
OSVERSIONINFO ver_info;
/* get the console input and output handles */
G_out_bufhdl = GetStdHandle(STD_OUTPUT_HANDLE);
G_in_bufhdl = GetStdHandle(STD_INPUT_HANDLE);
/* get the original console mode so we can restore it when we're done */
GetConsoleMode(G_out_bufhdl, &S_orig_console_out_mode);
GetConsoleMode(G_in_bufhdl, &S_orig_console_in_mode);
/* if we're in 'plain' mode, don't change the console mode */
if (os_f_plain)
return;
/* start with the original console mode bits */
new_console_mode = S_orig_console_out_mode;
* Turn off wrapping when writing at the end of the line - the
* automatic wrapping screws up our scrolling, and we don't need it
* anyway since we keep track of all of our cursor positioning
* ourselves, hence it's easier if we just turn this feature off
new_console_mode &= ~ENABLE_WRAP_AT_EOL_OUTPUT;
* If we're on a 95 derivative (95, 98, ME), also clear the "processed
* output" flag. This flag is necessary on NT for proper character
* set handling, but is not on 95/98/ME; and if that flag isn't
* cleared on 95/98/ME, clearing the wrap-at-eol flag has no effect.
* So, we must clear this flag on 95/98/ME, but we must leave it
* enabled on NT. (What a pain.)
ver_info.dwOSVersionInfoSize = sizeof(ver_info);
GetVersionEx(&ver_info);
if (ver_info.dwPlatformId != VER_PLATFORM_WIN32_NT)
new_console_mode &= ~ENABLE_PROCESSED_OUTPUT;
/* set the new console mode */
SetConsoleMode(G_out_bufhdl, new_console_mode);
}
/*--------------------------------------------------------------------------*/
void InitializeTerminal(void)
if (!Win32InputStream)
Win32InputStream = GetStdHandle(STD_INPUT_HANDLE);
GetConsoleMode(Win32InputStream, &OldWin32Mode);
SetConsoleMode(Win32InputStream, ENABLE_PROCESSED_INPUT);
if (!Win32OutputStream)
Win32OutputStream = GetStdHandle(STD_OUTPUT_HANDLE);
setFocusOnConsole();
SetConsoleCtrlHandler( (PHANDLER_ROUTINE) CtrlHandler, TRUE );
}
/*
==================
CON_Init
==================
void CON_Init (void)
CONSOLE_CURSOR_INFO curs;
CONSOLE_SCREEN_BUFFER_INFO info;
int i;
// handle Ctrl-C or other console termination
SetConsoleCtrlHandler(CON_CtrlHandler, TRUE);
qconsole_hin = GetStdHandle(STD_INPUT_HANDLE);
if (qconsole_hin == INVALID_HANDLE_VALUE)
return;
qconsole_hout = GetStdHandle(STD_OUTPUT_HANDLE);
if (qconsole_hout == INVALID_HANDLE_VALUE)
return;
GetConsoleMode(qconsole_hin, &qconsole_orig_mode);
// allow mouse wheel scrolling
SetConsoleMode(qconsole_hin, qconsole_orig_mode & ~ENABLE_MOUSE_INPUT);
FlushConsoleInputBuffer(qconsole_hin);
GetConsoleScreenBufferInfo(qconsole_hout, &info);
qconsole_attrib = info.wAttributes;
qconsole_backgroundAttrib = qconsole_attrib & (BACKGROUND_BLUE | BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_INTENSITY);
SetConsoleTitle("Dedicated Server Console");
// make cursor invisible
GetConsoleCursorInfo(qconsole_hout, &qconsole_orig_cursorinfo);
curs.dwSize = 1;
curs.bVisible = FALSE;
SetConsoleCursorInfo(qconsole_hout, &curs);
// initialize history
for (i = 0; i < QCONSOLE_HISTORY; i++)
qconsole_history[i][0] = '\0';
// set text color to white
SetConsoleTextAttribute(qconsole_hout, CON_ColorCharToAttrib(COLOR_WHITE));
}
WindowsInputController::WindowsInputController() {
HANDLE hStdin;
DWORD fdwMode, fdwSaveOldMode;
// Get the standard input handle.
hStdin = GetStdHandle( STD_INPUT_HANDLE );
if( hStdin == INVALID_HANDLE_VALUE )
return;
// Save the current input mode, to be restored on exit.
if( !GetConsoleMode(hStdin, &fdwSaveOldMode) )
return;
// Enable the window and mouse input events.
fdwMode = ENABLE_WINDOW_INPUT | ENABLE_MOUSE_INPUT;
if( !SetConsoleMode(hStdin, fdwMode) )
return;
}
DWORD CPequote::Start()
//CEgRegKey key;
CModuleVersion ver;
TCHAR pModName [1024] = { 0 };
TCHAR pVer[100] = { 0 };
//detecting the module version
::GetModuleFileName( NULL, pModName, sizeof(pModName)/sizeof(TCHAR));
ver.GetModuleVersionInfo(pModName);
ver.GetValue(_T("ProductVersion"), pVer);
DWORD dwFlags;
if(GetConsoleMode(GetStdHandle(STD_INPUT_HANDLE), &dwFlags))
dwFlags &= ~(ENABLE_QUICK_EDIT | ENABLE_INSERT_MODE);
SetConsoleMode(GetStdHandle(STD_INPUT_HANDLE), dwFlags);
m_hStopApplication = ::CreateEvent(NULL, TRUE, FALSE, NULL);
if (!m_hStopApplication)
return TraceError();
if (!::SetConsoleCtrlHandler(HandlerRoutine, TRUE))
return TraceError();
CTracer::TraceMessage(CTracer::enMtInformation, NULL, _T("Starting Pequote connector..."));
DWORD dwRes = m_PequoteConnector.Start(NULL);
if (dwRes)
CTracer::TraceMessage(CTracer::enMtError, NULL, _T("Failed to start Pequote connector."));
return dwRes;
CTracer::TraceMessage(CTracer::enMtInformation, NULL, _T("Pequote connector started."));
CTracer::TraceMessage(CTracer::enMtInformation, NULL, _T("Server started."));
return 0;
}
static int noecho_console(UI *ui)
#ifdef TTY_FLAGS
memcpy(&(tty_new), &(tty_orig), sizeof(tty_orig));
tty_new.TTY_FLAGS &= ~ECHO;
#endif
#if defined(TTY_set) && !defined(OPENSSL_SYS_VMS)
if (is_a_tty && (TTY_set(fileno(tty_in), &tty_new) == -1))
return 0;
#endif
#ifdef OPENSSL_SYS_VMS
if (is_a_tty) {
tty_new[0] = tty_orig[0];
tty_new[1] = tty_orig[1] | TT$M_NOECHO;
tty_new[2] = tty_orig[2];
status = sys$qiow(0, channel, IO$_SETMODE, &iosb, 0, 0, tty_new, 12,
0, 0, 0, 0);
if ((status != SS$_NORMAL) || (iosb.iosb$w_value != SS$_NORMAL)) {
char tmp_num[2][12];
BIO_snprintf(tmp_num[0], sizeof(tmp_num[0]) - 1, "%%X%08X",
status);
BIO_snprintf(tmp_num[1], sizeof(tmp_num[1]) - 1, "%%X%08X",
iosb.iosb$w_value);
UIerr(UI_F_NOECHO_CONSOLE, UI_R_SYSQIOW_ERROR);
ERR_add_error_data(5, "status=", tmp_num[0],
",", "iosb.iosb$w_value=", tmp_num[1]);
return 0;
#endif
#if defined(_WIN32) && !defined(_WIN32_WCE)
if (is_a_tty) {
tty_new = tty_orig;
tty_new &= ~ENABLE_ECHO_INPUT;
SetConsoleMode(GetStdHandle(STD_INPUT_HANDLE), tty_new);
#endif
return 1;
}
/*
* initialize the terminal data structures.
void init_terminal(void) {
if (ttyoring.init(2*BUFSIZ, ttysink, NULL) != 1) {
exit(1);
if (ttyiring.init(BUFSIZ, NULL, ttysrc) != 1) {
exit(1);
autoflush = TerminalAutoFlush();
#ifdef __WIN32__
* Set the console mode. This will only have an effect if the
* handle is a console handle
HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
#if 0
printf("1. Calling SetConsoleMode(0x%08x, 0x%08x)\n",
hOut, ENABLE_PROCESSED_OUTPUT|ENABLE_WRAP_AT_EOL_OUTPUT);
#endif
SetConsoleMode(hOut, ENABLE_PROCESSED_OUTPUT|ENABLE_WRAP_AT_EOL_OUTPUT);
#endif
}
void stdin_echo(bool enable) #ifdef WIN32 HANDLE hStdin=GetStdHandle(STD_INPUT_HANDLE); DWORD mode; GetConsoleMode(hStdin,&mode); if(!enable) mode&=~ENABLE_ECHO_INPUT; mode|=ENABLE_ECHO_INPUT; SetConsoleMode(hStdin, mode ); #else struct termios tty; tcgetattr(STDIN_FILENO,&tty); if(!enable) tty.c_lflag&=~ECHO; tty.c_lflag|=ECHO; tcsetattr(STDIN_FILENO,TCSANOW,&tty); #endif }
static void termset(void) DWORD flag; if(donetermset) return; donetermset = 1; conh = GetStdHandle(STD_OUTPUT_HANDLE); kbdh = GetStdHandle(STD_INPUT_HANDLE); errh = GetStdHandle(STD_ERROR_HANDLE); if(errh == INVALID_HANDLE_VALUE) errh = conh; // The following will fail if kbdh not from console (e.g. a pipe) // in which case we don't care GetConsoleMode(kbdh, &consolestate); flag = consolestate; flag = flag & ~(ENABLE_PROCESSED_INPUT|ENABLE_LINE_INPUT|ENABLE_ECHO_INPUT); SetConsoleMode(kbdh, flag); }
/** get a character from the terminal */
mygetch(void)
#if !defined(_WIN32) || !defined(__CYGWIN__)
/* longjmp won't work, it's in a different thread */
sighandler_t savesig; /* old value of signal */
#endif
int c;
/* change an interrupt signal to a break key character */
if (setjmp(env) == 0) {
#if defined(_WIN32) && !defined(__CYGWIN__)
/* turn off Ctrl+C handling (PDCurses does this, but it gets turned on
again by CMD during system) */
SetConsoleMode( GetStdHandle( STD_INPUT_HANDLE ), 0 );
#else
savesig = signal(SIGINT, catchint);
#endif
refresh(); /* update the display */
mousereinit(); /* curses can change the menu number */
if(prevchar) {
c = prevchar;
prevchar = 0;
} else {
c = -1;
while (c == -1) {
/* get a character from the terminal */
c = getch();
if ((c == -1) && (errno != EINTR))
break;
} else { /* longjmp to here from signal handler */
c = KEY_BREAK;
#if !defined(_WIN32) || !defined(__CYGWIN__)
signal(SIGINT, savesig);
#endif
return(c);
}
/* ================== CON_Init ================== void CON_Init( void ) CONSOLE_SCREEN_BUFFER_INFO info; char consoleTitle[128]; int i; // handle Ctrl-C or other console termination SetConsoleCtrlHandler( CON_CtrlHandler, TRUE ); qconsole_hin = GetStdHandle( STD_INPUT_HANDLE ); if( qconsole_hin == INVALID_HANDLE_VALUE ) return; qconsole_hout = GetStdHandle( STD_OUTPUT_HANDLE ); if( qconsole_hout == INVALID_HANDLE_VALUE ) return; GetConsoleMode( qconsole_hin, &qconsole_orig_mode ); // allow mouse wheel scrolling SetConsoleMode( qconsole_hin, qconsole_orig_mode & ~ENABLE_MOUSE_INPUT ); FlushConsoleInputBuffer( qconsole_hin ); GetConsoleScreenBufferInfo( qconsole_hout, &info ); qconsole_attrib = info.wAttributes; qconsole_backgroundAttrib = qconsole_attrib & (BACKGROUND_BLUE|BACKGROUND_GREEN|BACKGROUND_RED|BACKGROUND_INTENSITY); // ZTM: FIXME: com_productName isn't initialized or set to game title yet. Com_sprintf( consoleTitle, sizeof (consoleTitle), "%s Dedicated Server Console", com_productName ? com_productName->string : PRODUCT_NAME ); SetConsoleTitle( consoleTitle ); // initialize history for( i = 0; i < QCONSOLE_HISTORY; i++ ) qconsole_history[ i ][ 0 ] = '\0'; // set text color to white SetConsoleTextAttribute( qconsole_hout, CON_ColorCharToAttrib( COLOR_WHITE ) ); }
static char * readpassphrase(const char *prompt, char *buf, size_t bufsiz, int flags) HANDLE hStdin, hStdout; DWORD mode, rbytes; BOOL success; (void)flags; hStdin = GetStdHandle(STD_INPUT_HANDLE); if (hStdin == INVALID_HANDLE_VALUE) return (NULL); hStdout = GetStdHandle(STD_OUTPUT_HANDLE); if (hStdout == INVALID_HANDLE_VALUE) return (NULL); success = GetConsoleMode(hStdin, &mode); if (!success) return (NULL); mode &= ~ENABLE_ECHO_INPUT; mode |= ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT; success = SetConsoleMode(hStdin, mode); if (!success) return (NULL); success = WriteFile(hStdout, prompt, (DWORD)strlen(prompt), NULL, NULL); if (!success) return (NULL); success = ReadFile(hStdin, buf, (DWORD)bufsiz - 1, &rbytes, NULL); if (!success) return (NULL); WriteFile(hStdout, "\r\n", 2, NULL, NULL); buf[rbytes] = '\0'; /* Remove trailing carriage return(s). */ if (rbytes > 2 && buf[rbytes - 2] == '\r' && buf[rbytes - 1] == '\n') buf[rbytes - 2] = '\0'; return (buf); }
/*
==================
CON_Init
==================
void CON_Init( void )
CONSOLE_CURSOR_INFO curs;
CONSOLE_SCREEN_BUFFER_INFO info;
int i;
// handle Ctrl-C or other console termination
SetConsoleCtrlHandler( CON_CtrlHandler, TRUE );
qconsole_hin = GetStdHandle( STD_INPUT_HANDLE );
if( qconsole_hin == INVALID_HANDLE_VALUE )
return;
qconsole_hout = GetStdHandle( STD_OUTPUT_HANDLE );
if( qconsole_hout == INVALID_HANDLE_VALUE )
return;
GetConsoleMode( qconsole_hin, &qconsole_orig_mode );
// allow mouse wheel scrolling
SetConsoleMode( qconsole_hin,
qconsole_orig_mode & ~ENABLE_MOUSE_INPUT );
FlushConsoleInputBuffer( qconsole_hin );
GetConsoleScreenBufferInfo( qconsole_hout, &info );
qconsole_attrib = info.wAttributes;
SetConsoleTitle("ioquake3 Dedicated Server Console");
// make cursor invisible
GetConsoleCursorInfo( qconsole_hout, &qconsole_orig_cursorinfo );
curs.dwSize = 1;
curs.bVisible = FALSE;
SetConsoleCursorInfo( qconsole_hout, &curs );
// initialize history
for( i = 0; i < QCONSOLE_HISTORY; i++ )
qconsole_history[ i ][ 0 ] = '\0';
}
int ty_terminal_setup(int flags)
HANDLE handle;
DWORD mode;
BOOL r;
handle = GetStdHandle(STD_INPUT_HANDLE);
if (handle == INVALID_HANDLE_VALUE)
return ty_error(TY_ERROR_SYSTEM, "GetStdHandle(STD_INPUT_HANDLE) failed");
r = GetConsoleMode(handle, &mode);
if (!r) {
if (GetLastError() == ERROR_INVALID_HANDLE)
return ty_error(TY_ERROR_UNSUPPORTED, "Not a terminal");
return ty_error(TY_ERROR_SYSTEM, "GetConsoleMode(STD_INPUT_HANDLE) failed: %s",
ty_win32_strerror(0));
if (!saved_console_mode) {
orig_console_mode = mode;
saved_console_mode = true;
atexit(ty_terminal_restore);
mode |= ENABLE_PROCESSED_INPUT;
mode &= (DWORD)~(ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT);
if (!(flags & TY_TERMINAL_RAW))
mode |= ENABLE_LINE_INPUT;
if (!(flags & TY_TERMINAL_SILENT))
mode |= ENABLE_ECHO_INPUT;
r = SetConsoleMode(handle, mode);
if (!r)
return ty_error(TY_ERROR_SYSTEM, "SetConsoleMode(STD_INPUT_HANDLE) failed: %s",
ty_win32_strerror(0));
return 0;
}
bool input_waiting()
#ifndef WIN32
fd_set readfds;
struct timeval tv;
FD_ZERO(&readfds);
FD_SET(fileno(stdin), &readfds);
tv.tv_sec = 0;
tv.tv_usec = 0;
select(16, &readfds, nullptr, nullptr, &tv);
return (FD_ISSET(fileno(stdin), &readfds));
#else
static int init = 0, pipe;
static HANDLE inh;
DWORD dw;
if(!init)
init = 1;
inh = GetStdHandle(STD_INPUT_HANDLE);
pipe = !GetConsoleMode(inh, &dw);
if(!pipe)
SetConsoleMode(inh, dw & ~(ENABLE_MOUSE_INPUT|ENABLE_WINDOW_INPUT));
FlushConsoleInputBuffer(inh);
if(pipe)
if(!PeekNamedPipe(inh, NULL, 0, NULL, &dw, NULL)) return 1;
return dw;
GetNumberOfConsoleInputEvents(inh, &dw);
return dw <= 1 ? 0 : dw;
#endif // WIN32
}
void FileTests::TestReadFileBasicSync()
HANDLE const hIn = GetStdInputHandle();
VERIFY_IS_NOT_NULL(hIn, L"Verify we have the standard input handle.");
DWORD dwMode = 0;
VERIFY_WIN32_BOOL_SUCCEEDED(SetConsoleMode(hIn, dwMode), L"Set input mode for test.");
VERIFY_WIN32_BOOL_SUCCEEDED(FlushConsoleInputBuffer(hIn), L"Flush input buffer in preparation for test.");
char const chExpected = 'a';
Log::Comment(L"Send a key into the console.");
SendFullKeyStrokeHelper(hIn, chExpected);
char ch = '\0';
Log::Comment(L"Read with synchronous blocking read.");
DWORD dwRead = 0;
VERIFY_WIN32_BOOL_SUCCEEDED(ReadFile(hIn, &ch, 1, &dwRead, nullptr), L"Read file was successful.");
VERIFY_ARE_EQUAL(1u, dwRead, L"Verify we read 1 character.");
VERIFY_ARE_EQUAL(chExpected, ch);
}
void CMap::SetDefault()
{ // This is the desired size of our window
SMALL_RECT newSize = {0, 0, kMapWidth - 1, kMapHeight - 1};
HANDLE hOutput = GetStdHandle(STD_OUTPUT_HANDLE); // Get a OUTPUT handle to our screen.
HANDLE hInput = GetStdHandle(STD_INPUT_HANDLE); // Get a INPUT handle to our screen.
// We actually change our window size from the normal size of (80, 15} to {80, 45}.
SetConsoleWindowInfo(hOutput, TRUE, &newSize);
// Next we want to be able to have mouse input and other keyboard input
SetConsoleMode(hInput, ENABLE_PROCESSED_INPUT | ENABLE_MOUSE_INPUT);
// Make sure we clear and release all the data with our global lists
m_vTiles.clear();
m_vItems.clear();
m_vMonsters.clear();
m_vNpcs.clear();
m_vExits.clear();
// Reset the current map's name
strcpy(m_szMapName, "");
}
int main(int argc, char const *argv[])
if(argc < 3)
cout << "Usage: encryptor InputFileName OutputFileName" << endl << "Terminating..." << endl;
return 0;
//Text hiding method by guestgulkan on cplusplus forum
HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE);
DWORD mode = 0;
GetConsoleMode(hStdin, &mode);
SetConsoleMode(hStdin, mode & (~ENABLE_ECHO_INPUT));
string key;
string input;
string output;
FileHandler inputFile(true);
if(!inputFile.setFileName(argv[1]))
return 0;
FileHandler outputFile(false);
outputFile.setFileName(argv[2]);
cout << "Please enter your session key:" << endl;
getline(cin, key);
input = *inputFile.get();
Encryptor enc(key, input);
output = enc.crypt();
outputFile.write(output);
return 0;
}
void Apep::initialize(std::string name, int width_ = 80, int height_ = 60) {
tin = GetStdHandle(STD_INPUT_HANDLE);
tout = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTitle(name.c_str());
{ // hide console cursor
CONSOLE_CURSOR_INFO cci;
GetConsoleCursorInfo(tout, &cci);
cci.bVisible = false;
cci.dwSize = 1;
SetConsoleCursorInfo(tout, &cci);
width = width_;
height = height_;
assert("width must be > 1!" && width > 1);
assert("height must be > 1!" && height > 1);
// resizing console window
SMALL_RECT cs = { 0, 0, width - 1, height - 1 };
consoleSize = cs;
COORD bs = { width, height };
buffSize = bs;
SetConsoleWindowInfo(tout, TRUE, &consoleSize);
SetConsoleScreenBufferSize(tout, buffSize);
{ // turning off showing keys being pressed
DWORD mode;
GetConsoleMode(tin, &mode);
SetConsoleMode(tin, mode & ~ENABLE_ECHO_INPUT);
// allocating back buffer
total_size = width * height;
back_buffer = new CHAR_INFO[total_size];
}
void FileTests::TestReadFileLine()
HANDLE const hIn = GetStdInputHandle();
VERIFY_IS_NOT_NULL(hIn, L"Verify we have the standard input handle.");
DWORD dwMode = ENABLE_LINE_INPUT;
VERIFY_WIN32_BOOL_SUCCEEDED(SetConsoleMode(hIn, dwMode), L"Set input mode for test.");
VERIFY_WIN32_BOOL_SUCCEEDED(FlushConsoleInputBuffer(hIn), L"Flush input buffer in preparation for test.");
char ch = '\0';
Log::Comment(L"Queue background blocking read file operation.");
auto BackgroundRead = std::async([&] {
DWORD dwRead = 0;
VERIFY_WIN32_BOOL_SUCCEEDED(ReadFile(hIn, &ch, 1, &dwRead, nullptr), L"Read file was successful.");
VERIFY_ARE_EQUAL(1u, dwRead, L"Verify we read 1 character.");
char const chExpected = 'a';
Log::Comment(L"Send a key into the console.");
SendFullKeyStrokeHelper(hIn, chExpected);
auto status = BackgroundRead.wait_for(std::chrono::milliseconds(250));
VERIFY_ARE_EQUAL(std::future_status::timeout, status, L"We should still be waiting for a result.");
VERIFY_ARE_EQUAL('\0', ch, L"Character shouldn't be filled by background read yet.");
Log::Comment(L"Send a line feed character, we should stay blocked.");
SendFullKeyStrokeHelper(hIn, '\n');
status = BackgroundRead.wait_for(std::chrono::milliseconds(250));
VERIFY_ARE_EQUAL(std::future_status::timeout, status, L"We should still be waiting for a result.");
VERIFY_ARE_EQUAL('\0', ch, L"Character shouldn't be filled by background read yet.");
Log::Comment(L"Now send a carriage return into the console to signify the end of the input line.");
SendFullKeyStrokeHelper(hIn, '\r');
Log::Comment(L"Wait for background thread to unblock.");
BackgroundRead.wait();
VERIFY_ARE_EQUAL(chExpected, ch);
}
/* Turn off buffering on stdin. */
void add_anykey(void)
#ifdef _WIN32
stdin_handle = GetStdHandle(STD_INPUT_HANDLE);
if (!GetConsoleMode(stdin_handle, &stdin_mode)) {
/* TODO: Error handling. */
SetConsoleMode(stdin_handle, 0);
#else
struct termios term;
tcgetattr(STDIN_FILENO, &term);
memcpy(&term_orig, &term, sizeof(struct termios));
term.c_lflag &= ~(ECHO | ICANON | ISIG);
tcsetattr(STDIN_FILENO, TCSADRAIN, &term);
#endif
sr_session_source_add(STDIN_FILENO, G_IO_IN, -1, received_anykey, NULL);
printf("Press any key to stop acquisition.\n");
}
void FileTests::TestReadFileLineSync()
HANDLE const hIn = GetStdInputHandle();
VERIFY_IS_NOT_NULL(hIn, L"Verify we have the standard input handle.");
DWORD dwMode = ENABLE_LINE_INPUT;
VERIFY_WIN32_BOOL_SUCCEEDED(SetConsoleMode(hIn, dwMode), L"Set input mode for test.");
VERIFY_WIN32_BOOL_SUCCEEDED(FlushConsoleInputBuffer(hIn), L"Flush input buffer in preparation for test.");
char const chExpected = 'a';
Log::Comment(L"Send a key into the console followed by a carriage return.");
SendFullKeyStrokeHelper(hIn, chExpected);
SendFullKeyStrokeHelper(hIn, '\r');
char ch = '\0';
Log::Comment(L"Read back the input with a synchronous blocking read.");
DWORD dwRead = 0;
VERIFY_WIN32_BOOL_SUCCEEDED(ReadFile(hIn, &ch, 1, nullptr, nullptr), L"Read file was successful.");
VERIFY_ARE_EQUAL(0u, dwRead, L"Verify we read 0 characters.");
VERIFY_ARE_EQUAL(chExpected, ch);
}
bool Util::enableConsoleEcho(const bool enable) bool originalValue = true; #ifdef Q_OS_WIN DWORD mode; HANDLE hConIn = GetStdHandle( STD_INPUT_HANDLE ); GetConsoleMode( hConIn, &mode ); originalValue = (mode & (ENABLE_ECHO_INPUT)); mode = enable ? (mode | ENABLE_ECHO_INPUT ) : (mode & ~(ENABLE_ECHO_INPUT)); SetConsoleMode( hConIn, mode ); #else struct termios settings; tcgetattr( STDIN_FILENO, &settings ); originalValue = (settings.c_lflag & (ECHO)); settings.c_lflag = enable ? (settings.c_lflag | ECHO ) : (settings.c_lflag & ~(ECHO)); tcsetattr( STDIN_FILENO, TCSANOW, &settings ); #endif return originalValue; }
// returns a char of the current key pressed char Console::InputChar() SetConsoleMode(hInput, ENABLE_PROCESSED_INPUT); // check to see if there are any input records GetNumberOfConsoleInputEvents(hInput,&charsRead); // get input if (charsRead > 0) ReadConsoleInput(hInput,&InputRecords[0],255,&charsRead); for(int Count = charsRead; Count >= 0; --Count) if (InputRecords[Count].EventType == KEY_EVENT) if (InputRecords[Count].Event.KeyEvent.bKeyDown != 0) return InputRecords[Count].Event.KeyEvent.uChar.AsciiChar; // if we didn't get anything return 0; return 0; }
void CConsole::initconsole()
conin = GetStdHandle(STD_INPUT_HANDLE);
conout = GetStdHandle(STD_OUTPUT_HANDLE);
ZeroMemory(&ovc,sizeof(ovc));
ovc.hEvent = CreateEvent(NULL,FALSE,FALSE,NULL);
if(ovc.hEvent == INVALID_HANDLE_VALUE) {
throw errors("CreateEvent error");
SetConsoleMode(conin,ENABLE_MOUSE_INPUT);
GetConsoleScreenBufferInfo(conout,&csb);
if (csb.dwSize.X<80||csb.dwSize.Y<25){
CloseHandle(ovc.hEvent);
throw errors("console size is too small");
FlushConsoleInputBuffer(conin);
head=tail=0;
cci.bVisible=0;cci.dwSize=10;
SetConsoleCursorInfo(conout,&cci);
SetConsoleTitle(jmail);
}
BOOL
consoleSetMode (
KBDMODE Mode
Routine Description:
Sets the console mode.
Arguments:
Mode - Supplies the mode flags.
Return Value:
TRUE if success, FALSE otherwise
return SetConsoleMode( hInput,
Mode );
}
/*
* cuiInitialize
* Purpose:
* Initialize console input/output.
VOID cuiInitialize(
_In_ BOOL InitInput,
_Out_opt_ PBOOL IsConsoleOutput
ULONG dummy;
g_ConOut = GetStdHandle(STD_OUTPUT_HANDLE);
if (InitInput) g_ConIn = GetStdHandle(STD_INPUT_HANDLE);
SetConsoleMode(g_ConOut, ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT | ENABLE_PROCESSED_OUTPUT);
g_ConsoleOutput = TRUE;
if (!GetConsoleMode(g_ConOut, &dummy)) {
g_ConsoleOutput = FALSE;
WriteFile(g_ConOut, &g_BE, sizeof(WCHAR), &dummy, NULL);
if (IsConsoleOutput)
*IsConsoleOutput = g_ConsoleOutput;
return;
}