示例#1
0
        public ShellHook()
        {
            if (IsRegistered)
                throw new InvalidOperationException("ShellHook already initialized.");
            try
            {
                _wnd = new NativeWindowEx();
                _wnd.CreateHandle(new CreateParams());
                _wndHandle = _wnd.Handle;

                // Register to receive shell-related events
                if (_wndHandle != IntPtr.Zero)
                    _initShellHook = WinAPI.RegisterShellHookWindow(_wnd.Handle);
                if (_initShellHook)
                    WinAPI.WM_SHELLHOOKMESSAGE = WinAPI.RegisterWindowMessage("SHELLHOOK");
                if (WinAPI.WM_SHELLHOOKMESSAGE != -1)
                    _initWindowMessage = true;
                if (!_initWindowMessage)
                {
                    Cleanup();
                    return;
                }
                _wnd.MessageReceived += ShellHookHandler;
                _initHotkey1 = WinAPI.RegisterHotKey(_wndHandle, _HotKey1Id, (uint)_HotKeyModifier, (uint)_HotKey1);
                _initHotkey2 = WinAPI.RegisterHotKey(_wndHandle, _HotKey2Id, (uint)_HotKeyModifier, (uint)_HotKey2);
                IsRegistered = true;
            }
            catch
            {
                Cleanup();
            }
        }
示例#2
0
 private void Cleanup()
 {
     if (_wndHandle != IntPtr.Zero)
     {
         WinAPI.WM_SHELLHOOKMESSAGE = -1;
         if (_initShellHook)
             WinAPI.DeregisterShellHookWindow(_wndHandle);
         if (_initHotkey1)
             WinAPI.UnregisterHotKey(_wndHandle, _HotKey1Id);
         if (_initHotkey2)
             WinAPI.UnregisterHotKey(_wndHandle, _HotKey2Id);
     }
     if (_wnd != null)
     {
         _wnd.DestroyHandle();
         _wnd = null;
     }
     IsRegistered = false;
 }