LOGO OA教程 ERP教程 模切知識交流 PMS教程 CRM教程 開發文檔 其他文檔  
 
網站管理員

C#鉤子(Hook) 捕獲鍵盤鼠標所有事件 - 5分鐘沒有操作,自動關閉 Form 窗體

freeflydom
2025年1月15日 8:49 本文熱度 363

C# 鉤子 捕獲鍵盤鼠標所有事件,可用于:判斷鼠標鍵盤無操作時,關閉 Winform 窗體
5分鐘沒有操作,自動關閉 Form 窗體

鉤子(Hook)的作用主要體現在監視和攔截系統或進程中的各種事件消息,并進行自定義處理。鉤子可以截獲并處理相應的消息,例如鍵盤鉤子可以截獲鍵盤消息,外殼鉤子可以截取、啟動和關閉應用程序的消息等。鉤子分為線程鉤子和系統鉤子,線程鉤子監視指定線程的事件消息,而系統鉤子監視系統中的所有線程的事件消息

鉤子的具體應用場景和功能

  • 鍵盤和鼠標輸入監控:鉤子可以截獲鍵盤和鼠標的輸入,用于記錄用戶的操作或進行自動化測試。
  • 屏幕取詞和日志監視:通過監控系統事件,鉤子可以實現屏幕取詞功能或記錄系統的操作日志。
  • 應用程序監控:外殼鉤子可以截取、啟動和關閉應用程序的消息,用于監控或管理應用程序的行為。

鉤子的種類及其功能

  • 鍵盤鉤子:截獲鍵盤消息,用于記錄鍵盤輸入或進行輸入攔截。
  • 鼠標鉤子:截獲鼠標事件,用于監控鼠標操作。
  • 外殼鉤子:截取、啟動和關閉應用程序的消息,用于管理應用程序行為。
  • 日志鉤子:監控系統日志事件,用于記錄系統操作日志。

鉤子的工作原理
鉤子是Windows消息處理機制中的一個監視點,應用程序可以在這里安裝一個監視子程序,從而在系統的消息流到達目的窗口的過程前監控它們。通過這種方式,鉤子能夠實現各種自定義的功能和處理邏輯

  • GlobalHook

  • KeyboardHook

  • MouseHook

  • KeyboardSimulator

  • MouseSimulator

GlobalHook

