Пример #1
0
        public Form1()
        {
            this.InitializeComponent();

            this.hook = new DebugLowLevelKeyboardHook();
            this.hook.Install();
        }
Пример #2
0
        static KKey _WaitForKey(double secondsTimeout, KKey key, bool up, bool block)
        {
            //SHOULDDO: if up and block: don't block if was down when starting to wait. Also in the Mouse func.

            KKey R = 0;

            using (WindowsHook.Keyboard(x => {
                if (key != 0 && !x.IsKey(key))
                {
                    return;
                }
                if (x.IsUp != up)
                {
                    if (up && block)                       //key down when waiting for up. If block, now block down too.
                    {
                        if (key == 0)
                        {
                            key = x.vkCode;
                        }
                        x.BlockEvent();
                    }
                    return;
                }
                R = x.vkCode;                 //info: for mod keys returns left/right
                if (block)
                {
                    x.BlockEvent();
                }
            })) wait.forMessagesAndCondition(secondsTimeout, () => R != 0);

            return(R);
        }
Пример #3
0
        public void Register(RadDropDownMenu menu)
        {
            if (menu == ActiveDropDown || DropDowns.Contains(menu))
            {
                return;
            }

            Suspended = true;
            if (ActiveDropDown != null)
            {
                //ActiveDropDown.Capture = false;
                if (menu != null && menu.OwnerElement != null && menu.OwnerElement.ElementTree != null)
                {
                    RadDropDownMenu menuOwner = menu.OwnerElement.ElementTree.Control as RadDropDownMenu;
                    if (menuOwner != null)
                    {
                        int index = DropDowns.IndexOf(menuOwner);
                        while (index < DropDowns.Count - 1)
                        {
                            DropDowns[DropDowns.Count - 1].ClosePopup(RadPopupCloseReason.CloseCalled);
                        }
                    }
                }
            }
            else
            {
                if (!InDesignMode)
                {
                    Application.AddMessageFilter(this);
                }
                else
                {
                    hookMouse              = new WindowsHook(WindowsHook.HookType.WH_MOUSE_LL);
                    hookMouse.HookInvoked += new WindowsHook.HookEventHandler(hookMouse_HookInvoked);
                    hookMouse.Install();
                }
            }
            this.DropDowns.Add(menu);
            ActiveDropDown = menu;
            Suspended      = false;

            //if (InDesignMode && selectionService == null)
            //{
            //    if (ActiveDropDown.OwnerElement is ISiteProvider)
            //    {
            //        ISite site = (ActiveDropDown.OwnerElement as ISiteProvider).GetSite();
            //        selectionService = (ISelectionService)site.GetService(typeof(ISelectionService));
            //        selectionService.SelectionChanged += new EventHandler(selectionService_SelectionChanged);
            //    }
            //}
        }
Пример #4
0
        public void WndProcRet(object sender, WndProcRetEventArgs e)
        {
            if (e.cw.message == WndMessage.WM_INITDIALOG ||
                e.cw.message == WndMessage.WM_UNKNOWINIT)
            {
                USER32.MoveWindow(e.cw.hwnd, rect.Left, rect.Top, rect.Width, rect.Height, 1);

                // uninstall this hook
                WindowsHook wndHook = (WindowsHook)sender;
                Debug.Assert(wndProcRetHook == wndHook);
                wndProcRetHook.Uninstall();
                wndProcRetHook = null;
            }
        }
Пример #5
0
        /// <summary>
        /// 停止全局钩子
        /// </summary>
        /// <exception cref="System.Exception">UnhookWindowsHookEx failed.</exception>
        /// <exception cref="Exception">UnhookWindowsHookEx failed.</exception>
        public static void Stop()
        {
            bool retMouse = true;

            if (_hMouseHook != 0)
            {
                retMouse    = WindowsHook.StopHook(_hMouseHook);
                _hMouseHook = 0;
            }

            // 假设卸下钩子失败
            if (!(retMouse))
            {
                throw new Exception("UnhookWindowsHookEx failed.");
            }
        }
        private async void Window_Loaded(object sender, RoutedEventArgs e)
        {
            textBox.Clear();
            //proc = Process.Start($@"C:\Work\Shortcuts\Launch Shantae and the Pirate's Curse.lnk");
            proc = Process.GetCurrentProcess();
            //proc = Process.Start($@"notepad.exe");
            textBox.AppendText($"proc_hndl={proc.MainWindowHandle}\n");
            await Task.Delay(1000);

            hwnd = proc.MainWindowHandle;
            textBox.AppendText($"hwnd={hwnd}\n");
            mh = new WindowsHook(hwnd, HookType.WH_GETMESSAGE);
            mh.InstallHook();
            //mh.MouseDown += Mh_MouseDown;
            //mh.MouseMove += delegate { };
        }
