public void Start(bool installMouseHook, bool installKeyboardHook) { if (this.mouseHookHandle == 0 && installMouseHook) { GlobalHook.mouseHookProcedure = new NativeMethods.HookProc(this.MouseHookProc); // In .net 4 we send in IntPtr.Zero for the hMod parameter this.mouseHookHandle = NativeMethods.SetWindowsHookEx(NativeMethods.WH_MOUSE_LL, GlobalHook.mouseHookProcedure, IntPtr.Zero, 0); if (this.mouseHookHandle == 0) { int lastWin32Error = Marshal.GetLastWin32Error(); this.Stop(true, false, false); throw new Win32Exception(lastWin32Error); } } if (this.keyboardHookHandle == 0 && installKeyboardHook) { GlobalHook.keyboardHookProcedure = new NativeMethods.HookProc(this.KeyboardHookProc); // In .net 4 we send in IntPtr.Zero for the hMod parameter this.keyboardHookHandle = NativeMethods.SetWindowsHookEx(NativeMethods.WH_KEYBOARD_LL, GlobalHook.keyboardHookProcedure, IntPtr.Zero, 0); if (this.keyboardHookHandle == 0) { int lastWin32Error2 = Marshal.GetLastWin32Error(); this.Stop(false, true, false); throw new Win32Exception(lastWin32Error2); } } }
/// <summary> /// Installsmouse hook and starts rasing events /// </summary> /// <param name="InstallMouseHook"><b>true</b> if mouse events must be monitored</param> /// <exception cref="Win32Exception">Any windows problem.</exception> public void Start() { // install Mouse hook only if it is not installed and must be installed if (hMouseHook.ToInt64() == 0) { // Create an instance of HookProc. MouseHookProcedure = new NativeMethods.HookProc(MouseHookProc); //install hook hMouseHook = NativeMethods.SetWindowsHookEx( WH_MOUSE_LL, MouseHookProcedure, IntPtr.Zero, 0); //If SetWindowsHookEx fails. if (hMouseHook.ToInt64() == 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 Stop(true, false); //Initializes and throws a new instance of the Win32Exception class with the specified error. throw new Win32Exception(errorCode); } } }
private static IntPtr SetHook(NativeMethods.HookProc proc) { using (var curProcess = Process.GetCurrentProcess()) using (var curModule = curProcess.MainModule) { return(NativeMethods.SetWindowsHookEx(14, proc, NativeMethods.GetModuleHandle(curModule.ModuleName), 0)); } }
public void SetHook(bool enable) { if (enable && this.m_hHook == 0) { this.m_HookCallback = this.HookCallbackProc; var module = System.Reflection.Assembly.GetExecutingAssembly().GetModules()[0]; this.m_hHook = NativeMethods.SetWindowsHookEx(WinUtil.WH_KEYBOARD_LL, this.m_HookCallback, System.Runtime.InteropServices.Marshal.GetHINSTANCE (module), 0); if (this.m_hHook == 0) { MessageBox.Show( "SetHook Failed. Please make sure the 'Visual Studio Host Process' on the debug setting page is disabled"); return; } return; } if (enable == false && this.m_hHook != 0) { NativeMethods.UnhookWindowsHookEx(this.m_hHook); this.m_hHook = 0; } }
public CursorModule() { llMouseProc = llMouseHookCallback; winEventProc = EventCallback; StartListeningForWindowChanges(); }
private void Dispose(bool disposing) { if (disposing) { // because we can unhook only in the same thread, not in garbage collector thread if (this.windowsHookHandle != IntPtr.Zero) { if (NativeMethods.UnhookWindowsHookEx(this.windowsHookHandle) is false) { int errorCode = Marshal.GetLastWin32Error(); this.logger.LogCritical($"Failed to remove keyboard hooks for '{Process.GetCurrentProcess().ProcessName}'. Error {errorCode}: {new Win32Exception(Marshal.GetLastWin32Error()).Message}."); } this.windowsHookHandle = IntPtr.Zero; this.hookProc -= LowLevelKeyboardProc; } } if (this.user32LibraryHandle != IntPtr.Zero) { if (NativeMethods.FreeLibrary(this.user32LibraryHandle) is false) // reduces reference to library by 1. { int errorCode = Marshal.GetLastWin32Error(); this.logger.LogCritical($"Failed to unload library 'User32.dll'. Error {errorCode}: {new Win32Exception(Marshal.GetLastWin32Error()).Message}."); } this.user32LibraryHandle = IntPtr.Zero; } }
public void SetHook() { // Set Hooks if (hKeyboardHook.ToInt32() == 0) { KeyboardHookProcedure = new NativeMethods.HookProc(KeyboardHookProc); //MouseHookProcedure = new HookProc(MouseHookProc); //Keyboard Global Hook (Do not need reflection) hKeyboardHook = NativeMethods.SetWindowsHookEx(WH_KEYBOARD_LL, KeyboardHookProcedure, NativeMethods.GetModuleHandle(Process.GetCurrentProcess().MainModule.ModuleName), 0); //hMouseHook = SetWindowsHookEx(WH_MOUSE_LL, MouseHookProcedure, GetModuleHandle(Process.GetCurrentProcess().MainModule.ModuleName), 0); //Keyboard Global Hook (need reflection) //hKeyboardHook = SetWindowsHookEx(WH_KEYBOARD_LL, KeyboardHookProcedure, Marshal.GetHINSTANCE(Assembly.GetExecutingAssembly().GetModules()[0]), 0); //If SetWindowsHookEx Failed if (hKeyboardHook.ToInt32() == 0) { ReleaseKeyboardHook(); throw new Exception("安装键盘钩子失败"); } } }
static void Main(string[] args) { Process process = Process.Start(@"C:\Program Files\Internet Explorer\iexplore.exe"); // Process process = Process.Start(@"D:\VisualStudioGit\RandomSoftware\ApplicationHook\Dummy\bin\Debug\Dummy.exe"); try { hhookProc += Hook; //hhook = NativeMethods.SetWindowsHookEx(HookType.WH_MOUSE, hhookProc, IntPtr.Zero, 0); //hhook = process.Handle; //Console.WriteLine(hhook); //hhook = NativeMethods.SetWindowsHookEx(HookType.WH_MOUSE, hhookProc, process.Handle, 0); Console.WriteLine(NativeMethods.SetWindowsHookEx(HookType.WH_MOUSE, hhookProc, process.Handle, 0)); //hhook = NativeMethods.SetWindowsHookEx(HookType.WH_CBT, hhookProc, process.Handle, 0); Console.WriteLine("hhook valid? {0}", hhook != IntPtr.Zero); Console.WriteLine("process valid? {0}", process.Handle != IntPtr.Zero); while (!process.HasExited) { process.WaitForExit(500); } } finally { if (hhook != IntPtr.Zero) { NativeMethods.UnhookWindowsHookEx(hhook); } } }
public void SetHook(bool enable) { if (enable && this.m_hHook == 0) { this.m_HookCallback = this.HookCallbackProc; var module = System.Reflection.Assembly.GetExecutingAssembly().GetModules()[0]; this.m_hHook = NativeMethods.SetWindowsHookEx(WinUtil.WH_KEYBOARD_LL, this.m_HookCallback, System.Runtime.InteropServices.Marshal.GetHINSTANCE (module), 0); if (this.m_hHook == 0) { MessageBox.Show( "SetHook Failed. Please make sure the 'Visual Studio Host Process' on the debug setting page is disabled"); return; } return; } if (enable == false && this.m_hHook != 0) { NativeMethods.UnhookWindowsHookEx(this.m_hHook); this.m_hHook = 0; } }
public AppContext() { notifyIcon = new NotifyIcon { Text = $"{Application.ProductName} {Application.ProductVersion}", ContextMenuStrip = new ContextMenuStrip() }; notifyIcon.ContextMenuStrip.Items.Add("Exit", null, ExitItem_OnClick); timer = new Timer { Interval = 100 }; timer.Tick += Timer_Tick; SystemEvents.SessionEnding += SystemEvents_SessionEnding; hookProc = new NativeMethods.HookProc(HookCallback); using var process = Process.GetCurrentProcess(); var mainModule = process.MainModule; hook = NativeMethods.SetWindowsHookEx(NativeMethods.WH_KEYBOARD_LL, hookProc, NativeMethods.GetModuleHandle(mainModule.ModuleName), 0); if (hook == IntPtr.Zero) { MessageBox.Show(new Win32Exception(Marshal.GetLastWin32Error()).Message, notifyIcon.Text, MessageBoxButtons.OK, MessageBoxIcon.Error); Application.Exit(); } else { Timer_Tick(this, EventArgs.Empty); } }
protected virtual void AddHooks() { mouseHookCallback -= MouseHook; mouseHookCallback += MouseHook; mouseHook = NativeMethods.SetWindowsHookEx( NativeMethods.HookType.WH_MOUSE_LL, mouseHookCallback, NativeMethods.GetModuleHandle("user32"), 0); keyboardHookCallback -= KeyboardHook; keyboardHookCallback += KeyboardHook; keyboardHook = NativeMethods.SetWindowsHookEx( NativeMethods.HookType.WH_KEYBOARD_LL, keyboardHookCallback, NativeMethods.GetModuleHandle("user32"), 0); if (mouseHook == IntPtr.Zero || keyboardHook == IntPtr.Zero) { this.Close(); } }
private static IntPtr CreateHook(NativeMethods.HookProc proc) { using var curProcess = Process.GetCurrentProcess(); using var curModule = curProcess.MainModule; return(NativeMethods.SetWindowsHookEx(NativeMethods.HookType.WH_KEYBOARD_LL, proc, NativeMethods.GetModuleHandle(curModule.ModuleName), 0)); }
public void Hook() { //See comment of this field. To avoid GC to clean it up. _keyboardDelegate = KeyboardHookProc; //install hook using (var curProcess = Process.GetCurrentProcess()) using (var curModule = curProcess.MainModule) { _keyboardHookHandle = NativeMethods.SetWindowsHookEx( HookType.WH_KEYBOARD_LL, _keyboardDelegate, NativeMethods.GetModuleHandle(curModule.ModuleName), 0); } //If SetWindowsHookEx fails. if (_keyboardHookHandle == IntPtr.Zero) { //Returns the error code returned by the last unmanaged function called using platform invoke that has the DllImportAttribute.SetLastError flag set. var errorCode = Marshal.GetLastWin32Error(); //do cleanup //Initializes and throws a new instance of the Win32Exception class with the specified error. throw new Win32Exception(errorCode); } }
/// <summary> /// Enable the hook /// </summary> /// <returns></returns> public bool Enable() { _hockDelegate = new NativeMethods.HookProc(KeyHookProc); _hookHandle = NativeMethods.SetWindowsHookEx(NativeMethods.WH_KEYBOARD_LL, _hockDelegate, IntPtr.Zero, 0); return(_hookHandle != 0); }
public void Attach() { _hookProc = HookProc; _windowHook = User32.SetWindowsHookEx( HookType.WhCbt, _hookProc, IntPtr.Zero, (int)Kernel32.GetCurrentThreadId()); }
void SetHook() { if (!Hooked) { var cb = new NativeMethods.HookProc(WindowHookProc); Hook = NativeMethods.SetWindowsHookEx(WH_CBT, cb, NativeMethods.GetModuleHandle(null), NativeMethods.GetCurrentThreadId()); Hooked = true; } }
public static int SetHook(NativeMethods.HookProc proc) { using (Process curProcess = Process.GetCurrentProcess()) using (ProcessModule curModule = curProcess.MainModule) { return(NativeMethods.SetWindowsHookEx(Input.WH_MOUSE_LL, proc, Windows.GetModuleHandle(curModule.ModuleName), 0)); } }
/// <summary> /// 手动安装键盘钩子 /// </summary> public void SetHook() { KeyboardHookDelegate = new NativeMethods.HookProc(KeyboardHookProc); ProcessModule cModule = Process.GetCurrentProcess().MainModule; var mh = NativeMethods.GetModuleHandle(cModule.ModuleName); hHook = NativeMethods.SetWindowsHookEx(NativeMethods.WHKEYBOARDLL, KeyboardHookDelegate, mh, 0); GCHandle.Alloc(KeyboardHookDelegate); }
public static IntPtr SetWindowsHookEx(NativeMethods.HookType hookType, NativeMethods.HookProc lpfn, IntPtr hMod, int dwThreadId) { Contract.Ensures(Contract.Result <IntPtr>() != IntPtr.Zero); var handle = UnsafeNativeMethods.SetWindowsHookEx(hookType, lpfn, hMod, dwThreadId); ThrowLastError(handle == IntPtr.Zero); return(handle); }
public IntPtr SetHook(int HookNum, NativeMethods.HookProc proc) { using var curProcess = Process.GetCurrentProcess(); using var curModule = curProcess.MainModule ?? throw new NullReferenceException("Main Module not found"); if (_moduleHandle == IntPtr.Zero) { _moduleHandle = NativeMethods.GetModuleHandle(curModule.ModuleName); } return(NativeMethods.SetWindowsHookEx(HookNum, proc, _moduleHandle, 0)); }
/// <summary> /// Disable the hook /// </summary> public void Disable() { if (_hookHandle != 0) { NativeMethods.UnhookWindowsHookEx(_hookHandle); } _hookHandle = 0; _hockDelegate = null; }
public static IntPtr SetHook(HookType hookType, NativeMethods.HookProc hookProc) { using (var curProcess = Process.GetCurrentProcess()) { using var curModule = curProcess.MainModule; HookId = NativeMethods.SetWindowsHookEx((int)hookType, hookProc, NativeMethods.GetModuleHandle(curModule?.ModuleName), 0); } return(HookId); }
/// <summary> /// 削除。 /// </summary> /// <param name="proc">メッセージ解析メソッド。</param> internal void Remove(AnalyzeMessage proc) { _proc.Remove(proc); if (0 < _proc.Count) { return; } NativeMethods.UnhookWindowsHookEx(_idHook); GC.KeepAlive(_traceProc); _traceProc = null; }
public override void Start() { //https://stackoverflow.com/questions/8980873/implementing-a-win32-message-loop-and-creating-a-window-object-with-p-invoke _messageWindowProc = WndProc; w = new WNDCLASSEX { cbSize = (uint)Marshal.SizeOf(typeof(WNDCLASSEX)), lpszClassName = "OTB_Message_Watcher_Class", lpfnWndProc = _messageWindowProc }; NativeMethods.RegisterClassEx(ref w); IntPtr hInstance = NativeMethods.GetModuleHandle(Process.GetCurrentProcess().MainModule.ModuleName); //new IntPtr(-3) = MESSAGE ONLY _messageWindowHandle = NativeMethods.CreateWindowEx(0, w.lpszClassName, w.lpszClassName, 0, 0, 0, 0, 0, new IntPtr(-3), IntPtr.Zero, hInstance /*Can I make this 0?*/, IntPtr.Zero); NativeMethods.AddClipboardFormatListener(_messageWindowHandle); _windowsMouseHookHandle = IntPtr.Zero; _user32LibraryHandle = IntPtr.Zero; _mouseHookProc = LowLevelMouseProc; // we must keep alive _hookProc, because GC is not aware about SetWindowsHookEx behaviour. _windowsKeyboardHookHandle = IntPtr.Zero; _keyboardHookProc = LowLevelKeyboardProc; // we must keep alive _hookProc, because GC is not aware about SetWindowsHookEx behaviour. _user32LibraryHandle = NativeMethods.LoadLibrary("User32"); if (_user32LibraryHandle == IntPtr.Zero) { int errorCode = Marshal.GetLastWin32Error(); throw new Win32Exception(errorCode, $"Failed to load library 'User32.dll'. Error {errorCode}: {new Win32Exception(Marshal.GetLastWin32Error()).Message}."); } _windowsMouseHookHandle = NativeMethods.SetWindowsHookEx(WH_MOUSE_LL, _mouseHookProc, _user32LibraryHandle, 0); if (_windowsMouseHookHandle == IntPtr.Zero) { int errorCode = Marshal.GetLastWin32Error(); throw new Win32Exception(errorCode, $"Failed to adjust mouse hooks for '{Process.GetCurrentProcess().ProcessName}'. Error {errorCode}: {new Win32Exception(Marshal.GetLastWin32Error()).Message}."); } _windowsKeyboardHookHandle = NativeMethods.SetWindowsHookEx(WH_KEYBOARD_LL, _keyboardHookProc, _user32LibraryHandle, 0); if (_windowsKeyboardHookHandle == IntPtr.Zero) { int errorCode = Marshal.GetLastWin32Error(); throw new Win32Exception(errorCode, $"Failed to adjust keyboard hooks for '{Process.GetCurrentProcess().ProcessName}'. Error {errorCode}: {new Win32Exception(Marshal.GetLastWin32Error()).Message}."); } //init initial cursor position if (NativeMethods.GetCursorPos(out Point p)) { MouseState.Position = new MousePoint(p.X, p.Y); } }
public FormNotification(FormBrowser owner, PluginManager pluginManager, NotificationFlags flags) { InitializeComponent(); this.owner = owner; this.plugins = pluginManager; this.flags = flags; owner.FormClosed += (sender, args) => Close(); browser = new ChromiumWebBrowser("about:blank") { MenuHandler = new ContextMenuNotification(this, !flags.HasFlag(NotificationFlags.DisableContextMenu)), LifeSpanHandler = new LifeSpanHandler() }; #if DEBUG browser.ConsoleMessage += BrowserUtils.HandleConsoleMessage; #endif browser.IsBrowserInitializedChanged += Browser_IsBrowserInitializedChanged; browser.LoadingStateChanged += Browser_LoadingStateChanged; browser.FrameLoadEnd += Browser_FrameLoadEnd; if (!flags.HasFlag(NotificationFlags.DisableScripts)) { notificationJS = ScriptLoader.LoadResource(NotificationScriptFile); browser.RegisterAsyncJsObject("$TD", new TweetDeckBridge(owner, this)); if (plugins != null) { pluginJS = ScriptLoader.LoadResource(PluginManager.PluginNotificationScriptFile); browser.RegisterAsyncJsObject("$TDP", plugins.Bridge); } } panelBrowser.Controls.Add(browser); if (flags.HasFlag(NotificationFlags.AutoHide)) { Program.UserConfig.MuteToggled += Config_MuteToggled; Disposed += (sender, args) => Program.UserConfig.MuteToggled -= Config_MuteToggled; if (Program.UserConfig.MuteNotifications) { PauseNotification(); } } mouseHookDelegate = MouseHookProc; Disposed += FormNotification_Disposed; }
public void Install() { khookProc = new NativeMethods.HookProc(KeyboardHookProc); mhookProc = new NativeMethods.HookProc(MouseHookProc); using (Process process = Process.GetCurrentProcess()) using (ProcessModule module = process.MainModule) { hhk = NativeMethods.SetWindowsHookEx(NativeMethods.HookType.WH_KEYBOARD_LL, khookProc, NativeMethods.GetModuleHandle(module.ModuleName), 0); hhm = NativeMethods.SetWindowsHookEx(NativeMethods.HookType.WH_MOUSE_LL, mhookProc, NativeMethods.GetModuleHandle(module.ModuleName), 0); } }
public void Install() { khookProc = new NativeMethods.HookProc(KeyboardHookProc); mhookProc = new NativeMethods.HookProc(MouseHookProc); using (Process process = Process.GetCurrentProcess()) using (ProcessModule module = process.MainModule) { hhk = NativeMethods.SetWindowsHookEx(NativeMethods.HookType.WH_KEYBOARD_LL, khookProc, NativeMethods.GetModuleHandle(module.ModuleName), 0); hhm = NativeMethods.SetWindowsHookEx(NativeMethods.HookType.WH_MOUSE_LL, mhookProc, NativeMethods.GetModuleHandle(module.ModuleName), 0); } }
private IntPtr SetHook(int HookNum, NativeMethods.HookProc proc) { using (Process curProcess = Process.GetCurrentProcess()) using (ProcessModule curModule = curProcess.MainModule) { if (ThisModHandle == IntPtr.Zero) { ThisModHandle = NativeMethods.GetModuleHandle(curModule.ModuleName); } return(NativeMethods.SetWindowsHookEx(HookNum, proc, ThisModHandle, 0)); } }
/// <summary> /// 卸载键盘钩子 /// </summary> public void Stop() { if (idHook != 0) { var result = NativeMethods.UnhookWindowsHookEx(idHook); idHook = 0; keyDelegate = null; if (result == 0) { HookError(); } } }
public void UnInstall() { if (hhk != null) { NativeMethods.UnhookWindowsHookEx(hhk); khookProc = null; } if (hhm != null) { NativeMethods.UnhookWindowsHookEx(hhm); mhookProc = null; } }
public void UnInstall() { if (hhk != null) { NativeMethods.UnhookWindowsHookEx(hhk); khookProc = null; } if (hhm != null) { NativeMethods.UnhookWindowsHookEx(hhm); mhookProc = null; } }
/// <summary>Starts intercepting keystrokes</summary> public static void StartInterceptor() { if (hHook == 0) { hookProc = new NativeMethods.HookProc(MouseHookProc); hHook = NativeMethods.SetWindowsHookEx(NativeMethods.WH_MOUSE_LL, hookProc, Marshal.GetHINSTANCE(Assembly.GetExecutingAssembly().GetModules()[0]), 0); if (hHook == 0) { int errorCode = Marshal.GetLastWin32Error(); StopInterceptor(); throw new Win32Exception(errorCode); } } }
protected virtual void Dispose(bool disposing) { if (disposing) { if (_messageWindowHandle != IntPtr.Zero) { NativeMethods.RemoveClipboardFormatListener(_messageWindowHandle); NativeMethods.DestroyWindow(_messageWindowHandle); NativeMethods.UnregisterClass("OTB_Message_Watcher_Class", IntPtr.Zero); } // because we can unhook only in the same thread, not in garbage collector thread if (_windowsMouseHookHandle != IntPtr.Zero) { if (!NativeMethods.UnhookWindowsHookEx(_windowsMouseHookHandle)) { int errorCode = Marshal.GetLastWin32Error(); throw new Win32Exception(errorCode, $"Failed to remove mouse hooks for '{Process.GetCurrentProcess().ProcessName}'. Error {errorCode}: {new Win32Exception(Marshal.GetLastWin32Error()).Message}."); } _windowsMouseHookHandle = IntPtr.Zero; // ReSharper disable once DelegateSubtraction _mouseHookProc -= LowLevelMouseProc; } // because we can unhook only in the same thread, not in garbage collector thread if (_windowsKeyboardHookHandle != IntPtr.Zero) { if (!NativeMethods.UnhookWindowsHookEx(_windowsKeyboardHookHandle)) { int errorCode = Marshal.GetLastWin32Error(); throw new Win32Exception(errorCode, $"Failed to remove keyboard hooks for '{Process.GetCurrentProcess().ProcessName}'. Error {errorCode}: {new Win32Exception(Marshal.GetLastWin32Error()).Message}."); } _windowsKeyboardHookHandle = IntPtr.Zero; // ReSharper disable once DelegateSubtraction _keyboardHookProc -= LowLevelKeyboardProc; } } if (_user32LibraryHandle != IntPtr.Zero) { if (!NativeMethods.FreeLibrary(_user32LibraryHandle)) // reduces reference to library by 1. { int errorCode = Marshal.GetLastWin32Error(); throw new Win32Exception(errorCode, $"Failed to unload library 'User32.dll'. Error {errorCode}: {new Win32Exception(Marshal.GetLastWin32Error()).Message}."); } _user32LibraryHandle = IntPtr.Zero; } }
/// <summary>Starts intercepting keystrokes</summary> public static void StartInterceptor() { if (hHook == 0) { hookProc = new NativeMethods.HookProc(MouseHookProc); IntPtr moduleHandle = NativeMethods.GetModuleHandle(Process.GetCurrentProcess().MainModule.ModuleName); hHook = NativeMethods.SetWindowsHookEx(NativeMethods.WH_MOUSE_LL, hookProc, moduleHandle, 0); if (hHook == 0) { int errorCode = Marshal.GetLastWin32Error(); StopInterceptor(); throw new Win32Exception(errorCode); } } }
/// <summary>Starts intercepting keystrokes</summary> public static void StartInterceptor() { if (hHook == 0) { hookProc = new NativeMethods.HookProc(KeyboardHookProc); IntPtr moduleHandle = NativeMethods.GetModuleHandle(Process.GetCurrentProcess().MainModule.ModuleName); hHook = NativeMethods.SetWindowsHookEx(NativeMethods.WH_KEYBOARD_LL, hookProc, moduleHandle, 0); if (hHook == 0) { int errorCode = Marshal.GetLastWin32Error(); StopInterceptor(); throw new Win32Exception(errorCode); } } }
public bool Hook() { mHookProc = new NativeMethods.HookProc(_Hook); IntPtr module = NativeMethods.LoadLibrary("user32"); mHookPtr = NativeMethods.SetWindowsHookEx(NativeEnums.HookType.WH_KEYBOARD_LL, mHookProc, module, 0); if (mHookPtr.ToInt32() != 0) { _hooked = true; } return(_hooked); }
public static void Initialize(ClientInstance clientInstance) { myWindowHandle = Process.GetCurrentProcess().MainWindowHandle; myClientInstance = clientInstance; myMsgHook = new NativeMethods.HookProc(MsgHook); myWindowMsgHook = new NativeMethods.HookProc(WindowMsgHook); Process p = Process.GetProcessById(EasyHook.RemoteHooking.GetCurrentProcessId()); uint x; uint threadID = NativeMethods.GetWindowThreadProcessId(p.MainWindowHandle, out x); /* Use user32.dll as SetWindowHookEx hMod as per http://stackoverflow.com/questions/17897646/gma-useractivitymonitor-setwindowshookex-error-126 */ IntPtr user32 = NativeMethods.LoadLibrary("user32.dll"); myMsgHookHandle = NativeMethods.SetWindowsHookEx(NativeMethods.WH_GETMESSAGE, Marshal.GetFunctionPointerForDelegate(myMsgHook), /*Marshal.GetHINSTANCE(Assembly.GetExecutingAssembly().GetModules()[0])*/user32, threadID); #if DEBUG if (myMsgHookHandle == IntPtr.Zero) { clientInstance.SendCommand(Command.Message, "Error installing WH_GETMESSAGE hook, GetLastError = " + Marshal.GetLastWin32Error().ToString()); } #endif myWindowMsgHookHandle = NativeMethods.SetWindowsHookEx(NativeMethods.WH_CALLWNDPROC, Marshal.GetFunctionPointerForDelegate(myWindowMsgHook), /*Marshal.GetHINSTANCE(Assembly.GetExecutingAssembly().GetModules()[0])*/user32, threadID); #if DEBUG if (myWindowMsgHookHandle == IntPtr.Zero) { clientInstance.SendCommand(Command.Message, "Error installing WH_CALLWNDPROC hook, GetLastError = " + Marshal.GetLastWin32Error().ToString()); } #endif NativeMethods.WINDOWPLACEMENT wp = new NativeMethods.WINDOWPLACEMENT(); if (NativeMethods.GetWindowPlacement(myWindowHandle, ref wp)) { MessageHook.myWindowX = wp.rcNormalPosition.X; MessageHook.myWindowY = wp.rcNormalPosition.Y; } if (myMsgHookHandle == IntPtr.Zero || myWindowMsgHookHandle == IntPtr.Zero) { clientInstance.SendCommand(Command.Message, "Error installing WH_GETMESSAGE\\WH_CALLWNDPROC hooks!"); } }
private void UninstallMessageHook() { lock (this) { if (messageHookHandle != IntPtr.Zero) { UnsafeNativeMethods.UnhookWindowsHookEx(new HandleRef(this, messageHookHandle)); hookProc = null; messageHookHandle = IntPtr.Zero; isHooked = false; } } }
public LocalWindowsHook(HookType hook) { this._mHookType = hook; this._mFilterFunc = this.CoreHookProc; }
private void ApplyCustomChrome() { if (!isHooked) { hwndSource.AddHook(this.WndProc); mouseProc = this.MouseWndProc; #pragma warning disable 618 mouseHook = NativeMethods.SetWindowsHookEx(NativeMethods.HookType.WH_MOUSE, mouseProc, IntPtr.Zero, AppDomain.GetCurrentThreadId()); isHooked = true; } FixFrameworkIssues(); // Force this the first time. UpdateSystemMenu(WindowState); UpdateFrameState(true); NativeMethods.SetWindowPos(handle, IntPtr.Zero, 0, 0, 0, 0, SwpFlags); }
/// <summary> /// コンストラクタ。 /// </summary> /// <param name="threadId">スレッドID。</param> internal void Init(int threadId) { _traceProc = WindowProcHook; _idHook = NativeMethods.SetWindowsHookEx(HookType, _traceProc, IntPtr.Zero, threadId); }
public void SetHook(bool enable) { if (enable && _mHHook == 0) { _mHookCallback = HookCallbackProc; var module = Assembly.GetExecutingAssembly().GetModules()[0]; _mHHook = NativeMethods.SetWindowsHookEx(NativeMethods.WH_KEYBOARD_LL, _mHookCallback, Marshal.GetHINSTANCE(module), 0); if (_mHHook != 0) return; MessageBox.Show(@"SetHook Failed. Please make sure the 'Visual Studio Host Process' on the debug setting page is disabled"); return; } if (enable || _mHHook == 0) return; NativeMethods.UnhookWindowsHookEx(_mHHook); _mHHook = 0; }
private void InstallMessageHook() { lock (this) { if (messageHookHandle != IntPtr.Zero) { return; } hookProc = new NativeMethods.HookProc(this.MessageHookProc); messageHookHandle = UnsafeNativeMethods.SetWindowsHookEx(NativeMethods.WH_GETMESSAGE, hookProc, new HandleRef(null, IntPtr.Zero), SafeNativeMethods.GetCurrentThreadId()); if (messageHookHandle != IntPtr.Zero) { isHooked = true; } Debug.Assert(messageHookHandle != IntPtr.Zero, "Failed to install mouse hook"); } }
public LocalWindowsHook(HookType hook) { m_hookType = hook; m_filterFunc = CoreHookProc; }
private void HookMouse() { GC.KeepAlive(this); // Locking 'this' here is ok since this is an internal class. See VSW#464499. lock(this) { if (mouseHookHandle != IntPtr.Zero) { return; } if (thisProcessID == 0) { SafeNativeMethods.GetWindowThreadProcessId(new HandleRef(control, control.Handle), out thisProcessID); } NativeMethods.HookProc hook = new NativeMethods.HookProc(new MouseHookObject(this).Callback); mouseHookRoot = GCHandle.Alloc(hook); mouseHookHandle = UnsafeNativeMethods.SetWindowsHookEx(NativeMethods.WH_MOUSE, hook, NativeMethods.NullHandleRef, SafeNativeMethods.GetCurrentThreadId()); Debug.Assert(mouseHookHandle != IntPtr.Zero, "Failed to install mouse hook"); Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "DropDownHolder:HookMouse()"); } }
private void TrackDropDown(int index) { while (index >= 0) { this.trackNextItem = -1; this.BeginUpdate(); CommandBarMenu menu = this.items[index] as CommandBarMenu; if (menu != null) { menu.PerformDropDown(EventArgs.Empty); this.contextMenu.Items.Clear(); this.contextMenu.Items.AddRange(menu.Items); // = menu.Items; this.contextMenu.Mnemonics = true; } else { this.contextMenu.Items.Clear(); // .Items = new CommandBarItemCollection(); this.contextMenu.Mnemonics = true; } // Item state NativeMethods.SendMessage(this.Handle, NativeMethods.TB_PRESSBUTTON, index, -1); // Trick to get the first menu item selected NativeMethods.PostMessage(this.Handle, NativeMethods.WM_KEYDOWN, (int) Keys.Down, 1); NativeMethods.PostMessage(this.Handle, NativeMethods.WM_KEYUP, (int) Keys.Down, 1); this.SetState(State.HotTracking, index); // Hook NativeMethods.HookProc hookProc = new NativeMethods.HookProc(DropDownHook); GCHandle hookProcHandle = GCHandle.Alloc(hookProc); this.hookHandle = NativeMethods.SetWindowsHookEx(NativeMethods.WH_MSGFILTER, hookProc, IntPtr.Zero, NativeMethods.GetCurrentThreadId()); if (this.hookHandle == IntPtr.Zero) { throw new SecurityException(); } // Ask for position NativeMethods.RECT rect = new NativeMethods.RECT(); NativeMethods.SendMessage(Handle, NativeMethods.TB_GETRECT, index, ref rect); Point position = new Point(rect.left, rect.bottom); this.EndUpdate(); this.Update(); this.contextMenu.Show(this, position); // Unhook NativeMethods.UnhookWindowsHookEx(hookHandle); hookProcHandle.Free(); this.hookHandle = IntPtr.Zero; // Item state NativeMethods.SendMessage(Handle, NativeMethods.TB_PRESSBUTTON, index, 0); this.SetState(trackEscapePressed ? State.Hot : State.None, index); index = trackNextItem; } }
/// <include file='doc\SendKeys.uex' path='docs/doc[@for="SendKeys.InstallHook"]/*' /> /// <devdoc> /// install the hook. quite easy /// </devdoc> private static void InstallHook() { if (hhook == IntPtr.Zero) { hook = new NativeMethods.HookProc(new SendKeysHookProc().Callback); stopHook = false; hhook = UnsafeNativeMethods.SetWindowsHookEx(NativeMethods.WH_JOURNALPLAYBACK, hook, new HandleRef(null, UnsafeNativeMethods.GetModuleHandle(null)), 0); if (hhook == IntPtr.Zero) throw new SecurityException(SR.GetString(SR.SendKeysHookFailed)); } }
public LocalWindowsHook(Win32.HookType hook) { m_hookType = hook; m_filterFunc = new NativeMethods.HookProc(this.CoreHookProc); }
private static void TestHook() { hookSupported = false; try { NativeMethods.HookProc hookProc = new NativeMethods.HookProc(EmptyHookCallback); IntPtr hookHandle = UnsafeNativeMethods.SetWindowsHookEx(NativeMethods.WH_JOURNALPLAYBACK, hookProc, new HandleRef(null, UnsafeNativeMethods.GetModuleHandle(null)), 0); hookSupported = (hookHandle != IntPtr.Zero); if (hookHandle != IntPtr.Zero) { UnsafeNativeMethods.UnhookWindowsHookEx(new HandleRef(null, hookHandle)); } } catch {} // ignore any exceptions to keep existing SendKeys behavior }