using System;
using System.Text;
using System.Runtime.InteropServices;
using System.Reflection;
using System.Windows.Forms;
namespace VipSoft.BaseClass.Hook
{
    /// <summary>  
    /// Abstract base class for Mouse and Keyboard hooks  
    /// </summary>  
    public abstract class GlobalHook
    {
        #region Windows API Code  
        /// <summary>
        /// 用于控制結構體或類的字段在內存中的布局方式
        /// 具體來說,LayoutKind.Sequential 表示字段將按照它們在源代碼中聲明的順序排列
        /// 結構體字段將按照 x、y 的順序在內存中排列
        /// - Sequential:字段按聲明順序排列,不插入填充字節。
		/// - Explicit:允許開發者精確控制每個字段的存儲位置,使用 FieldOffset 屬性指定偏移量。
		/// - Auto:由編譯器選擇最優布局方式,通常不推薦用于與非托管代碼交互的場景 		 
        /// </summary>
        [StructLayout(LayoutKind.Sequential)]
        protected class POINT
        {
            public int x;
            public int y;
        }
        [StructLayout(LayoutKind.Sequential)]
        protected class MouseHookStruct
        {
            public POINT pt;
            public int hwnd;
            public int wHitTestCode;
            public int dwExtraInfo;
        }
        [StructLayout(LayoutKind.Sequential)]
        protected class MouseLLHookStruct
        {
            public POINT pt;
            public int mouseData;
            public int flags;
            public int time;
            public int dwExtraInfo;
        }
        [StructLayout(LayoutKind.Sequential)]
        protected class KeyboardHookStruct
        {
            public int vkCode;
            public int scanCode;
            public int flags;
            public int time;
            public int dwExtraInfo;
        }
		/// <summary>
		/// CallingConvention屬性指定調用約定,它定義了函數如何接收參數和返回值。常見的調用約定包括:		
		///	- CallingConvention.Cdecl:調用者清理堆棧,多用于C/C++庫。
		///	- CallingConvention.StdCall:被調用者清理堆棧,Windows API常用。
		///	- CallingConvention.ThisCall:用于C++類方法。
		///	- CallingConvention.FastCall:用于快速調用,較少使用。 
		/// CharSet屬性用于指定字符串的字符集,影響字符串的處理和傳遞方式。主要選項有:		
		///	- CharSet.Ansi:將字符串作為ANSI編碼傳遞。
		///	- CharSet.Unicode:將字符串作為Unicode編碼傳遞。
		///	- CharSet.Auto:根據平臺自動選擇ANSI或Unicode。
		/// SetLastError屬性指定是否在調用非托管函數后調用GetLastError。設置為true時,可以使用Marshal.GetLastWin32Error獲取錯誤代碼。
		///
		/// idHook, 指示欲被安裝的掛鉤處理過程之類型
        /// lpfn, 指向相應的掛鉤處理過程.若參數dwThreadId為0或者指示了一個其他進程創建的線程之標識符,則參數lpfn必須指向一個動態鏈接中的掛鉤處理過程.否則,參數lpfn可以指向一個與當前進程相關的代碼中定義的掛鉤處理過程
		/// hMod 指示了一個動態鏈接的句柄,該動態連接庫包含了參數lpfn 所指向的掛鉤處理過程.若參數dwThreadId指示的線程由當前進程創建,并且相應的掛鉤處理過程定義于當前進程相關的代碼中,則參數hMod必須被設置為NULL(0)。
		/// dwThreadId 指示了一個線程標識符,掛鉤處理過程與線程相關.若此參數值為0,則該掛鉤處理過程與所有現存的線程相關。
		///
		/// </summary>
        [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall, SetLastError = true)]
        protected static extern int SetWindowsHookEx(
            int idHook,
            HookProc lpfn, 
            IntPtr hMod,
            int dwThreadId);
        [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall, SetLastError = true)]
        protected static extern int UnhookWindowsHookEx(int idHook);
        [DllImport("user32.dll", CharSet = CharSet.Auto,CallingConvention = CallingConvention.StdCall)]
        protected static extern int CallNextHookEx(
            int idHook,
            int nCode,
            int wParam,
            IntPtr lParam);
        [DllImport("user32")]
        protected static extern int ToAscii(
            int uVirtKey,
            int uScanCode,
            byte[] lpbKeyState,
            byte[] lpwTransKey,
            int fuState);
        [DllImport("user32")]
        protected static extern int GetKeyboardState(byte[] pbKeyState);
        [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
        protected static extern short GetKeyState(int vKey);
        protected delegate int HookProc(int nCode, int wParam, IntPtr lParam);
        protected const int WH_MOUSE_LL = 14; //此掛鉤只能在Windows NT中被安裝,用來對底層的鼠標輸入事件進行監視.詳情參見LowLevelMouseProc掛鉤處理過程.
        protected const int WH_KEYBOARD_LL = 13; //此掛鉤只能在Windows NT中被安裝,用來對底層的鍵盤輸入事件進行監視.詳情參見LowLevelKeyboardProc掛鉤處理過程.
        protected const int WH_MOUSE = 7; //安裝一個掛鉤處理過程,對鼠標消息進行監視. 詳情參見 MouseProc掛鉤處理過程.
        protected const int WH_KEYBOARD = 2; //安裝一個掛鉤處理過程對擊鍵消息進行監視. 詳情參見KeyboardProc掛鉤處理過程.
        protected const int WM_MOUSEMOVE = 0x200;   //鼠標移動
        protected const int WM_LBUTTONDOWN = 0x201; //鼠標左健按下
        protected const int WM_RBUTTONDOWN = 0x204; //鼠標右健按下
        protected const int WM_MBUTTONDOWN = 0x207; //鼠標滾輪按下
        protected const int WM_LBUTTONUP = 0x202;
        protected const int WM_RBUTTONUP = 0x205;
        protected const int WM_MBUTTONUP = 0x208;
        protected const int WM_LBUTTONDBLCLK = 0x203;
        protected const int WM_RBUTTONDBLCLK = 0x206;
        protected const int WM_MBUTTONDBLCLK = 0x209;
        protected const int WM_MOUSEWHEEL = 0x020A;
        protected const int WM_KEYDOWN = 0x100;
        protected const int WM_KEYUP = 0x101;
        protected const int WM_SYSKEYDOWN = 0x104;
        protected const int WM_SYSKEYUP = 0x105;
        protected const byte VK_SHIFT = 0x10;
        protected const byte VK_CAPITAL = 0x14;
        protected const byte VK_NUMLOCK = 0x90;
        protected const byte VK_LSHIFT = 0xA0;
        protected const byte VK_RSHIFT = 0xA1;
        protected const byte VK_LCONTROL = 0xA2;
        protected const byte VK_RCONTROL = 0x3;
        protected const byte VK_LALT = 0xA4;
        protected const byte VK_RALT = 0xA5;
        protected const byte LLKHF_ALTDOWN = 0x20;
        #endregion
        #region Private Variables  
        protected int _hookType;
        protected int _handleToHook;
        protected bool _isStarted;
        protected HookProc _hookCallback;
        #endregion
        #region Properties  
        public bool IsStarted
        {
            get
            {
                return _isStarted;
            }
        }
        #endregion
        #region Constructor  
        public GlobalHook()
        {
            Application.ApplicationExit += new EventHandler(Application_ApplicationExit);
        }
        #endregion
        #region Methods  
		/// <summary>
		/// 啟用鉤子
		///	</summary>	
        public void Start()
        {
            if (!_isStarted &&
                _hookType != 0)
            {
                // Make sure we keep a reference to this delegate!  
                // If not, GC randomly collects it, and a NullReference exception is thrown  
                _hookCallback = new HookProc(HookCallbackProcedure);
                _handleToHook = SetWindowsHookEx(
                    _hookType,
                    _hookCallback,
                    Marshal.GetHINSTANCE(Assembly.GetExecutingAssembly().GetModules()[0]),
                    0);
                // Were we able to sucessfully start hook?  
                if (_handleToHook != 0)
                {
                    _isStarted = true;
                }
            }
        }
        
		/// <summary>
		/// 停止鉤子
		///	</summary>	
        public void Stop()
        {
            if (_isStarted)
            {
                UnhookWindowsHookEx(_handleToHook);
                _isStarted = false;
            }
        }
        protected virtual int HookCallbackProcedure(int nCode, Int32 wParam, IntPtr lParam)
        {
            // This method must be overriden by each extending hook  
            return 0;
        }
        protected void Application_ApplicationExit(object sender, EventArgs e)
        {
            if (_isStarted)
            {
                Stop();
            }
        }
        #endregion
    }
}