Пример #7
0
        void _ThreadProc()
        {
            WindowsHook hk = null, hm = null; WinEventHook hwe = null;

            try {
                try {
                    if (_block.Has(BIEvents.Keys))
                    {
                        hk = WindowsHook.Keyboard(_keyHookProc ??= _KeyHookProc);
                    }
                    if (_block.HasAny(BIEvents.MouseClicks | BIEvents.MouseMoving))
                    {
                        hm = WindowsHook.Mouse(_mouseHookProc ??= _MouseHookProc);
                    }
                }
                catch (AuException e1) { Debug_.Print(e1); _block = 0; return; }                 //failed to hook

                //This prevents occassional inserting a foreign key after the first our-script-pressed key.
                //To reproduce, let our script send small series of chars in loop, and simultaneously a foreign script send other chars.
                wait.doEvents();

                //print.it("started");
                Api.SetEvent(_syncEvent);

                //the hook detects Ctrl+Alt+Del, Win+L, UAC consent, etc. SystemEvents.SessionSwitch only Win+L.
                try { hwe = new WinEventHook(EEvent.SYSTEM_DESKTOPSWITCH, 0, _winEventProc ??= _WinEventProc); }
                catch (AuException e1) { Debug_.Print(e1); }                 //failed to hook

                wait.Wait_(-1, WHFlags.DoEvents, _stopEvent, _threadHandle);

                if (_blockedKeys != null)
                {
                    bool onlyUp = _discardBlockedKeys || Environment.TickCount64 - _startTime > c_maxResendTime;
                    _blockedKeys.SendBlocked_(onlyUp);
                }
                //print.it("ended");
            }
            finally {
                _blockedKeys = null;
                hk?.Dispose();
                hm?.Dispose();
                hwe?.Dispose();
                Api.SetEvent(_syncEvent);
            }
            GC.KeepAlive(this);
        }
Пример #8
0
        private static int _hMouseHook = 0; // 鼠标钩子句柄
        /// <summary>
        /// 启动全局钩子
        /// </summary>
        /// <exception cref="System.Exception">SetWindowsHookEx failed.</exception>
        /// <exception cref="Exception">SetWindowsHookEx failed.</exception>
        public static void Start()
        {
            // 安装鼠标钩子
            if (_hMouseHook != 0)
            {
                Stop();
            }
            // 生成一个HookProc的实例.
            WindowsHook.HookMsgChanged += WindowsHook_HookMsgChanged;
            _hMouseHook = WindowsHook.StartHook(HookType.WH_MOUSE_LL);

            //假设装置失败停止钩子
            if (_hMouseHook == 0)
            {
                Stop();
            }
        }
Пример #9
0
        /// <summary>
        /// Waits for keyboard events using callback function.
        /// </summary>
        /// <returns>
        /// Returns the key code. On timeout returns 0 if <i>secondsTimeout</i> is negative; else exception.
        /// For modifier keys returns the left or right key code, for example LCtrl/RCtrl, not Ctrl.
        /// </returns>
        /// <param name="secondsTimeout">Timeout, seconds. Can be 0 (infinite), &gt;0 (exception) or &lt;0 (no exception). More info: [](xref:wait_timeout).</param>
        /// <param name="f">Callback function that receives key down and up events. Let it return true to stop waiting.</param>
        /// <param name="block">Make the key down event invisible for other apps (when the callback function returns true).</param>
        /// <remarks>
        /// Waits for key event, not for key state.
        /// Uses low-level keyboard hook.
        /// Ignores key events injected by functions of this library.
        /// </remarks>
        /// <example>
        /// Wait for F3 or Esc.
        /// <code><![CDATA[
        /// var k = keys.waitForKeys(0, k => !k.IsUp && k.Key is KKey.F3 or KKey.Escape, block: true);
        /// print.it(k);
        /// ]]></code>
        /// </example>
        public static KKey waitForKeys(double secondsTimeout, Func <HookData.Keyboard, bool> f, bool block = false)
        {
            KKey R = 0;

            using (WindowsHook.Keyboard(x => {
                if (!f(x))
                {
                    return;
                }
                R = x.vkCode;                 //info: for mod keys returns left/right
                if (block && !x.IsUp)
                {
                    x.BlockEvent();
                }
            })) wait.forMessagesAndCondition(secondsTimeout, () => R != 0);

            return(R);
        }
