[Winform]經過鉤子監控鍵盤操做和鼠標移動

摘要

有這樣一個需求,在程序隱藏以後,須要監控當前電腦是否有操做,若是1分鐘內,無操做,則彈出視頻,循環播放。函數

解決辦法

從網上找的一個解決辦法,能夠經過鉤子的方式實現,這裏記錄一下。測試

    /// <summary>
    ///監控鍵盤鉤子
    /// </summary>
    public class KeyboardHook
    {
        private const int WM_KEYDOWN = 0x100;
        private const int WM_KEYUP = 0x101;
        private const int WM_SYSKEYDOWN = 0x104;
        private const int WM_SYSKEYUP = 0x105;

        //全局事件  
        public event KeyEventHandler OnKeyDownEvent;
        public event KeyEventHandler OnKeyUpEvent;
        public event KeyPressEventHandler OnKeyPressEvent;

        static int hKeyboardHook = 0;

        //鼠標常量  
        public const int WH_KEYBOARD_LL = 13;

        public delegate int HookProc(int nCode, Int32 wParam, IntPtr lParam);

        //聲明鍵盤鉤子事件類型  
        HookProc KeyboardHookProcedure;

        /// <summary>  
        /// 聲明鍵盤鉤子的封送結構類型  
        /// </summary>  
        [StructLayout(LayoutKind.Sequential)]
        public class KeyboardHookStruct
        {
            public int vkCode;//表示一個1到254間的虛擬鍵盤碼  
            public int scanCode;//表示硬件掃描碼  
            public int flags;
            public int time;
            public int dwExtraInfo;
        }
        [DllImport("kernel32.dll")]
        public static extern IntPtr GetModuleHandle(string lpModuleName);

        //安裝鉤子  
        [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
        public static extern int SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hInstance, int threadId);
        //下一個鉤子  
        [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
        public static extern int CallNextHookEx(int idHook, int nCode, Int32 wParam, IntPtr lParam);
        //卸載鉤子  
        [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
        public static extern bool UnhookWindowsHookEx(int idHook);

        private int KeyboardHookProc(int nCode, Int32 wParam, IntPtr lParam)
        {
            if ((nCode >= 0) && (OnKeyDownEvent != null || OnKeyUpEvent != null || OnKeyPressEvent != null))
            {
                KeyboardHookStruct MyKBHookStruct = (KeyboardHookStruct)Marshal.PtrToStructure(lParam, typeof(KeyboardHookStruct));

                //引起OnKeyDownEvent  
                if (OnKeyDownEvent != null && (wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN))
                {
                    Keys keyData = (Keys)MyKBHookStruct.vkCode;
                    KeyEventArgs e = new KeyEventArgs(keyData);
                    OnKeyDownEvent(this, e);
                }
            }
            return CallNextHookEx(hKeyboardHook, nCode, wParam, lParam);
        }

        public void Start()
        {
            if (hKeyboardHook == 0)
            {
                KeyboardHookProcedure = new HookProc(KeyboardHookProc);
                using (System.Diagnostics.Process curProcess = System.Diagnostics.Process.GetCurrentProcess())
                using (System.Diagnostics.ProcessModule curModule = curProcess.MainModule)
                    hKeyboardHook = SetWindowsHookEx(WH_KEYBOARD_LL, KeyboardHookProcedure, GetModuleHandle(curModule.ModuleName), 0);

                if (hKeyboardHook == 0)
                {
                    Stop();
                    throw new Exception("Set GlobalKeyboardHook failed!");
                }
            }
        }

        public void Stop()
        {
            bool retKeyboard = true;
            if (hKeyboardHook != 0)
            {
                retKeyboard = UnhookWindowsHookEx(hKeyboardHook);
                hKeyboardHook = 0;
            }
            if (!retKeyboard)
                throw new Exception("Unload GlobalKeyboardHook failed!");
        }

        //構造函數中安裝鉤子  
        public KeyboardHook()
        {
        }
        //析構函數中卸載鉤子  
        ~KeyboardHook()
        {
            Stop();
        }
    }
   /// <summary>
    /// 監控鼠標鉤子
    /// </summary>
    public class MouseHook
    {
        private const int WM_MOUSEMOVE = 0x200;
        private const int WM_LBUTTONDOWN = 0x201;
        private const int WM_RBUTTONDOWN = 0x204;
        private const int WM_MBUTTONDOWN = 0x207;
        private const int WM_LBUTTONUP = 0x202;
        private const int WM_RBUTTONUP = 0x205;
        private const int WM_MBUTTONUP = 0x208;
        private const int WM_LBUTTONDBLCLK = 0x203;
        private const int WM_RBUTTONDBLCLK = 0x206;
        private const int WM_MBUTTONDBLCLK = 0x209;

        //全局的事件    
        public event MouseEventHandler OnMouseActivity;

        static int hMouseHook = 0; //鼠標鉤子句柄    

        //鼠標常量    
        public const int WH_MOUSE_LL = 14; //mouse hook constant    

        HookProc MouseHookProcedure; //聲明鼠標鉤子事件類型.    

        //聲明一個Point的封送類型    
        [StructLayout(LayoutKind.Sequential)]
        public class POINT
        {
            public int x;
            public int y;
        }

        //聲明鼠標鉤子的封送結構類型    
        [StructLayout(LayoutKind.Sequential)]
        public class MouseHookStruct
        {
            public POINT pt;
            public int hWnd;
            public int wHitTestCode;
            public int dwExtraInfo;
        }
        [DllImport("kernel32.dll")]
        public static extern IntPtr GetModuleHandle(string lpModuleName);
        //裝置鉤子的函數    
        [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
        public static extern int SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hInstance, int threadId);

        //卸下鉤子的函數    
        [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
        public static extern bool UnhookWindowsHookEx(int idHook);

        //下一個鉤掛的函數    
        [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
        public static extern int CallNextHookEx(int idHook, int nCode, Int32 wParam, IntPtr lParam);

        public delegate int HookProc(int nCode, Int32 wParam, IntPtr lParam);

        /// <summary>    
        /// 墨認的構造函數構造當前類的實例.    
        /// </summary>    
        public MouseHook()
        {
        }

        //析構函數.    
        ~MouseHook()
        {
            Stop();
        }

        public void Start()
        {
            //安裝鼠標鉤子    
            if (hMouseHook == 0)
            {
                //生成一個HookProc的實例.    
                MouseHookProcedure = new HookProc(MouseHookProc);
                using (System.Diagnostics.Process curProcess = System.Diagnostics.Process.GetCurrentProcess())
                using (System.Diagnostics.ProcessModule curModule = curProcess.MainModule)
                    hMouseHook = SetWindowsHookEx(WH_MOUSE_LL, MouseHookProcedure, GetModuleHandle(curModule.ModuleName), 0);

                //若是裝置失敗中止鉤子    
                if (hMouseHook == 0)
                {
                    Stop();
                    throw new Exception("SetWindowsHookEx failed.");
                }
            }
        }

        public void Stop()
        {
            bool retMouse = true;
            if (hMouseHook != 0)
            {
                retMouse = UnhookWindowsHookEx(hMouseHook);
                hMouseHook = 0;
            }

            //若是卸下鉤子失敗    
            if (!(retMouse)) throw new Exception("UnhookWindowsHookEx failed.");
        }

        private int MouseHookProc(int nCode, Int32 wParam, IntPtr lParam)
        {
            //若是正常運行而且用戶要監聽鼠標的消息    
            if ((nCode >= 0) && (OnMouseActivity != null))
            {
                MouseButtons button = MouseButtons.None;
                int clickCount = 0;

                switch (wParam)
                {
                    case WM_LBUTTONDOWN:
                        button = MouseButtons.Left;
                        clickCount = 1;
                        break;
                    case WM_LBUTTONUP:
                        button = MouseButtons.Left;
                        clickCount = 1;
                        break;
                    case WM_LBUTTONDBLCLK:
                        button = MouseButtons.Left;
                        clickCount = 2;
                        break;
                    case WM_RBUTTONDOWN:
                        button = MouseButtons.Right;
                        clickCount = 1;
                        break;
                    case WM_RBUTTONUP:
                        button = MouseButtons.Right;
                        clickCount = 1;
                        break;
                    case WM_RBUTTONDBLCLK:
                        button = MouseButtons.Right;
                        clickCount = 2;
                        break;
                }

                //從回調函數中獲得鼠標的信息    
                MouseHookStruct MyMouseHookStruct = (MouseHookStruct)Marshal.PtrToStructure(lParam, typeof(MouseHookStruct));
                MouseEventArgs e = new MouseEventArgs(button, clickCount, MyMouseHookStruct.pt.x, MyMouseHookStruct.pt.y, 0);

                OnMouseActivity(this, e);
            }
            return CallNextHookEx(hMouseHook, nCode, wParam, lParam);
        }
    }

使用this

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        KeyboardHook key = new KeyboardHook();
        MouseHook mouse = new MouseHook();
        private void Form1_Load(object sender, EventArgs e)
        {
            mouse.OnMouseActivity += mouse_OnMouseActivity;
            key.OnKeyDownEvent += key_OnKeyDownEvent;
            mouse.Start();
            key.Start();
            this.FormClosing += Form1_FormClosing;

        }

        void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            key.Stop();
            mouse.Stop();
        }
        void key_OnKeyDownEvent(object sender, System.Windows.Forms.KeyEventArgs e)
        {
            this.Text = e.KeyData.ToString();
        }

        void mouse_OnMouseActivity(object sender, System.Windows.Forms.MouseEventArgs e)
        {

            this.Text = "X=" + e.X + ",Y=" + e.Y;
        }
    }

測試spa

最小化到任務欄以後.net

原文code

http://blog.csdn.net/gdjlc/article/details/8660191orm

相關文章
相關標籤/搜索