KeyboardHook

using System;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace VipSoft.BaseClass.Hook
{
    /// <summary>  
    /// Captures global keyboard events  
    /// </summary>  
    public class KeyboardHook : GlobalHook
    {
        #region Events  
        public event KeyEventHandler KeyDown;
        public event KeyEventHandler KeyUp;
        public event KeyPressEventHandler KeyPress;
        #endregion
        #region Constructor  
        public KeyboardHook()
        {
            _hookType = WH_KEYBOARD_LL;
        }
        #endregion
        #region Methods  
        protected override int HookCallbackProcedure(int nCode, int wParam, IntPtr lParam)
        {
            bool handled = false;
            if (nCode > -1 && (KeyDown != null || KeyUp != null || KeyPress != null))
            {
                KeyboardHookStruct keyboardHookStruct =
                    (KeyboardHookStruct)Marshal.PtrToStructure(lParam, typeof(KeyboardHookStruct));
                // Is Control being held down?  
                bool control = ((GetKeyState(VK_LCONTROL) & 0x80) != 0) ||
                               ((GetKeyState(VK_RCONTROL) & 0x80) != 0);
                // Is Shift being held down?  
                bool shift = ((GetKeyState(VK_LSHIFT) & 0x80) != 0) ||
                             ((GetKeyState(VK_RSHIFT) & 0x80) != 0);
                // Is Alt being held down?  
                bool alt = ((GetKeyState(VK_LALT) & 0x80) != 0) ||
                           ((GetKeyState(VK_RALT) & 0x80) != 0);
                // Is CapsLock on?  
                bool capslock = (GetKeyState(VK_CAPITAL) != 0);
                // Create event using keycode and control/shift/alt values found above  
                KeyEventArgs e = new KeyEventArgs(
                    (Keys)(
                        keyboardHookStruct.vkCode |
                        (control ? (int)Keys.Control : 0) |
                        (shift ? (int)Keys.Shift : 0) |
                        (alt ? (int)Keys.Alt : 0)
                        ));
                // Handle KeyDown and KeyUp events  
                switch (wParam)
                {
                    case WM_KEYDOWN:
                    case WM_SYSKEYDOWN:
                        if (KeyDown != null)
                        {
                            KeyDown(this, e);
                            handled = handled || e.Handled;
                        }
                        break;
                    case WM_KEYUP:
                    case WM_SYSKEYUP:
                        if (KeyUp != null)
                        {
                            KeyUp(this, e);
                            handled = handled || e.Handled;
                        }
                        break;
                }
                // Handle KeyPress event  
                if (wParam == WM_KEYDOWN &&
                   !handled &&
                   !e.SuppressKeyPress &&
                    KeyPress != null)
                {
                    byte[] keyState = new byte[256];
                    byte[] inBuffer = new byte[2];
                    GetKeyboardState(keyState);
                    if (ToAscii(keyboardHookStruct.vkCode,
                              keyboardHookStruct.scanCode,
                              keyState,
                              inBuffer,
                              keyboardHookStruct.flags) == 1)
                    {
                        char key = (char)inBuffer[0];
                        if ((capslock ^ shift) && Char.IsLetter(key))
                            key = Char.ToUpper(key);
                        KeyPressEventArgs e2 = new KeyPressEventArgs(key);
                        KeyPress(this, e2);
                        handled = handled || e.Handled;
                    }
                }
            }
            if (handled)
            {
                return 1;
            }
            else
            {
                return CallNextHookEx(_handleToHook, nCode, wParam, lParam);
            }
        }
        #endregion
    }
}