Пример #10
0
        public void WndProcRet(object sender, WndProcRetEventArgs e)
        {
            switch (e.cw.message)
            {
            case WndMessage.WM_INITDIALOG:
            case WndMessage.WM_UNKNOWINIT:
            case WndMessage.WM_ACTIVATE:    //tony 2011.3.12 update 这是能否显示在当前父窗体中央的关键!
                USER32.MoveWindow(e.cw.hwnd, rect.Left, rect.Top, rect.Width, rect.Height, 1);
                // uninstall this hook
                WindowsHook wndHook = (WindowsHook)sender;
                Debug.Assert(wndProcRetHook == wndHook);
                wndProcRetHook.Uninstall();
                wndProcRetHook = null;
                break;

            default: break;
            }
        }
Пример #11
0
        void _Thread()
        {
            _tid = Api.GetCurrentThreadId();

            WindowsHook hookK = null, hookM = null;

            if (_usedEvents.Has(UsedEvents.Keyboard))
            {
                hookK = WindowsHook.Keyboard(_KeyboardHookProc);                 //note: if lambda, very slow JIT on first hook event
            }
            if (_usedEvents.Has(UsedEvents.Mouse))
            {
                hookM = WindowsHook.MouseRaw_(_MouseHookProc);
            }
            if (_usedEvents.Has(UsedEvents.MouseEdgeMove))
            {
                _emDetector = new MouseTriggers.EdgeMoveDetector_();
            }
            //tested: don't need JIT-compiling.

            nint idTimer = (hookK != null || hookM != null) ? Api.SetTimer(default, 0, 10_000, null) : 0;
        /// <summary>
        /// Installs the hook.
        /// </summary>
        /// <returns></returns>
        public bool InstallHook()
        {
            lock (lockObject)
            {
                if (hook != null)
                {
                    return(false);
                }

                hook = new WindowsHook(WindowsHookType.LowLevelMouse);
            }

            hook.OnHookCalled += Hook_OnHookCalled;

            hook.InstallHook();

            Global.OnProcessExit        += Global_OnProcessExit;
            Global.OnUnhandledException += Global_OnUnhandledException;

            return(true);
        }
        /// <summary>
        /// Uninstalls the hook.
        /// </summary>
        /// <returns></returns>
        public bool UninstallHook()
        {
            lock (lockObject)
            {
                if (hook == null)
                {
                    return(false);
                }

                Global.OnProcessExit        -= Global_OnProcessExit;
                Global.OnUnhandledException -= Global_OnUnhandledException;

                hook.OnHookCalled -= Hook_OnHookCalled;

                hook.UninstallHook();

                hook.Dispose();

                hook = null;

                return(true);
            }
        }
Пример #14
0
 /// <summary>
 /// Required method for Designer support - do not modify
 /// the contents of this method with the code editor.
 /// </summary>
 private void InitializeComponent()
 {
     this.components = new System.ComponentModel.Container();
     System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(MessageBalloon));
     this.windowsHook = new mdlComponentesGraficos.BalloonTip.WindowsHook(this.components);
     this.timer1      = new System.Windows.Forms.Timer(this.components);
     this.closeButton = new System.Windows.Forms.Button();
     this.SuspendLayout();
     //
     // windowsHook
     //
     this.windowsHook.ThreadID = 0;
     //
     // timer1
     //
     this.timer1.Interval = 5000;
     this.timer1.Tick    += new System.EventHandler(this.timer1_Tick);
     //
     // closeButton
     //
     this.closeButton.Anchor    = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
     this.closeButton.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
     this.closeButton.Image     = ((System.Drawing.Image)(resources.GetObject("closeButton.Image")));
     this.closeButton.Location  = new System.Drawing.Point(136, 0);
     this.closeButton.Name      = "closeButton";
     this.closeButton.Size      = new System.Drawing.Size(14, 14);
     this.closeButton.TabIndex  = 1;
     //
     // MessageBalloon
     //
     this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
     this.ClientSize        = new System.Drawing.Size(152, 94);
     this.Controls.Add(this.closeButton);
     this.Name = "MessageBalloon";
     this.ResumeLayout(false);
 }
Пример #15
0
 public void Register(RadDropDownMenu menu)
 {
     if (menu == this.ActiveDropDown || this.DropDowns.Contains(menu))
     {
         return;
     }
     this.Suspended = true;
     if (this.ActiveDropDown != null)
     {
         if (menu != null && menu.OwnerElement != null && menu.OwnerElement.ElementTree != null)
         {
             RadDropDownMenu control = menu.OwnerElement.ElementTree.Control as RadDropDownMenu;
             if (control != null)
             {
                 int num = this.DropDowns.IndexOf(control);
                 while (num < this.DropDowns.Count - 1)
                 {
                     this.DropDowns[this.DropDowns.Count - 1].ClosePopup(RadPopupCloseReason.CloseCalled);
                 }
             }
         }
     }
     else if (!RadModalFilter.InDesignMode)
     {
         Application.AddMessageFilter((IMessageFilter)this);
     }
     else
     {
         this.hookMouse              = new WindowsHook(WindowsHook.HookType.WH_MOUSE_LL);
         this.hookMouse.HookInvoked += new WindowsHook.HookEventHandler(this.hookMouse_HookInvoked);
         this.hookMouse.Install();
     }
     this.DropDowns.Add(menu);
     this.ActiveDropDown = menu;
     this.Suspended      = false;
 }
