private static void EnsureSubscribedToGlobalKeyboardEvents() { // install Keyboard hook only if it is not installed and must be installed if (s_KeyboardHookHandle == 0) { //See comment of this field. To avoid GC to clean it up. s_KeyboardDelegate = KeyboardHookProc; //install hook s_KeyboardHookHandle = WinAPI.SetWindowsHookEx( WinAPI.WH_KEYBOARD_LL, s_KeyboardDelegate, Marshal.GetHINSTANCE( Assembly.GetExecutingAssembly().GetModules()[0]), 0); //If SetWindowsHookEx fails. if (s_KeyboardHookHandle == 0) { //Returns the error code returned by the last unmanaged function called using platform invoke that has the DllImportAttribute.SetLastError flag set. int errorCode = Marshal.GetLastWin32Error(); //do cleanup //Initializes and throws a new instance of the Win32Exception class with the specified error. throw new Win32Exception(errorCode); } } }
// 安装键盘钩子 private void start_button_Click(object sender, EventArgs e) { if (m_hHook != 0) { // 钩子已经安装 return; } using (Process curProcess = Process.GetCurrentProcess()) using (ProcessModule curModule = curProcess.MainModule) { m_KeyboardHookProcedure = new WinAPI.HookProc(MainForm.KeyboardHookProc); m_hHook = WinAPI.SetWindowsHookEx(13 /*WH_KEYBOARD_L*/, m_KeyboardHookProcedure, WinAPI.GetModuleHandle(curModule.ModuleName), 0); if (m_hHook == 0) { int iError = WinAPI.GetLastError(); string strMsg = "开始服务错误(错误码:" + iError.ToString() + ")!"; ErrorMessage(strMsg); return; } // 启动成功 stop_button.Enabled = true; start_button.Enabled = false; stop_button.Focus(); } }
public void SetHook() { KeyboardHookDelegate = new WinAPI.HookProc(KeyboardHookProc); Process cProcess = Process.GetCurrentProcess(); ProcessModule cModule = cProcess.MainModule; var mh = WinAPI.GetModuleHandle(cModule.ModuleName); hHook = WinAPI.SetWindowsHookEx(WinAPI.WH_KEYBOARD_LL, KeyboardHookDelegate, mh, 0); }
/// <summary> /// Windows NT/2000/XP: Installs a hook procedure that monitors low-level mouse input events. /// </summary> public void InstallHook() { try { MouseHookProcedure = new WinAPI.HookProc(MouseHookProc);// generate a HookProc instance. } catch (Exception ex) { Console.WriteLine("HookProc error: " + ex.Message); } hMouseHook = WinAPI.SetWindowsHookEx(WH_MOUSE_LL, MouseHookProcedure, WinAPI.GetModuleHandle("user32"), 0); if (hMouseHook == IntPtr.Zero) throw new Win32Exception(1); }
/// <summary> /// Windows NT/2000/XP: Installs a hook procedure that monitors low-level mouse input events. /// </summary> public void InstallHook() { try { MouseHookProcedure = MouseHookProc; // generate a HookProc instance. } catch (Exception ex) { Console.WriteLine("HookProc error: " + ex.Message); } hMouseHook = WinAPI.SetWindowsHookEx(WH_MOUSE_LL, MouseHookProcedure, WinAPI.GetModuleHandle("user32"), 0); if (hMouseHook == IntPtr.Zero) { throw new Win32Exception(1); } }
private static void ForceUnsunscribeFromGlobalKeyboardEvents() { if (s_KeyboardHookHandle != 0) { //uninstall hook int result = WinAPI.UnhookWindowsHookEx(s_KeyboardHookHandle); //reset invalid handle s_KeyboardHookHandle = 0; //Free up for GC s_KeyboardDelegate = null; //if failed and exception must be thrown if (result == 0) { //Returns the error code returned by the last unmanaged function called using platform invoke that has the DllImportAttribute.SetLastError flag set. int errorCode = Marshal.GetLastWin32Error(); //Initializes and throws a new instance of the Win32Exception class with the specified error. throw new Win32Exception(errorCode); } } }
public bool InstallHook() { if (mainWindow == IntPtr.Zero) { return(false); } var hModule = WinAPI.GetModuleHandle(null); if (hModule == IntPtr.Zero) { return(false); } m_Callback = Callback; m_Hook = WinAPI.SetWindowsHookEx(WinAPI.HookType.WH_GETMESSAGE, m_Callback, hModule, threadId); if (m_Hook == IntPtr.Zero) { return(false); } // Allow dragging of files onto the main window. generates the WM_DROPFILES message WinAPI.DragAcceptFiles(mainWindow, true); return(true); }
/// <summary> /// Handles the Startup event of the Application control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="StartupEventArgs"/> instance containing the event data.</param> /// <remarks>...</remarks> private void Application_Startup(object sender, StartupEventArgs e) { // Helper registration this.RegisterApplication(); // Notifications this.AddNotificationManager(new SysTrayNotificationManager(this.CreateWinFormsNotifiyIcon(notifier => { notifier.ContextMenu = new ContextMenu(); notifier.ContextMenu.MenuItems.Add("Resume UI", (a, b) => Current.Dispatcher.BeginInvoke(new Action(() => { foreach (var window in Current.Windows) { ((Window)window).Activate(); ((Window)window).Show(); } }))); notifier.ContextMenu.MenuItems.Add("Suspend UI", (a, b) => Current.Dispatcher.BeginInvoke(new Action(() => { foreach (var window in Current.Windows) { ((Window)window).Hide(); } }))); notifier.ContextMenu.MenuItems.Add("Restart", (a, b) => Current.Dispatcher.BeginInvoke(new Action(Restart))); notifier.ContextMenu.MenuItems.Add("Close", (a, b) => Current.Dispatcher.BeginInvoke(new Action(Close))); // OBSOLETE: notifier.ShowBalloonTip(1000, "Newgen", "Loading ...", System.Windows.Forms.ToolTipIcon.Info); }))); // Hot key try { var objCurrentModule = Process.GetCurrentProcess().MainModule; objKeyboardProcess = new WinAPI.HookProc(CaptureKey); ptrHook = WinAPI.SetWindowsHookEx(13, objKeyboardProcess, WinAPI.GetModuleHandle(objCurrentModule.ModuleName), 0); Api.Logger.LogInformation("Hooking into system key events done without error."); } catch { Api.Logger.LogWarning("Hooking into system key events done with error."); } // IPC messages Api.Messenger.MessageReceived += new Action <IntPtr, EMessage>(OnMessageReceived); // Hub helpers Api.HubOpening += new Action(() => Screen.ZOrderHelper(false)); Api.HubClosing += new Action(() => { if (Screen != null) { Screen.ZOrderHelper(true); } ThreadingExtensions.LazyInvoke(WinAPI.FlushMemory, 250); }); // Load view Screen.Show(); #if !DEBUG // Run tracker under non-dispatcher context. InternalHelper.SendAnalytics().ConfigureInstances(-1); #endif try { // PM. PSS = new PackageSettingsStorage(); PM = PackageManagerPackage.Create(PSS); PM.Settings.RemoveAll(f => f is RuntimeSettings); PM.Settings.Add(new NewgenPackageManagerRuntimeSettings(PM)); PM.Logger.Listeners.Add(new LoggerLogListener(PackageManagerExtensions.Logger)); PackageManagerExtensions.Logger.Listeners.Add(new LoggerLogListener(Api.Logger)); PM.Packages.CollectionChanged += (o, a) => { switch (a.Action) { // On package loaded. case NotifyCollectionChangedAction.Add: foreach (var package in a.NewItems.OfType <NewgenPackage>()) { Dispatcher.BeginInvoke(new Action(() => { package.Start(); })); } break; case NotifyCollectionChangedAction.Move: break; // On package un-loaded. case NotifyCollectionChangedAction.Remove: foreach (var package in a.NewItems.OfType <NewgenPackage>()) { Dispatcher.BeginInvoke(new Action(() => { package.Stop(); })); } break; case NotifyCollectionChangedAction.Replace: break; case NotifyCollectionChangedAction.Reset: break; default: break; } }; // Find all packages if (!PM.GetSettings().ScanLocations.Contains(Api.PackagesRoot)) { PM.GetSettings().ScanLocations.Add(Api.PackagesRoot); } ThreadingExtensions.LazyInvoke(async() => await PM.LoadAll(), 3500); } catch (Exception ex) { Api.Logger.LogError("PM cannot be started.", ex); } Api.Logger.LogInformation("STARTED app."); }
private void ToogleHook() { if (hKeyboardHook == 0) { // Create an instance of HookProc. KeyboardHookProcedure = new WinAPI.HookProc(KeyboardHookProc); hKeyboardHook = WinAPI.SetWindowsHookEx(WinAPI.WH_KEYBOARD_LL, KeyboardHookProcedure, (IntPtr)0, 0); if (hKeyboardHook == 0) { MessageBox.Show("SetWindowsHookEx Failed"); return; } } else { bool ret = WinAPI.UnhookWindowsHookEx(hKeyboardHook); if (ret == false) { MessageBox.Show("UnhookWindowsHookEx Failed"); return; } hKeyboardHook = 0; } }