static int noecho_fgets(char *buf, int size, FILE *tty) { int i; char *p; p=buf; for (;;) { if (size == 0) { *p='\0'; break; } size--; #ifdef WIN16TTY i=_inchar(); #elif defined(_WIN32) i=_getch(); #else i=getch(); #endif if (i == '\r') i='\n'; *(p++)=i; if (i == '\n') { *p='\0'; break; } } #ifdef WIN_CONSOLE_BUG /* Win95 has several evil console bugs: one of these is that the * last character read using getch() is passed to the next read: this is * usually a CR so this can be trouble. No STDIO fix seems to work but * flushing the console appears to do the trick. */ { HANDLE inh; inh = GetStdHandle(STD_INPUT_HANDLE); FlushConsoleInputBuffer(inh); } #endif return(strlen(buf)); }
/* Read console events until there is a key event. Also returns on any error. */ static void wait_for_console_key(void) { HANDLE hConsoleInput = GetStdHandle(STD_INPUT_HANDLE); if (!ELEM(hConsoleInput, NULL, INVALID_HANDLE_VALUE) && FlushConsoleInputBuffer(hConsoleInput)) { for (;;) { INPUT_RECORD buffer; DWORD ignored; if (!ReadConsoleInput(hConsoleInput, &buffer, 1, &ignored)) { break; } if (buffer.EventType == KEY_EVENT) { break; } } } }
void BaseApp::Run() { CStopwatch timer; int sum = 0; int counter = 0; int deltaTime = 0; while (1) { timer.Start(); if (kbhit()) { KeyPressed (getch()); if (!FlushConsoleInputBuffer(mConsoleIn)) cout<<"FlushConsoleInputBuffer failed with error "<<GetLastError(); } UpdateF((float)deltaTime / 1000.0f); Render(); Sleep(1); while (1) { deltaTime = timer.Now(); if (deltaTime > 20) break; } sum += deltaTime; counter++; if (sum >= 1000) { TCHAR szbuff[255]; StringCchPrintf(szbuff, 255, TEXT("FPS: %d"), counter); SetConsoleTitle(szbuff); counter = 0; sum = 0; } } }
void CMap::CheckForNpc(int x, int y) { // Go through all of the npcs and see if we have a match for the position for(int i = 0; i < (int)m_vNpcs.size(); i++) { CNpc *pNpc= &m_vNpcs[i]; // Check if this npc has the same position as the position passed in if(x == pNpc->GetIndex().X && y == pNpc->GetIndex().Y) { // Move the player back so they aren't on the NPC g_Player.MovePlayerBack(); //////////// *** NEW *** ////////// *** NEW *** ///////////// *** NEW *** //////////////////// // Since we have cut scenes and eventual shop keepers, we first check // to see if there is any action key assigned with the npc before we // let them speak. If they do, we want to use that dialog and not // the standard dialog that they would spit out. Like Jax's case. if(pNpc->GetActionKey()) { // Handle the action key and return g_ActionKeys.HandleKey(pNpc->GetActionKey(), pNpc); return; } //////////// *** NEW *** ////////// *** NEW *** ///////////// *** NEW *** //////////////////// // Display the NPC message, pause, then clear the input buffer and wait for a key char szDialog[5000] = {0}; sprintf(szDialog, "%s: %s", pNpc->GetName(), pNpc->GetMessage()); DisplayDialog(szDialog); Sleep(1000); FlushConsoleInputBuffer(GetStdHandle(STD_INPUT_HANDLE)); getch(); break; } } }
/* ================== 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 ) ); }
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; } else { GetNumberOfConsoleInputEvents(inh, &dw); return dw <= 1 ? 0 : dw; } #endif // WIN32 }
/* ================== 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 getKey() { int key; DWORD cNumRead; INPUT_RECORD irInBuf; HANDLE hStdIn = GetStdHandle(STD_INPUT_HANDLE); do { FlushConsoleInputBuffer(hStdIn); do { ReadConsoleInput(hStdIn, &irInBuf, 1, &cNumRead); } while (irInBuf.EventType != KEY_EVENT || irInBuf.Event.KeyEvent.bKeyDown); if (irInBuf.Event.KeyEvent.uChar.AsciiChar == 0) { key = irInBuf.Event.KeyEvent.wVirtualKeyCode; } else key = irInBuf.Event.KeyEvent.uChar.AsciiChar; } while (key != ESCAPE && key != LEFT && key != UP && key != RIGHT && key != DOWN && key != ENTER); return key; }
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); }
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 initializeWorld(){ hConsole = GetStdHandle(STD_OUTPUT_HANDLE); FlushConsoleInputBuffer(hConsole); drawTable(); rotatingBar(WIDTH/2, HEIGHT/2, 0); gotoxy(0,0); SetConsoleTextAttribute(hConsole, colors[0]); printf("O"); SetConsoleTextAttribute(hConsole, colors[1]); gotoxy(WIDTH,0); printf("O"); SetConsoleTextAttribute(hConsole, colors[2]); gotoxy(WIDTH,HEIGHT); printf("O"); SetConsoleTextAttribute(hConsole, colors[3]); gotoxy(0,HEIGHT); printf("O"); }
void __declspec(noreturn) exit() { // EnableMenuItem(GetSystemMenu(GetConsoleWindow(), FALSE), SC_CLOSE, MF_ENABLED); exitflag = 1; if (savesndtype) savesnddialog(); if (videosaver_state) main_savevideo(); // stop saving video if (!normal_exit) done_fdd(false); done_tape(); done_dx(); done_gs(); done_leds(); save_nv(); zf232.rs_close(); zf232.zf_close(); done_ie_help(); done_bpx(); GdiplusShutdown(); // timeEndPeriod(1); if (ay[1].Chip2203) YM2203Shutdown(ay[1].Chip2203); //Dexus if (ay[0].Chip2203) YM2203Shutdown(ay[0].Chip2203); //Dexus if (comp.ts.vdac2) vdac2::close_ft8xx(); color(); printf("\nsee you later!\n"); if (!nowait) { SetConsoleTitle("press a key..."); FlushConsoleInputBuffer(GetStdHandle(STD_INPUT_HANDLE)); getch(); } fflush(stdout); SetConsoleCtrlHandler(ConsoleHandler, FALSE); exit(0); }
int tty_getchar() { HANDLE stdinHandle = GetStdHandle (STD_INPUT_HANDLE); DWORD rc = WaitForSingleObject (stdinHandle, 1000); if (rc == WAIT_TIMEOUT) return 0; if (rc == WAIT_ABANDONED) return -1; if (rc == WAIT_FAILED) return -1; // The whole ReadConsoleInput () part is a workaround. // For some unknown reason, maybe a mingw bug, a random signal // is sent to stdin which unblocks WaitForSingleObject () and sets rc 0. // Then it wants to read with getche () a keyboard input // which has never been made. INPUT_RECORD buf[100]; DWORD num = 0; memset (buf, 0, sizeof (buf)); ReadConsoleInput (stdinHandle, buf, 100, &num); FlushConsoleInputBuffer (stdinHandle); for (DWORD i = 0; i < num; i++) { if (buf[i].EventType != KEY_EVENT) continue; KEY_EVENT_RECORD KeyEvent = buf[i].Event.KeyEvent; if (KeyEvent.bKeyDown != TRUE) continue; return KeyEvent.uChar.AsciiChar; } return 0; }
R_API int r_cons_readchar() { char buf[2]; buf[0] = -1; #if __WINDOWS__ && !__CYGWIN__ && !MINGW32 BOOL ret; DWORD out; DWORD mode; char b; HANDLE h = GetStdHandle (STD_INPUT_HANDLE); GetConsoleMode (h, &mode); SetConsoleMode (h, 0); // RAW ignore: if (!I->is_wine) { while (!_kbhit ()); b = getwinkey (); if (b=='2') goto ignore; else if (b=='1') ret = ReadConsole (h, buf, 1, &out, NULL); else { buf[0]=b; ret=1; } } else { ret = ReadConsole (h, buf, 1, &out, NULL); } FlushConsoleInputBuffer(h); if (!ret) return -1; SetConsoleMode (h, mode); #else r_cons_set_raw (1); if (read (0, buf, 1)==-1) return -1; r_cons_set_raw (0); #endif return r_cons_controlz (buf[0]); }
bool KConsoleDriver::readKeyExtended(char *out,bool *pressing,int *repeatCount) { #ifdef USE_M_API INPUT_RECORD inrec; dword count; FlushConsoleInputBuffer( hStdIn ); ReadConsoleInput( hStdIn, &inrec, 1, &count ); if (count > 0) { if (inrec.EventType == KEY_EVENT) { *out = inrec.Event.KeyEvent.uChar.AsciiChar; *pressing = inrec.Event.KeyEvent.bKeyDown != 0; *repeatCount = (int)inrec.Event.KeyEvent.wRepeatCount; return true; } } #endif *out = 0; return false; }
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); }
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); }
/* ================== CON_Init ================== */ void CON_Init( void ) { 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(CLIENT_WINDOW_TITLE " Dedicated Server Console"); // 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 ) ); }
void open_console() { BYTE Title[200]; BYTE ClassName[200]; LPTSTR lpClassName=ClassName; HANDLE hConWnd; FILE *hf; static BYTE consolecreated=FALSE; static int hCrt=0; if(consolecreated==TRUE) { GetConsoleTitle(Title,sizeof(Title)); hConWnd=FindWindow(NULL,Title); GetClassName(hConWnd,lpClassName,120); ShowWindow(hConWnd,SW_SHOW); SetForegroundWindow(hConWnd); hConWnd=GetStdHandle(STD_INPUT_HANDLE); FlushConsoleInputBuffer(hConWnd); return; } AllocConsole(); hCrt=_open_osfhandle((long)GetStdHandle(STD_OUTPUT_HANDLE),_O_TEXT); fflush(stdin); hf=_fdopen(hCrt,"w"); *stdout=*hf; setvbuf(stdout,NULL,_IONBF,0); GetConsoleTitle(Title,sizeof(Title)); hConWnd=FindWindow(NULL,Title); GetClassName(hConWnd,lpClassName,120); ShowWindow(hConWnd,SW_SHOW); SetForegroundWindow(hConWnd); consolecreated=TRUE; }
void EventHandle::PollInput() // Grabs input from 'GetAsyncKeyState()' { int i = 0; FlushConsoleInputBuffer(GetStdHandle(STD_INPUT_HANDLE)); if (GetAsyncKeyState(VK_LEFT) & 0x8000) { m_vKeys.push_back(VK_LEFT); ++i; } if (GetAsyncKeyState(VK_RIGHT) & 0x8000) { m_vKeys.push_back(VK_RIGHT); ++i; } if (GetAsyncKeyState(VK_UP) & 0x8000) { m_vKeys.push_back(VK_UP); ++i; } if (GetAsyncKeyState(VK_DOWN) & 0x8000) { m_vKeys.push_back(VK_DOWN); ++i; } if (GetAsyncKeyState('W') & 0x8000) { m_vKeys.push_back(0x57); ++i; } // W Key if (GetAsyncKeyState('A') & 0x8000) { m_vKeys.push_back(0x41); ++i; } // A Key if (GetAsyncKeyState('S') & 0x8000) { m_vKeys.push_back(0x53); ++i; } // S Key if (GetAsyncKeyState('D') & 0x8000) { m_vKeys.push_back(0x44); ++i; } // D Key if (GetAsyncKeyState('P') & 0x8000) { m_vKeys.push_back(0x50); ++i; } // P Key if (GetAsyncKeyState('G') & 0x8000) { m_vKeys.push_back(0x47); ++i; } // G Key if (GetAsyncKeyState('X') & 0x8000) { m_vKeys.push_back(0x58); ++i; } // X Key if (GetAsyncKeyState('F') & 0x8000) { m_vKeys.push_back(0x46); ++i; } // F Key if (GetAsyncKeyState(VK_RETURN) & 0x8000) { m_vKeys.push_back(VK_RETURN); ++i; } if (GetAsyncKeyState(VK_PRIOR) & 0x8000) { m_vKeys.push_back(VK_PRIOR); ++i; } if (GetAsyncKeyState(VK_NEXT) & 0x8000) { m_vKeys.push_back(VK_NEXT); ++i; } if (GetAsyncKeyState(VK_ESCAPE) & 0x8000) { m_vKeys.push_back(VK_ESCAPE); ++i; } OrderInput(); ParseInput(); if (!i) { m_vPrevKeys.clear(); m_vUntilPressed.clear(); m_vUntilRepeat.clear(); } }
int InputAvailable(void) { #if defined(_WIN32) || defined(_WIN64) 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 > 0; } else { GetNumberOfConsoleInputEvents(inh, &dw); return dw > 1; } #else fd_set readfds; struct timeval tv; FD_ZERO(&readfds); FD_SET(STDIN_FILENO, &readfds); tv.tv_sec = 0; tv.tv_usec = 0; select(STDIN_FILENO + 1, &readfds, NULL, NULL, &tv); return FD_ISSET(STDIN_FILENO, &readfds); #endif }
void additem() { fclose(fsal); int b; FlushConsoleInputBuffer(GetStdHandle(STD_INPUT_HANDLE)); sal1.id=0; sal1.price=0; sal1.quan=0; int id; gtc(45,13);printf("Input Item ID: ");scanf("%d",&id); fi1=fopen("mainInv.data","rb+"); while(fread(&inv1,sizeof(inv1),1,fi1)==1) { if (cID(id)==0) { gtc(45,14);printf("Item Matched! \(%s)",inv1.pName); gtc(45,15);printf("Input Quantity: ");scanf("%d",&sal1.quan); for(int a=0;a<=6;a++) { sal1.name[a]=inv1.pName[a]; } srand(time(NULL)); b=rand()%100+1; sal1.id=inv1.itemID+b; sal1.totalquan+=sal1.quan; sal1.price=inv1.price*sal1.quan; sal1.total+=sal1.price; fsal=fopen("tempsales.data","ab+"); fseek(fsal,0,SEEK_END); fwrite(&sal1,sizeof(sal1),1,fsal); fclose(fsal); gtc(45,16);printf("Added %d of %s",sal1.quan,inv1.pName); getch(); sales();exit(0); } else {
BOOL consoleFlushInput ( void ) /*++ Routine Description: Flushes input events. Arguments: None. Return Value: TRUE if success, FALSE otherwise --*/ { EventBuffer.NumberOfEvents = 0; return FlushConsoleInputBuffer( hInput ); }
bool input_available() { #if defined(_WIN32) || defined(_WIN64) static bool init = false, is_pipe; static HANDLE stdin_h; DWORD val, error; // val = 0; // needed to make the compiler happy? // have a look at the "local" buffer first, *this time before init (no idea if it helps)* if( UseDebug && !init ) printf("info string init=%d stdin->_cnt=%d\n", int(init), stdin->_cnt); if( stdin->_cnt > 0 ) return true; // input init (only done once) if( !init ) { init = true; stdin_h = GetStdHandle(STD_INPUT_HANDLE); if( UseDebug && (stdin_h == NULL || stdin_h == INVALID_HANDLE_VALUE) ) { error = GetLastError(); printf("info string GetStdHandle() failed, error=%d\n", error); } is_pipe = !GetConsoleMode(stdin_h, &val); if( UseDebug ) printf("info string init=%d is_pipe=%d\n", int(init), int(is_pipe)); if( UseDebug && is_pipe ) { // GetConsoleMode() failed, everybody assumes pipe then error = GetLastError(); printf("info string GetConsoleMode() failed, error=%d\n", error); } if( !is_pipe ) { SetConsoleMode(stdin_h, val & ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT)); FlushConsoleInputBuffer(stdin_h); // no idea if we can lose data doing this } } // different polling depending on input type // does this code work at all for pipes? if( is_pipe ) { if( !PeekNamedPipe(stdin_h, NULL, 0, NULL, &val, NULL) ) { if( UseDebug ) { // PeekNamedPipe() failed, everybody assumes EOF then error = GetLastError(); printf("info string PeekNamedPipe() failed, error=%d\n", error); } return true; } if( UseDebug && val < 0 ) printf("info string PeekNamedPipe(): val=%d\n", val); return val > 0; // != 0??? } else { GetNumberOfConsoleInputEvents(stdin_h, &val); return val > 1; // no idea why 1 } return false; #else // assume POSIX int val; fd_set set[1]; struct timeval time_val[1]; FD_ZERO(set); FD_SET(STDIN_FILENO, set); time_val->tv_sec = 0; time_val->tv_usec = 0; val = select(STDIN_FILENO + 1, set, NULL, NULL, time_val); if( val == -1 && errno != EINTR ) { my_fatal("input_available(): select(): %s\n", strerror(errno)); } return val > 0; #endif }
void win_ctrl_z(HANDLE ctrlz) { int i; int *p; DWORD rc; DWORD size; INPUT_RECORD input[EVENTSIZE]; rc = WaitForSingleObject(ctrlz, 0); if (rc == WAIT_FAILED) { fprintf(stderr, "WaitForSingleObject failed: %d\n", GetLastError()); } else if (rc == WAIT_OBJECT_0) { if (!ReadConsoleInput(ctrlz, input, EVENTSIZE, &size)) { fprintf(stderr, "ReadConsoleInput failed: %d\n", GetLastError()); } else { for (i = 0; i < size; ++i) { if (input[i].EventType == KEY_EVENT) { if (input[i].Event.KeyEvent.bKeyDown && (input[i].Event.KeyEvent.uChar.AsciiChar == 0x1A || input[i].Event.KeyEvent.uChar.AsciiChar == 0x01)) { switch (ctrlzbind) { case BIND_DPORT: p = &dst_port; break; case BIND_TTL: p = &src_ttl; break; default: printf("[winctrl_z]: error binding port or ttl, disabling ctrl-a " "and ctrl-z\n"); ctrlzbind = BIND_NONE; return; } if (input[i].Event.KeyEvent.uChar.AsciiChar == 0x01) { if (*p > 0) (*p)--; } else (*p)++; printf("\b\b\b\b\b\b\b\b\b"); printf("%d: ", *p); fflush(stdout); break; } } } } } FlushConsoleInputBuffer(ctrlz); ResetEvent(ctrlz); }
void DoMain (HINSTANCE hInstance) { LONG WinWidth, WinHeight; int height, width, x, y; RECT cRect; TIMECAPS tc; DEVMODE displaysettings; try { #ifdef _MSC_VER _set_new_handler (NewFailure); #endif Args = new DArgs(__argc, __argv); // Load Win32 modules Kernel32Module.Load({"kernel32.dll"}); Shell32Module.Load({"shell32.dll"}); User32Module.Load({"user32.dll"}); // Under XP, get our session ID so we can know when the user changes/locks sessions. // Since we need to remain binary compatible with older versions of Windows, we // need to extract the ProcessIdToSessionId function from kernel32.dll manually. HMODULE kernel = GetModuleHandle ("kernel32.dll"); if (Args->CheckParm("-stdout")) { // As a GUI application, we don't normally get a console when we start. // If we were run from the shell and are on XP+, we can attach to its // console. Otherwise, we can create a new one. If we already have a // stdout handle, then we have been redirected and should just use that // handle instead of creating a console window. StdOut = GetStdHandle(STD_OUTPUT_HANDLE); if (StdOut != NULL) { // It seems that running from a shell always creates a std output // for us, even if it doesn't go anywhere. (Running from Explorer // does not.) If we can get file information for this handle, it's // a file or pipe, so use it. Otherwise, pretend it wasn't there // and find a console to use instead. BY_HANDLE_FILE_INFORMATION info; if (!GetFileInformationByHandle(StdOut, &info)) { StdOut = NULL; } } if (StdOut == NULL) { // AttachConsole was introduced with Windows XP. (OTOH, since we // have to share the console with the shell, I'm not sure if it's // a good idea to actually attach to it.) typedef BOOL (WINAPI *ac)(DWORD); ac attach_console = kernel != NULL ? (ac)GetProcAddress(kernel, "AttachConsole") : NULL; if (attach_console != NULL && attach_console(ATTACH_PARENT_PROCESS)) { StdOut = GetStdHandle(STD_OUTPUT_HANDLE); DWORD foo; WriteFile(StdOut, "\n", 1, &foo, NULL); AttachedStdOut = true; } if (StdOut == NULL && AllocConsole()) { StdOut = GetStdHandle(STD_OUTPUT_HANDLE); } FancyStdOut = true; } } // Set the timer to be as accurate as possible if (timeGetDevCaps (&tc, sizeof(tc)) != TIMERR_NOERROR) TimerPeriod = 1; // Assume minimum resolution of 1 ms else TimerPeriod = tc.wPeriodMin; timeBeginPeriod (TimerPeriod); /* killough 1/98: This fixes some problems with exit handling during abnormal situations. The old code called I_Quit() to end program, while now I_Quit() is installed as an exit handler and exit() is called to exit, either normally or abnormally. */ atexit (call_terms); atterm (I_Quit); // Figure out what directory the program resides in. char *program; #ifdef _MSC_VER if (_get_pgmptr(&program) != 0) { I_FatalError("Could not determine program location."); } #else char progbuff[1024]; GetModuleFileName(0, progbuff, sizeof(progbuff)); progbuff[1023] = '\0'; program = progbuff; #endif progdir = program; program = progdir.LockBuffer(); *(strrchr(program, '\\') + 1) = '\0'; FixPathSeperator(program); progdir.Truncate((long)strlen(program)); progdir.UnlockBuffer(); HDC screenDC = GetDC(0); int dpi = GetDeviceCaps(screenDC, LOGPIXELSX); ReleaseDC(0, screenDC); width = (512 * dpi + 96 / 2) / 96; height = (384 * dpi + 96 / 2) / 96; // Many Windows structures that specify their size do so with the first // element. DEVMODE is not one of those structures. memset (&displaysettings, 0, sizeof(displaysettings)); displaysettings.dmSize = sizeof(displaysettings); EnumDisplaySettings (NULL, ENUM_CURRENT_SETTINGS, &displaysettings); x = (displaysettings.dmPelsWidth - width) / 2; y = (displaysettings.dmPelsHeight - height) / 2; if (Args->CheckParm ("-0")) { x = y = 0; } WNDCLASS WndClass; WndClass.style = 0; WndClass.lpfnWndProc = LConProc; WndClass.cbClsExtra = 0; WndClass.cbWndExtra = 0; WndClass.hInstance = hInstance; WndClass.hIcon = LoadIcon (hInstance, MAKEINTRESOURCE(IDI_ICON1)); WndClass.hCursor = LoadCursor (NULL, IDC_ARROW); WndClass.hbrBackground = NULL; WndClass.lpszMenuName = NULL; WndClass.lpszClassName = (LPCTSTR)WinClassName; /* register this new class with Windows */ if (!RegisterClass((LPWNDCLASS)&WndClass)) I_FatalError ("Could not register window class"); /* create window */ char caption[100]; mysnprintf(caption, countof(caption), "" GAMESIG " %s " X64 " (%s)", GetVersionString(), GetGitTime()); Window = CreateWindowEx( WS_EX_APPWINDOW, (LPCTSTR)WinClassName, (LPCTSTR)caption, WS_OVERLAPPEDWINDOW | WS_VISIBLE | WS_CLIPCHILDREN, x, y, width, height, (HWND) NULL, (HMENU) NULL, hInstance, NULL); if (!Window) I_FatalError ("Could not open window"); if (kernel != NULL) { typedef BOOL (WINAPI *pts)(DWORD, DWORD *); pts pidsid = (pts)GetProcAddress (kernel, "ProcessIdToSessionId"); if (pidsid != 0) { if (!pidsid (GetCurrentProcessId(), &SessionID)) { SessionID = 0; } hwtsapi32 = LoadLibraryA ("wtsapi32.dll"); if (hwtsapi32 != 0) { FARPROC reg = GetProcAddress (hwtsapi32, "WTSRegisterSessionNotification"); if (reg == 0 || !((BOOL(WINAPI *)(HWND, DWORD))reg) (Window, NOTIFY_FOR_THIS_SESSION)) { FreeLibrary (hwtsapi32); hwtsapi32 = 0; } else { atterm (UnWTS); } } } } GetClientRect (Window, &cRect); WinWidth = cRect.right; WinHeight = cRect.bottom; CoInitialize (NULL); atterm (UnCOM); C_InitConsole (((WinWidth / 8) + 2) * 8, (WinHeight / 12) * 8, false); I_DetectOS (); D_DoomMain (); } catch (class CNoRunExit &) { I_ShutdownGraphics(); if (!batchrun) { if (FancyStdOut && !AttachedStdOut) { // Outputting to a new console window: Wait for a keypress before quitting. DWORD bytes; HANDLE stdinput = GetStdHandle(STD_INPUT_HANDLE); ShowWindow(Window, SW_HIDE); WriteFile(StdOut, "Press any key to exit...", 24, &bytes, NULL); FlushConsoleInputBuffer(stdinput); SetConsoleMode(stdinput, 0); ReadConsole(stdinput, &bytes, 1, &bytes, NULL); } else if (StdOut == NULL) { ShowErrorPane(NULL); } } exit(0); } catch (class CDoomError &error) { I_ShutdownGraphics (); RestoreConView (); I_FlushBufferedConsoleStuff(); if (error.GetMessage ()) { if (!batchrun) { ShowErrorPane(error.GetMessage()); } else { Printf("%s\n", error.GetMessage()); } } exit (-1); } }
VOID ConInFlush (VOID) { FlushConsoleInputBuffer (GetStdHandle (STD_INPUT_HANDLE)); }
/* ================== CON_ConsoleInput ================== */ char *CON_ConsoleInput (void) { INPUT_RECORD buff[MAXCMDLINE]; DWORD count = 0, events = 0; WORD key = 0; int i; int newlinepos = -1; if (!GetNumberOfConsoleInputEvents(qconsole_hin, &events)) return NULL; if (events < 1) return NULL; // if we have overflowed, start dropping oldest input events if (events >= MAXCMDLINE) { ReadConsoleInput(qconsole_hin, buff, 1, &events); return NULL; } if (!ReadConsoleInput(qconsole_hin, buff, events, &count)) return NULL; FlushConsoleInputBuffer(qconsole_hin); for (i = 0; i < count; i++) { if (buff[i].EventType != KEY_EVENT) continue; if (!buff[i].Event.KeyEvent.bKeyDown) continue; key = buff[i].Event.KeyEvent.wVirtualKeyCode; if (key == VK_RETURN) { newlinepos = i; break; } else if (key == VK_UP) { CON_HistPrev(); break; } else if (key == VK_DOWN) { CON_HistNext(); break; } else if (key == VK_TAB) { // command completion field_t f; Field_Clear(&f); Q_strlcpy(f.buffer, qconsole_line, sizeof(f.buffer)); Field_AutoComplete(&f); Q_strlcpy(qconsole_line, f.buffer, sizeof(qconsole_line)); qconsole_linelen = strlen(qconsole_line); break; } if (qconsole_linelen < sizeof(qconsole_line) - 1) { char c = buff[i].Event.KeyEvent.uChar.AsciiChar; if (key == VK_BACK) { int pos = (qconsole_linelen > 0) ? qconsole_linelen - 1 : 0; qconsole_line[pos] = '\0'; qconsole_linelen = pos; } else if (c) { qconsole_line[qconsole_linelen++] = c; qconsole_line[qconsole_linelen] = '\0'; } } } if (newlinepos < 0) { CON_Show(); return NULL; } if (!qconsole_linelen) { CON_Show(); Com_Printf("\n"); return NULL; } qconsole_linelen = 0; CON_Show(); CON_HistAdd(); Com_Printf("%s\n", qconsole_line); return qconsole_line; }
/* ================== CON_Input ================== */ char *CON_Input( void ) { INPUT_RECORD buff[ MAX_EDIT_LINE ]; DWORD count = 0, events = 0; WORD key = 0; int i; int newlinepos = -1; if ( !GetNumberOfConsoleInputEvents( qconsole_hin, &events ) ) { return NULL; } if ( events < 1 ) { return NULL; } // if we have overflowed, start dropping oldest input events if ( events >= MAX_EDIT_LINE ) { ReadConsoleInput( qconsole_hin, buff, 1, &events ); return NULL; } if ( !ReadConsoleInput( qconsole_hin, buff, events, &count ) ) { return NULL; } FlushConsoleInputBuffer( qconsole_hin ); for ( i = 0; i < count; i++ ) { if ( buff[ i ].EventType != KEY_EVENT ) { continue; } if ( !buff[ i ].Event.KeyEvent.bKeyDown ) { continue; } key = buff[ i ].Event.KeyEvent.wVirtualKeyCode; if ( key == VK_RETURN ) { newlinepos = i; break; } else if ( key == VK_UP ) { Q_strncpyz( qconsole_line, Hist_Prev(), sizeof( qconsole_line ) ); qconsole_linelen = strlen( qconsole_line ); break; } else if ( key == VK_DOWN ) { const char *history = Hist_Next(); if ( history ) { Q_strncpyz( qconsole_line, history, sizeof( qconsole_line ) ); qconsole_linelen = strlen( qconsole_line ); } else if ( qconsole_linelen ) { Hist_Add( qconsole_line ); qconsole_line[ 0 ] = '\0'; qconsole_linelen = 0; } break; } else if ( key == VK_TAB ) { field_t f; Q_strncpyz( f.buffer, qconsole_line, sizeof( f.buffer ) ); Field_AutoComplete( &f, "]" ); Q_strncpyz( qconsole_line, f.buffer, sizeof( qconsole_line ) ); qconsole_linelen = strlen( qconsole_line ); break; } if ( qconsole_linelen < sizeof( qconsole_line ) - 1 ) { char c = buff[ i ].Event.KeyEvent.uChar.AsciiChar; if ( key == VK_BACK ) { int pos = ( qconsole_linelen > 0 ) ? qconsole_linelen - 1 : 0; qconsole_line[ pos ] = '\0'; qconsole_linelen = pos; } else if ( c ) { qconsole_line[ qconsole_linelen++ ] = c; qconsole_line[ qconsole_linelen ] = '\0'; } } } CON_Show(); if ( newlinepos < 0 ) { return NULL; } if ( !qconsole_linelen ) { Com_Printf( "\n" ); return NULL; } Hist_Add( qconsole_line ); Com_Printf( "]%s\n", qconsole_line ); qconsole_linelen = 0; return qconsole_line; }
BOOL ProcessInputMessage(MSG64::MsgStr &msg, INPUT_RECORD &r) { memset(&r, 0, sizeof(r)); BOOL lbOk = FALSE; if (!UnpackInputRecord(&msg, &r)) { _ASSERT(FALSE); } else { TODO("Сделать обработку пачки сообщений, вдруг они накопились в очереди?"); //#ifdef _DEBUG //if (r.EventType == KEY_EVENT && (r.Event.KeyEvent.wVirtualKeyCode == 'C' || r.Event.KeyEvent.wVirtualKeyCode == VK_CANCEL)) //{ // DEBUGSTR(L" --- CtrlC/CtrlBreak recieved\n"); //} //#endif bool lbProcessEvent = false; bool lbIngoreKey = false; if (r.EventType == KEY_EVENT && r.Event.KeyEvent.bKeyDown && (r.Event.KeyEvent.wVirtualKeyCode == 'C' || r.Event.KeyEvent.wVirtualKeyCode == VK_CANCEL) && ( // Удерживается ТОЛЬКО Ctrl (r.Event.KeyEvent.dwControlKeyState & CTRL_MODIFIERS) && ((r.Event.KeyEvent.dwControlKeyState & ALL_MODIFIERS) == (r.Event.KeyEvent.dwControlKeyState & CTRL_MODIFIERS)) ) ) { lbProcessEvent = true; DEBUGSTR(L" --- CtrlC/CtrlBreak recieved\n"); DWORD dwMode = 0; GetConsoleMode(GetStdHandle(STD_INPUT_HANDLE), &dwMode); // CTRL+C (and Ctrl+Break?) is processed by the system and is not placed in the input buffer if ((dwMode & ENABLE_PROCESSED_INPUT) == ENABLE_PROCESSED_INPUT) lbIngoreKey = lbProcessEvent = true; else lbProcessEvent = false; if (lbProcessEvent) { //BOOL lbRc = FALSE; #if 0 DWORD dwEvent = (r.Event.KeyEvent.wVirtualKeyCode == 'C') ? CTRL_C_EVENT : CTRL_BREAK_EVENT; #endif //&& (gpSrv->dwConsoleMode & ENABLE_PROCESSED_INPUT) #if 1 // Issue 590: GenerateConsoleCtrlEvent нифига не прерывает функцию ReadConsoleW SendMessage(ghConWnd, WM_KEYDOWN, r.Event.KeyEvent.wVirtualKeyCode, 0); //lbRc = TRUE; #endif #if 0 //The SetConsoleMode function can disable the ENABLE_PROCESSED_INPUT mode for a console's input buffer, //so CTRL+C is reported as keyboard input rather than as a signal. // CTRL+BREAK is always treated as a signal if ( // Удерживается ТОЛЬКО Ctrl (r.Event.KeyEvent.dwControlKeyState & CTRL_MODIFIERS) && ((r.Event.KeyEvent.dwControlKeyState & ALL_MODIFIERS) == (r.Event.KeyEvent.dwControlKeyState & CTRL_MODIFIERS)) ) { // Вроде работает, Главное не запускать процесс с флагом CREATE_NEW_PROCESS_GROUP // иначе у микрософтовской консоли (WinXP SP3) сносит крышу, и она реагирует // на Ctrl-Break, но напрочь игнорирует Ctrl-C lbRc = GenerateConsoleCtrlEvent(dwEvent, 0); // Это событие (Ctrl+C) в буфер помещается(!) иначе до фара не дойдет собственно клавиша C с нажатым Ctrl } #endif } if (lbIngoreKey) return FALSE; // CtrlBreak отсылаем СРАЗУ, мимо очереди, иначе макросы FAR нельзя стопнуть if (r.Event.KeyEvent.wVirtualKeyCode == VK_CANCEL) { // При получении CtrlBreak в реальной консоли - буфер ввода очищается // иначе фар, при попытке считать ввод получит старые, // еще не обработанные нажатия, и CtrlBreak проигнорирует FlushConsoleInputBuffer(GetStdHandle(STD_INPUT_HANDLE)); SendConsoleEvent(&r, 1); return FALSE; } } #ifdef _DEBUG if (r.EventType == KEY_EVENT && r.Event.KeyEvent.bKeyDown && r.Event.KeyEvent.wVirtualKeyCode == VK_F11) { DEBUGSTR(L" --- F11 recieved\n"); } #endif #ifdef _DEBUG if (r.EventType == MOUSE_EVENT) { static DWORD nLastEventTick = 0; if (nLastEventTick && (GetTickCount() - nLastEventTick) > 2000) { OutputDebugString(L".\n"); } wchar_t szDbg[60]; _wsprintf(szDbg, SKIPLEN(countof(szDbg)) L" ConEmuC.MouseEvent(X=%i,Y=%i,Btns=0x%04x,Moved=%i)\n", r.Event.MouseEvent.dwMousePosition.X, r.Event.MouseEvent.dwMousePosition.Y, r.Event.MouseEvent.dwButtonState, (r.Event.MouseEvent.dwEventFlags & MOUSE_MOVED)); DEBUGLOGINPUT(szDbg); nLastEventTick = GetTickCount(); } #endif // Запомнить, когда была последняя активность пользователя if (r.EventType == KEY_EVENT || (r.EventType == MOUSE_EVENT && (r.Event.MouseEvent.dwButtonState || r.Event.MouseEvent.dwEventFlags || r.Event.MouseEvent.dwEventFlags == DOUBLE_CLICK))) { gpSrv->dwLastUserTick = GetTickCount(); } lbOk = TRUE; //SendConsoleEvent(&r, 1); } return lbOk; }