Пример #16
0
        /// <summary>
        ///     Installs the hook.
        /// </summary>
        /// <returns></returns>
        public bool InstallHook()
        {
            lock (_lockObject)
            {
                if (_hook != null)
                {
                    return(false);
                }

                _hook = new WindowsHook(WindowsHookType.LowLevelMouse);
            }

            _hook.OnHookCalled += Hook_OnHookCalled;

            if (!_hook.InstallHook())
            {
                WinApi.ThrowWin32Exception("Unknown error while installing hook.");
            }

            Global.OnProcessExit        += Global_OnProcessExit;
            Global.OnUnhandledException += Global_OnUnhandledException;

            return(true);
        }
Пример #17
0
        public void WndActivate(object sender, CbtEventArgs e)
        {
            IntPtr hMsgBox = e.wParam;

            // try to find a howner for this message box
            if (hOwner == IntPtr.Zero)
            {
                hOwner = USER32.GetActiveWindow();
            }

            // get the MessageBox window rect
            RECT rectDlg = new RECT();

            USER32.GetWindowRect(hMsgBox, ref rectDlg);

            // get the owner window rect
            RECT rectForm = new RECT();

            USER32.GetWindowRect(hOwner, ref rectForm);

            // get the biggest screen area
            Rectangle rectScreen = API.TrueScreenRect;

            // if no parent window, center on the primary screen
            if (rectForm.right == rectForm.left)
            {
                rectForm.right = rectForm.left = Screen.PrimaryScreen.WorkingArea.Width / 2;
            }
            if (rectForm.bottom == rectForm.top)
            {
                rectForm.bottom = rectForm.top = Screen.PrimaryScreen.WorkingArea.Height / 2;
            }

            // center on parent
            int dx = ((rectDlg.left + rectDlg.right) - (rectForm.left + rectForm.right)) / 2;
            int dy = ((rectDlg.top + rectDlg.bottom) - (rectForm.top + rectForm.bottom)) / 2;

            rect = new Rectangle(
                rectDlg.left - dx,
                rectDlg.top - dy,
                rectDlg.right - rectDlg.left,
                rectDlg.bottom - rectDlg.top);

            // place in the screen
            if (rect.Right > rectScreen.Right)
            {
                rect.Offset(rectScreen.Right - rect.Right, 0);
            }
            if (rect.Bottom > rectScreen.Bottom)
            {
                rect.Offset(0, rectScreen.Bottom - rect.Bottom);
            }
            if (rect.Left < rectScreen.Left)
            {
                rect.Offset(rectScreen.Left - rect.Left, 0);
            }
            if (rect.Top < rectScreen.Top)
            {
                rect.Offset(0, rectScreen.Top - rect.Top);
            }

            if (e.IsDialog)
            {
                // do the job when the WM_INITDIALOG message returns
                wndProcRetHook             = new WndProcRetHook(hMsgBox);
                wndProcRetHook.WndProcRet += new WndProcRetHook.WndProcEventHandler(WndProcRet);
                wndProcRetHook.Install();
            }
            else
            {
                USER32.MoveWindow(hMsgBox, rect.Left, rect.Top, rect.Width, rect.Height, 1);
            }

            // uninstall this hook
            WindowsHook wndHook = (WindowsHook)sender;

            Debug.Assert(cbtHook == wndHook);
            cbtHook.Uninstall();
            cbtHook = null;
        }
Пример #18
0
 public static extern IntPtr SetWindowsHookEx(WindowsHook idHook,
                                              MouseHookProc lpfn, IntPtr hMod, uint dwThreadId);
Пример #19
0
 public static extern IntPtr SetWindowsHookEx(WindowsHook hookType, HookProc lpfn, IntPtr hMod, uint dwThreadId);
 public static extern IntPtr SetWindowsHookEx(
     [In] WindowsHook idHook,
     [In] Delegate lpfn,
     [In] IntPtr hMod,
     [In] uint dwThreaedId = 0
     );
Пример #21
0
 public void Dispose()
 {
     WindowsHook?.Cancel();
 }
 protected Hook(WindowsHook hookType, SynchronizationContext sync)
 {
     this.hookType = hookType;
     this.sync     = sync;
     this.handler  = new Lazy <Delegate>(this.GetHandler);
 }