MouseHook

using System;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace VipSoft.BaseClass.Hook
{
    /// <summary>  
    /// Captures global mouse events  
    /// </summary>  
    public class MouseHook : GlobalHook
    {
        #region MouseEventType Enum  
        private enum MouseEventType
        {
            None,
            MouseDown,
            MouseUp,
            DoubleClick,
            MouseWheel,
            MouseMove
        }
        #endregion
        #region Events  
        public event MouseEventHandler MouseDown;
        public event MouseEventHandler MouseUp;
        public event MouseEventHandler MouseMove;
        public event MouseEventHandler MouseWheel;
        public event EventHandler Click;
        public event EventHandler DoubleClick;
        #endregion
        #region Constructor  
        public MouseHook()
        {
            _hookType = WH_MOUSE_LL;
        }
        #endregion
        #region Methods  
        protected override int HookCallbackProcedure(int nCode, int wParam, IntPtr lParam)
        {
            if (nCode > -1 && (MouseDown != null || MouseUp != null || MouseMove != null))
            {
                MouseLLHookStruct mouseHookStruct =
                    (MouseLLHookStruct)Marshal.PtrToStructure(lParam, typeof(MouseLLHookStruct));
                MouseButtons button = GetButton(wParam);
                MouseEventType eventType = GetEventType(wParam);
                MouseEventArgs e = new MouseEventArgs(
                    button,
                    (eventType == MouseEventType.DoubleClick ? 2 : 1),
                    mouseHookStruct.pt.x,
                    mouseHookStruct.pt.y,
                    (eventType == MouseEventType.MouseWheel ? (short)((mouseHookStruct.mouseData >> 16) & 0xffff) : 0));
                // Prevent multiple Right Click events (this probably happens for popup menus)  
                if (button == MouseButtons.Right && mouseHookStruct.flags != 0)
                {
                    eventType = MouseEventType.None;
                }
                switch (eventType)
                {
                    case MouseEventType.MouseDown:
                        if (MouseDown != null)
                        {
                            MouseDown(this, e);
                        }
                        break;
                    case MouseEventType.MouseUp:
                        if (Click != null)
                        {
                            Click(this, new EventArgs());
                        }
                        if (MouseUp != null)
                        {
                            MouseUp(this, e);
                        }
                        break;
                    case MouseEventType.DoubleClick:
                        if (DoubleClick != null)
                        {
                            DoubleClick(this, new EventArgs());
                        }
                        break;
                    case MouseEventType.MouseWheel:
                        if (MouseWheel != null)
                        {
                            MouseWheel(this, e);
                        }
                        break;
                    case MouseEventType.MouseMove:
                        if (MouseMove != null)
                        {
                            MouseMove(this, e);
                        }
                        break;
                    default:
                        break;
                }
            }
            return CallNextHookEx(_handleToHook, nCode, wParam, lParam);
        }
        private MouseButtons GetButton(Int32 wParam)
        {
            switch (wParam)
            {
                case WM_LBUTTONDOWN:
                case WM_LBUTTONUP:
                case WM_LBUTTONDBLCLK:
                    return MouseButtons.Left;
                case WM_RBUTTONDOWN:
                case WM_RBUTTONUP:
                case WM_RBUTTONDBLCLK:
                    return MouseButtons.Right;
                case WM_MBUTTONDOWN:
                case WM_MBUTTONUP:
                case WM_MBUTTONDBLCLK:
                    return MouseButtons.Middle;
                default:
                    return MouseButtons.None;
            }
        }
        private MouseEventType GetEventType(Int32 wParam)
        {
            switch (wParam)
            {
                case WM_LBUTTONDOWN:
                case WM_RBUTTONDOWN:
                case WM_MBUTTONDOWN:
                    return MouseEventType.MouseDown;
                case WM_LBUTTONUP:
                case WM_RBUTTONUP:
                case WM_MBUTTONUP:
                    return MouseEventType.MouseUp;
                case WM_LBUTTONDBLCLK:
                case WM_RBUTTONDBLCLK:
                case WM_MBUTTONDBLCLK:
                    return MouseEventType.DoubleClick;
                case WM_MOUSEWHEEL:
                    return MouseEventType.MouseWheel;
                case WM_MOUSEMOVE:
                    return MouseEventType.MouseMove;
                default:
                    return MouseEventType.None;
            }
        }
        #endregion
    }
}

