// console_lastclose.cpp : définit le point d'entrée pour l'application console. // #include #include #include #include #include // DWORD WINAPI SetLastConsoleEventActive(VOID); typedef DWORD (WINAPI* pSetLastConsoleEventActive)(VOID); BOOL WINAPI CtrlHandler(DWORD fdwCtrlType) { //switch (fdwCtrlType) //{ // case CTRL_C_EVENT: // case CTRL_CLOSE_EVENT: // case CTRL_BREAK_EVENT: // case CTRL_LOGOFF_EVENT: // case CTRL_SHUTDOWN_EVENT: // default: // break; //} wprintf(L"In console control handler -- %d\n", fdwCtrlType); wprintf(L"Press any key to continue...\n"); _getch(); return FALSE; // return TRUE; } void FixStdHandles(void) { int hCrt, i; FILE *hf; hCrt = _open_osfhandle((intptr_t)GetStdHandle(STD_INPUT_HANDLE), _O_TEXT); hf = _fdopen(hCrt, "r+"); *stdin = *hf; i = setvbuf(stdin, NULL, _IONBF, 0); hCrt = _open_osfhandle((intptr_t)GetStdHandle(STD_OUTPUT_HANDLE), _O_TEXT); hf = _fdopen(hCrt, "r+"); *stdout = *hf; i = setvbuf(stdout, NULL, _IONBF, 0); hCrt = _open_osfhandle((intptr_t)GetStdHandle(STD_ERROR_HANDLE), _O_TEXT); hf = _fdopen(hCrt, "r+"); *stderr = *hf; i = setvbuf(stderr, NULL, _IONBF, 0); } int wmain(int argc, WCHAR* argv[]) { BOOL Success = FALSE; DWORD dwError = 0; DWORD dwPID = -1; // Get the API pointer pSetLastConsoleEventActive SetLastConsoleEventActive = (pSetLastConsoleEventActive) GetProcAddress(GetModuleHandle(L"kernel32.dll"), "SetLastConsoleEventActive"); // Try to attach to some console (can be ours) wprintf(L"Enter the PID of the process on which you want to grab its console (enter -1 for keeping this console): "); wscanf(L"%d", &dwPID); if (dwPID != -1 && dwPID != GetCurrentProcessId()) { FreeConsole(); AttachConsole(dwPID); FixStdHandles(); } wprintf(L"\nSuccessfully attached to this console!\n\n"); // Register custom control handler Success = SetConsoleCtrlHandler(CtrlHandler, TRUE); if (!Success) { wprintf(L"Failure when trying to register console control handler\n"); return 1; } // Test SetLastConsoleEventActive dwError = SetLastConsoleEventActive(); wprintf(L"SetLastConsoleEventActive() first call, dwError = 0x%08x, GetLastError() == %lu\n", dwError, GetLastError()); // Again... dwError = SetLastConsoleEventActive(); wprintf(L"SetLastConsoleEventActive() second call, dwError = 0x%08x, GetLastError() == %lu\n", dwError, GetLastError()); while (TRUE) {}; wprintf(L"Press any key to quit...\n"); _getch(); return 0; }