KeyboardSimulator

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace VipSoft.BaseClass.Hook
{
    /// <summary>  
    /// Standard Keyboard Shortcuts used by most applications  
    /// </summary>  
    public enum StandardShortcut
    {
        Copy,
        Cut,
        Paste,
        SelectAll,
        Save,
        Open,
        New,
        Close,
        Print
    }
    /// <summary>  
    /// Simulate keyboard key presses  
    /// </summary>  
    public static class KeyboardSimulator
    {
        #region Windows API Code  
        const int KEYEVENTF_EXTENDEDKEY = 0x1;
        const int KEYEVENTF_KEYUP = 0x2;
        [DllImport("user32.dll")]
        static extern void keybd_event(byte key, byte scan, int flags, int extraInfo);
        #endregion
        #region Methods  
        public static void KeyDown(Keys key)
        {
            keybd_event(ParseKey(key), 0, 0, 0);
        }
        public static void KeyUp(Keys key)
        {
            keybd_event(ParseKey(key), 0, KEYEVENTF_KEYUP, 0);
        }
        public static void KeyPress(Keys key)
        {
            KeyDown(key);
            KeyUp(key);
        }
        public static void SimulateStandardShortcut(StandardShortcut shortcut)
        {
            switch (shortcut)
            {
                case StandardShortcut.Copy:
                    KeyDown(Keys.Control);
                    KeyPress(Keys.C);
                    KeyUp(Keys.Control);
                    break;
                case StandardShortcut.Cut:
                    KeyDown(Keys.Control);
                    KeyPress(Keys.X);
                    KeyUp(Keys.Control);
                    break;
                case StandardShortcut.Paste:
                    KeyDown(Keys.Control);
                    KeyPress(Keys.V);
                    KeyUp(Keys.Control);
                    break;
                case StandardShortcut.SelectAll:
                    KeyDown(Keys.Control);
                    KeyPress(Keys.A);
                    KeyUp(Keys.Control);
                    break;
                case StandardShortcut.Save:
                    KeyDown(Keys.Control);
                    KeyPress(Keys.S);
                    KeyUp(Keys.Control);
                    break;
                case StandardShortcut.Open:
                    KeyDown(Keys.Control);
                    KeyPress(Keys.O);
                    KeyUp(Keys.Control);
                    break;
                case StandardShortcut.New:
                    KeyDown(Keys.Control);
                    KeyPress(Keys.N);
                    KeyUp(Keys.Control);
                    break;
                case StandardShortcut.Close:
                    KeyDown(Keys.Alt);
                    KeyPress(Keys.F4);
                    KeyUp(Keys.Alt);
                    break;
                case StandardShortcut.Print:
                    KeyDown(Keys.Control);
                    KeyPress(Keys.P);
                    KeyUp(Keys.Control);
                    break;
            }
        }
        static byte ParseKey(Keys key)
        {
            // Alt, Shift, and Control need to be changed for API function to work with them  
            switch (key)
            {
                case Keys.Alt:
                    return (byte)18;
                case Keys.Control:
                    return (byte)17;
                case Keys.Shift:
                    return (byte)16;
                default:
                    return (byte)key;
            }
        }
        #endregion
    }
}

MouseSimulator

using System;
using System.Text;
using System.Runtime.InteropServices;
using System.Drawing;
using System.Windows.Forms;
namespace VipSoft.BaseClass.Hook
{
    /// <summary>  
    /// And X, Y point on the screen  
    /// </summary>  
    public struct MousePoint
    {
        public MousePoint(Point p)
        {
            X = p.X;
            Y = p.Y;
        }
        public int X;
        public int Y;
        public static implicit operator Point(MousePoint p)
        {
            return new Point(p.X, p.Y);
        }
    }
    /// <summary>  
    /// Mouse buttons that can be pressed  
    /// </summary>  
    public enum MouseButton
    {
        Left = 0x2,
        Right = 0x8,
        Middle = 0x20
    }
    /// <summary>  
    /// Operations that simulate mouse events  
    /// </summary>  
    public static class MouseSimulator
    {
        #region Windows API Code  
        [DllImport("user32.dll")]
        static extern int ShowCursor(bool show);
        [DllImport("user32.dll")]
        static extern void mouse_event(int flags, int dX, int dY, int buttons, int extraInfo);
        const int MOUSEEVENTF_MOVE = 0x1;
        const int MOUSEEVENTF_LEFTDOWN = 0x2;
        const int MOUSEEVENTF_LEFTUP = 0x4;
        const int MOUSEEVENTF_RIGHTDOWN = 0x8;
        const int MOUSEEVENTF_RIGHTUP = 0x10;
        const int MOUSEEVENTF_MIDDLEDOWN = 0x20;
        const int MOUSEEVENTF_MIDDLEUP = 0x40;
        const int MOUSEEVENTF_WHEEL = 0x800;
        const int MOUSEEVENTF_ABSOLUTE = 0x8000;
        #endregion
        #region Properties  
        /// <summary>  
        /// Gets or sets a structure that represents both X and Y mouse coordinates  
        /// </summary>  
        public static MousePoint Position
        {
            get
            {
                return new MousePoint(Cursor.Position);
            }
            set
            {
                Cursor.Position = value;
            }
        }
        /// <summary>  
        /// Gets or sets only the mouse's x coordinate  
        /// </summary>  
        public static int X
        {
            get
            {
                return Cursor.Position.X;
            }
            set
            {
                Cursor.Position = new Point(value, Y);
            }
        }
        /// <summary>  
        /// Gets or sets only the mouse's y coordinate  
        /// </summary>  
        public static int Y
        {
            get
            {
                return Cursor.Position.Y;
            }
            set
            {
                Cursor.Position = new Point(X, value);
            }
        }
        #endregion
        #region Methods  
        /// <summary>  
        /// Press a mouse button down  
        /// </summary>  
        /// <param name="button"></param>  
        public static void MouseDown(MouseButton button)
        {
            mouse_event(((int)button), 0, 0, 0, 0);
        }
        public static void MouseDown(MouseButtons button)
        {
            switch (button)
            {
                case MouseButtons.Left:
                    MouseDown(MouseButton.Left);
                    break;
                case MouseButtons.Middle:
                    MouseDown(MouseButton.Middle);
                    break;
                case MouseButtons.Right:
                    MouseDown(MouseButton.Right);
                    break;
            }
        }
        /// <summary>  
        /// Let a mouse button up  
        /// </summary>  
        /// <param name="button"></param>  
        public static void MouseUp(MouseButton button)
        {
            mouse_event(((int)button) * 2, 0, 0, 0, 0);
        }
        public static void MouseUp(MouseButtons button)
        {
            switch (button)
            {
                case MouseButtons.Left:
                    MouseUp(MouseButton.Left);
                    break;
                case MouseButtons.Middle:
                    MouseUp(MouseButton.Middle);
                    break;
                case MouseButtons.Right:
                    MouseUp(MouseButton.Right);
                    break;
            }
        }
        /// <summary>  
        /// Click a mouse button (down then up)  
        /// </summary>  
        /// <param name="button"></param>  
        public static void Click(MouseButton button)
        {
            MouseDown(button);
            MouseUp(button);
        }
        public static void Click(MouseButtons button)
        {
            switch (button)
            {
                case MouseButtons.Left:
                    Click(MouseButton.Left);
                    break;
                case MouseButtons.Middle:
                    Click(MouseButton.Middle);
                    break;
                case MouseButtons.Right:
                    Click(MouseButton.Right);
                    break;
            }
        }
        /// <summary>  
        /// Double click a mouse button (down then up twice)  
        /// </summary>  
        /// <param name="button"></param>  
        public static void DoubleClick(MouseButton button)
        {
            Click(button);
            Click(button);
        }
        public static void DoubleClick(MouseButtons button)
        {
            switch (button)
            {
                case MouseButtons.Left:
                    DoubleClick(MouseButton.Left);
                    break;
                case MouseButtons.Middle:
                    DoubleClick(MouseButton.Middle);
                    break;
                case MouseButtons.Right:
                    DoubleClick(MouseButton.Right);
                    break;
            }
        }
        /// <summary>  
        /// Show a hidden current on currently application  
        /// </summary>  
        public static void Show()
        {
            ShowCursor(true);
        }
        /// <summary>  
        /// Hide mouse cursor only on current application's forms  
        /// </summary>  
        public static void Hide()
        {
            ShowCursor(false);
        }
        #endregion
    }
}

測試類:

using System;  
using System.Collections.Generic;  
using System.ComponentModel;  
using System.Data;  
using System.Drawing;  
using System.Linq;  
using System.Text;  
using System.Windows.Forms;  
  
using MouseKeyboardLibrary;  
  
namespace SampleApplication  
{  
    /* 
      上面的5個類編譯成Dll引用,使用例子 
     */  
    public partial class HookTestForm : Form  
    {
	    //用于判斷,窗休是否自動關閉
        System.Windows.Forms.Timer mTimer = new System.Windows.Forms.Timer();
		//記錄鼠標鍵盤操作時間,用于判斷 Form 窗體自動關閉
        private DateTime mRecordTime = DateTime.Now; 
        MouseHook mouseHook = new MouseHook();  
        KeyboardHook keyboardHook = new KeyboardHook();  
  
        public HookTestForm()  
        {  
            InitializeComponent();  
        }  
  
        private void TestForm_Load(object sender, EventArgs e)  
        {  
           mTimer.Tick += mTimer_Tick;
           mTimer.Interval = 2000;
           mTimer.Start(); //開啟定時器
				
            mouseHook.MouseMove += new MouseEventHandler(mouseHook_MouseMove);  
            mouseHook.MouseDown += new MouseEventHandler(mouseHook_MouseDown);  
            mouseHook.MouseUp += new MouseEventHandler(mouseHook_MouseUp);  
            mouseHook.MouseWheel += new MouseEventHandler(mouseHook_MouseWheel);  
  
            keyboardHook.KeyDown += new KeyEventHandler(keyboardHook_KeyDown);  
            keyboardHook.KeyUp += new KeyEventHandler(keyboardHook_KeyUp);  
            keyboardHook.KeyPress += new KeyPressEventHandler(keyboardHook_KeyPress);  
  
            mouseHook.Start();  
            keyboardHook.Start();  
  
            SetXYLabel("", MouseSimulator.X.ToString(), MouseSimulator.Y.ToString());
  
        }  
  
        void keyboardHook_KeyPress(object sender, KeyPressEventArgs e)  
        {  
  
            AddKeyboardEvent(  
                "KeyPress",  
                "",  
                e.KeyChar.ToString(),  
                "",  
                "",  
                ""  
                );  
  
        }  
  
        void keyboardHook_KeyUp(object sender, KeyEventArgs e)  
        {  
  
            AddKeyboardEvent(  
                "KeyUp",  
                e.KeyCode.ToString(),  
                "",  
                e.Shift.ToString(),  
                e.Alt.ToString(),  
                e.Control.ToString()  
                );  
  
        }  
  
        void keyboardHook_KeyDown(object sender, KeyEventArgs e)  
        {  
  
  
            AddKeyboardEvent(  
                "KeyDown",  
                e.KeyCode.ToString(),  
                "",  
                e.Shift.ToString(),  
                e.Alt.ToString(),  
                e.Control.ToString()  
                );  
  
        }  
  
        void mouseHook_MouseWheel(object sender, MouseEventArgs e)  
        {  
  
            AddMouseEvent(  
                "MouseWheel",  
                "",  
                "",  
                "",  
                e.Delta.ToString()  
                );  
  
        }  
  
        void mouseHook_MouseUp(object sender, MouseEventArgs e)  
        {  
  
  
            AddMouseEvent(  
                "MouseUp",  
                e.Button.ToString(),  
                e.X.ToString(),  
                e.Y.ToString(),  
                ""  
                );  
  
        }  
  
        void mouseHook_MouseDown(object sender, MouseEventArgs e)  
        {  
  
  
            AddMouseEvent(  
                "MouseDown",  
                e.Button.ToString(),  
                e.X.ToString(),  
                e.Y.ToString(),  
                ""  
                );  
  
  
        }  
  
        void mouseHook_MouseMove(object sender, MouseEventArgs e)  
        {  
            SetXYLabel("", e.X.ToString(), e.Y.ToString());
        }
  
        void SetXYLabel(string keyName, string x, string y)
        {
            this.Text = $"Current keyName={keyName} Point: X={x}, y={y} {DateTime.Now.ToString("HH:mm:ss")}";
            mRecordTime = DateTime.Now;
        }
  
        void AddMouseEvent(string eventType, string button, string x, string y, string delta)  
        {  
  
             //this.Text = $"Current Mouse eventType ={eventType} button ={button} delta ={delta} X ={x}, y ={y}";
             SetXYLabel(button, x, y);
        }  
  
        void AddKeyboardEvent(string eventType, string keyCode, string keyChar, string shift, string alt, string control)  
        {  
  
             //this.Text = $"Current Mouse eventType ={eventType} keyCode ={keyCode} keyChar ={keyChar} shift ={shift}, alt ={alt} control={control}"; 
             SetXYLabel(button, x, y);
        }  
  
        private void TestForm_FormClosed(object sender, FormClosedEventArgs e)  
        {  
  
            // Not necessary anymore, will stop when application exits  
  
            //mouseHook.Stop();  
            //keyboardHook.Stop();  
  
        }  
		
        private bool stopForm = false;  
        //定時器
        private void mTimer_Tick(object sender, EventArgs e)
        {
            if (stopForm)
            {
                return;
            }
            if ((DateTime.Now - mRecordTime).TotalMinutes >= 5) //記錄時間大于5分鐘
            {
                stopForm = true;
                for (int i = Application.OpenForms.Count - 1; i >= 0; i--)
                {
                    Form item = Application.OpenForms[i];
                    if (item.Name != this.Name && item.Name != "UserLogin") //關閉不是主窗體的打開窗體
                    {
                        item.Close();
                    }
                }
                this.WindowState = FormWindowState.Maximized;
                stopForm = false;
            }
        }
    }  
}  



該文章在 2025/1/15 8:49:43 編輯過
關鍵字查詢
相關文章
正在查詢...
點晴ERP是一款針對中小制造業的專業生產管理軟件系統,系統成熟度和易用性得到了國內大量中小企業的青睞。
點晴PMS碼頭管理系統主要針對港口碼頭集裝箱與散貨日常運作、調度、堆場、車隊、財務費用、相關報表等業務管理,結合碼頭的業務特點,圍繞調度、堆場作業而開發的。集技術的先進性、管理的有效性于一體,是物流碼頭及其他港口類企業的高效ERP管理信息系統。
點晴WMS倉儲管理系統提供了貨物產品管理,銷售管理,采購管理,倉儲管理,倉庫管理,保質期管理,貨位管理,庫位管理,生產管理,WMS管理系統,標簽打印,條形碼,二維碼管理,批號管理軟件。
點晴免費OA是一款軟件和通用服務都免費,不限功能、不限時間、不限用戶的免費OA協同辦公管理系統。
Copyright 2010-2025 ClickSun All Rights Reserved

黄频国产免费高清视频,久久不卡精品中文字幕一区,激情五月天AV电影在线观看,欧美国产韩国日本一区二区
在线看片免费人成视频久试看 | 亚洲日韩女同一区二区三区 | 日本午夜福利片在线观看 | 亚洲一线高清在线视频 | 亚洲精品自拍AⅤ在线 | 在线午夜爽爽影院 |