现在的位置: 首页 > 综合 > 正文

C# 全局钩子,方法一

2017年11月06日 ⁄ 综合 ⁄ 共 16945字 ⁄ 字号 评论关闭

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Text;
using System.Runtime.InteropServices;
using System.Reflection;

namespace XCommon
{
    public delegate bool CallbackGetMessage(ref XMSG lpMsg, IntPtr hWnd, uint wMsgFilterMin, uint wMsgFilterMax);
    public delegate Int32 CallbackHookProc(int nCode, uint wParam, int lParam);  

    public struct XWin32Msg
    {
        public const int WM_COMMAND = 0x0111;
        public const int WM_ACTIVATEAPP = 0x001C;

  public const int WM_SETTEXT = 0x000C;
  public const int WM_GETTEXT = 0x000D;

        public const int WM_SETFOCUS = 0x0007;
        public const int WM_KILLFOCUS = 0x0008;
        public const int WM_MOUSEFIRST = 0x0200;
        public const int WM_MOUSEMOVE = 0x0200;
        public const int WM_LBUTTONDOWN = 0x0201;
        public const int WM_LBUTTONUP = 0x0202;
        public const int WM_LBUTTONDBLCLK = 0x0203;
        public const int WM_RBUTTONDOWN = 0x0204;
        public const int WM_RBUTTONUP = 0x0205;
        public const int WM_RBUTTONDBLCLK = 0x0206;
        public const int WM_MBUTTONDOWN = 0x0207;
        public const int WM_MBUTTONUP = 0x0208;
        public const int WM_MBUTTONDBLCLK = 0x0209;
        public const int WM_MOUSEWHEEL = 0x020A;
        #region Key Messages
        public const int WM_KEYFIRST                     =0x0100;
        public const int WM_KEYDOWN                      =0x0100;
        public const int WM_KEYUP                        =0x0101;
        public const int WM_CHAR                         =0x0102;
        public const int WM_DEADCHAR                     =0x0103;
        public const int WM_SYSKEYDOWN                   =0x0104;
        public const int WM_SYSKEYUP                     =0x0105;
        public const int WM_SYSCHAR                      =0x0106;
        public const int WM_SYSDEADCHAR                  =0x0107;
        public const int WM_KEYLAST                      =0x0108;
        #endregion
        #region MDI Messages
        public const int WM_MDICREATE                    =0x0220;
        public const int WM_MDIDESTROY                   =0x0221;
        public const int WM_MDIACTIVATE                  =0x0222;
        public const int WM_MDIRESTORE                   =0x0223;
        public const int WM_MDINEXT                      =0x0224;
        public const int WM_MDIMAXIMIZE                  =0x0225;
        public const int WM_MDITILE                      =0x0226;
        public const int WM_MDICASCADE                   =0x0227;
        public const int WM_MDIICONARRANGE               =0x0228;
        public const int WM_MDIGETACTIVE                 =0x0229;
        #endregion

  #region GDI Messages
  public const int WM_SETREDRAW      =0x000B;

  #endregion

  #region Button Message
  public const int BM_CLICK       =0x00F5;

  #endregion

        #region User Button Notification Codes
        public const int BN_CLICKED = 0;

        #endregion

        #region Dialog Box Command IDs
        public const int IDOK               = 1;
        public const int IDCANCEL           = 2;
        public const int IDABORT            = 3;
        public const int IDRETRY            = 4;
        public const int IDIGNORE           = 5;
        public const int IDYES              = 6;
        public const int IDNO               = 7;
        public const int IDCLOSE            = 8;
        public const int IDHELP             = 9;

        #endregion

        #region ShowWindow() Commands
        public const int SW_HIDE = 0;
        public const int SW_SHOWNORMAL = 1;
        public const int SW_NORMAL = 1;
        public const int SW_SHOWMINIMIZED = 2;
        public const int SW_SHOWMAXIMIZED = 3;
        public const int SW_MAXIMIZE = 3;
        public const int SW_SHOWNOACTIVATE = 4;
        public const int SW_SHOW = 5;
        public const int SW_MINIMIZE = 6;
        public const int SW_SHOWMINNOACTIVE = 7;
        public const int SW_SHOWNA = 8;
        public const int SW_RESTORE = 9;
        public const int SW_SHOWDEFAULT = 10;
        public const int SW_FORCEMINIMIZE = 11;
        public const int SW_MAX = 11;

        #endregion

        #region SetWindowHookEx Code
       
        public const int WH_MSGFILTER        =-1;
        public const int WH_JOURNALRECORD    =0;
        public const int WH_JOURNALPLAYBACK  =1;
        public const int WH_KEYBOARD         =2;
        public const int WH_GETMESSAGE       =3;
        public const int WH_CALLWNDPROC      =4;
        public const int WH_CBT              =5;
        public const int WH_SYSMSGFILTER     =6;
        public const int WH_MOUSE            =7;
        public const int WH_HARDWARE         =8;
        public const int WH_DEBUG            =9;
        public const int WH_SHELL            =10;
        public const int WH_FOREGROUNDIDLE   =11        ;
        public const int WH_CALLWNDPROCRET   =12;
        public const int WH_KEYBOARD_LL      =13;
        public const int WH_MOUSE_LL         =14;

        #endregion
                /*
         * 使用正则表达式:查找的内容
         * ^{.*}{\#define}{.*}{0x.*}$
         * 替换的内容
         * \1public const int\3=\4;
         *
         */

  /*
   * Key State Masks for Mouse Messages
   */
  public const int MK_LBUTTON         = 0x0001;
  public const int MK_RBUTTON         = 0x0002;
  public const int MK_SHIFT           = 0x0004;
  public const int MK_CONTROL         = 0x0008;
  public const int MK_MBUTTON   = 0x0010;

    }

    public struct XRasterOperator
    {
        public const int SRCCOPY             =0x00CC0020 ;/* dest = source                   */
        public const int SRCPAINT            =0x00EE0086 ;/* dest = source OR dest           */
        public const int SRCAND              =0x008800C6 ;/* dest = source AND dest          */
        public const int SRCINVERT           =0x00660046 ;/* dest = source XOR dest          */
        public const int SRCERASE            =0x00440328 ;/* dest = source AND (NOT dest )   */
        public const int NOTSRCCOPY          =0x00330008 ;/* dest = (NOT source)             */
        public const int NOTSRCERASE         =0x001100A6 ;/* dest = (NOT src) AND (NOT dest) */
        public const int MERGECOPY           =0x00C000CA ;/* dest = (source AND pattern)     */
        public const int MERGEPAINT          =0x00BB0226 ;/* dest = (NOT source) OR dest     */
        public const int PATCOPY             =0x00F00021 ;/* dest = pattern                  */
        public const int PATPAINT            =0x00FB0A09 ;/* dest = DPSnoo                   */
        public const int PATINVERT           =0x005A0049 ;/* dest = pattern XOR dest         */
        public const int DSTINVERT           =0x00550009 ;/* dest = (NOT dest)               */
        public const int BLACKNESS           =0x00000042 ;/* dest = BLACK                    */
        public const int WHITENESS           =0x00FF0062 ;/* dest = WHITE                    */
    }

    public struct XPOINT
    {
        int  x;
        int  y;
    }

    public struct XMSG
    {
        IntPtr      hwnd;
        uint        message;
        uint        wParam;
        int         lParam;
        uint        time;
        XPOINT      pt;
    }

    /// <summary>
    /// 对Windows API函数调用的封装
    /// </summary>
    public class XWin32API
    {
        public struct RECT
        {
            public int left;
            public int top;
            public int right;
            public int bottom;
            public RECT(int l, int t, int r, int b)
            {
                left = l;
                top = t;
                right = r;
                bottom = b;
            }  // End struct constructor.
        }

        //
        // used for an output LPCTSTR parameter on a method call
        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
        public struct StringBuffer
        {
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
            public string szText;
        }

        /// <summary>
        /// 得到窗体的客户区
        /// </summary>
        /// <param name="hwnd"></param>
        /// <param name="lpRect"></param>
        /// <returns></returns>
        [DllImport("user32.dll")]
        public static extern int GetClientRect(IntPtr hwnd, ref RECT lpRect);
        [DllImport("user32.dll",EntryPoint = "SendMessage")]
        public static extern int SendMessage(IntPtr hwnd, uint wMsg, uint wParam, int lParam);
  [DllImport("user32.dll", EntryPoint = "SendMessage")]
  public static extern bool SendMessageSetText(IntPtr hwnd, uint wMsg, uint wParam, string lParam);
  [DllImport("user32.dll", EntryPoint = "SendMessage")]
  public static extern int SendMessageGetText(IntPtr hwnd, uint wMsg, uint wParam, StringBuilder lParam);

        [DllImport("user32.dll")]
        public static extern int PostMessage(IntPtr hwnd, uint wMsg, uint wParam, int lParam);
        [DllImport("user32.dll")]
        public static extern int PostThreadMessage(uint idThread, uint wMsg, uint wParam, int lParam);
        [DllImport("user32.dll")]
        public static extern int SetForegroundWindow(IntPtr hwnd);
        /// <summary>
        /// 有关按键判断
        /// </summary>
        /// <param name="nVirtKey"></param>
        /// <returns></returns>
        [DllImport("user32.dll")]
        public static extern short GetKeyState(int nVirtKey);

        /// <summary>
        /// 从4字节的DWORD,获得低位的2字节WORD
        /// </summary>
        /// <param name="DWORD"></param>
        /// <returns></returns>
        public static ushort LOWORD(uint DWORD)
        {
            return (ushort)DWORD;
        }
        /// <summary>
        /// 从4字节的DWORD,获得高位的2字节WORD
        /// </summary>
        /// <param name="DWORD"></param>
        /// <returns></returns>
        public static ushort HIWORD(uint DWORD)
        {
            return (ushort)((DWORD >> 16) & 0xFFFF);
        }
        /// <summary>
        /// 从2字节的低位和2字节的高位,组成4字节的DWORD
        /// </summary>
        /// <param name="wLow"></param>
        /// <param name="wHigh"></param>
        /// <returns></returns>
        public static uint MAKELONG(ushort wLow, ushort wHigh)
        {
            return (uint)((wLow) | ((uint)wHigh) << 16);
        }
        /// <summary>
        /// 从1字节的低位和1字节的高位,组成2字节的WORD
        /// </summary>
        /// <param name="bLow"></param>
        /// <param name="bHigh"></param>
        /// <returns></returns>
        public static ushort MAKEWORD(byte bLow, byte bHigh)
        {
            return (ushort)((bLow) | ((ushort)bHigh) << 8);
        }
        /// <summary>
        /// Win32 API函数EnumWindows()的第一个参数的回调函数原型,是一种委托类型
        /// </summary>
        /// <param name="hWnd"></param>
        /// <param name="lParam"></param>
        /// <returns></returns>
        public delegate bool CallbackOfEnumWindows(IntPtr hWnd, int lParam);
        /// <summary>
        /// 枚举窗口
        /// </summary>
        /// <param name="lpEnumFunc"></param>
        /// <param name="lParam"></param>
        /// <returns></returns>
        [DllImport("user32.dll")]
        public static extern int EnumWindows(CallbackOfEnumWindows lpEnumFunc, int lParam);

        [DllImport("user32.dll")]
  public static extern bool IsWindowVisible(IntPtr hWnd);
        [DllImport("user32.dll")]
        public static extern bool IsWindowEnabled(IntPtr hWnd);

        [DllImport("user32.dll")]
  public static extern bool IsWindow(IntPtr hWnd);

        [DllImport("user32.dll")]
  public static extern bool ShowWindow(IntPtr hWnd,int nCmdShow);

        [DllImport("user32.dll")]
        public static extern IntPtr GetFocus();

  [DllImport("user32.dll")]
  public static extern IntPtr GetParent(IntPtr hWnd);

  [DllImport("user32.dll")]
        public static extern IntPtr GetDesktopWindow();

        [DllImport("user32.dll")]
        public static extern int AttachThreadInput(uint idAttach,uint idAttachTo,int fAttach);

        [DllImport("user32.dll")]
        public static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint ProcessId);

        [DllImport("Kernel32.dll")]
        public static extern uint GetCurrentThreadId();
 
        [DllImport("user32.dll")]
        public static extern int GetClassName(IntPtr hWnd, [Out] StringBuilder lpClassName, int nMaxCount);

  [DllImport("user32.DLL")]
  public static extern IntPtr FindWindow(string lpszClass, string lpszWindow);

  [DllImport("user32.dll", EntryPoint = "FindWindowEx")]
        public static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);

        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        public static extern int GetWindowText(IntPtr hWnd, out StringBuffer strWndText, int nMaxCount);
       
  [DllImport("user32.dll", CharSet = CharSet.Auto)]
  public static extern bool InvalidateRect(IntPtr hWnd,ref RECT lpRect,bool bErase);

  [DllImport("user32.dll", CharSet = CharSet.Auto)]
        public static extern bool UpdateWindow(IntPtr hWnd);
        /// <summary>
        /// 取得指定句柄的窗口的Caption字符串
        /// </summary>
        /// <param name="hWnd"></param>
        /// <param name="strWndText"></param>
        /// <returns></returns>
        public static int GetWindowTextX(IntPtr hWnd, out string strWndText)
        {   
            StringBuffer sLimitedString;
            int nLen = GetWindowText(hWnd, out sLimitedString, 256);
            if (nLen > 0)
                strWndText = sLimitedString.szText;
            else
                strWndText = @"";

            return nLen;
        }

        /// <summary>
  /// An application calls SetRedraw to allow a Window's changes to be redrawn or to prevent changes from being redrawn
        /// </summary>
        /// <param name="hWnd"></param>
        /// <param name="bRedraw"></param>
        /// <returns>如果设置成功,返回True</returns>
        public static bool SetRedraw(IntPtr hWnd,bool bRedraw)
        {
   uint wParam = (uint)(bRedraw ? 1 : 0);
   int nResult = XWin32API.SendMessage(hWnd, XWin32Msg.WM_SETREDRAW, wParam, 0);
   return (nResult == 0);
  }

  /// <summary>
  /// 取得指定句柄的窗口的Caption字符串
  /// </summary>
  /// <param name="hWnd"></param>
  /// <param name="strWndText"></param>
  /// <returns></returns>
  public static int GetWindowControlTextX(IntPtr hWnd, out string strWndText)
  {
   /*
            StringBuffer sLimitedString;
            int nLen = GetWindowText(hWnd, out sLimitedString, 256);
            if (nLen > 0)
                strWndText = sLimitedString.szText;
            else
                strWndText = @"";

            return nLen;
   */
   //由于针对不同的进程的窗体控件,不能使用GetWindowText函数,只能使用WM_GETTEXT
   StringBuilder strBuffer = new StringBuilder(1024);
   int nLen = SendMessageGetText(hWnd, XWin32Msg.WM_GETTEXT, 1024, strBuffer);
   strWndText = strBuffer.ToString();
   return nLen;
  }

  [DllImport("user32.dll", CharSet = CharSet.Auto)]
  public static extern bool SetWindowText(IntPtr hWnd, ref StringBuffer strWndText);

  /// <summary>
  /// 设置指定句柄的窗口的Caption字符串
  /// </summary>
  /// <param name="hWnd"></param>
  /// <param name="strWndText"></param>
  /// <param name="bAnotherProcess">是否同一进程</param>
  /// <returns></returns>
  public static bool SetWindowTextX(IntPtr hWnd, string strWndText)
  {
   //由于针对不同的进程的窗体控件,不能使用SetWindowText函数,只能使用WM_SETTEXT,为了统一,都使用WM_SETTEXT这种方法
   return SendMessageSetText(hWnd, XWin32Msg.WM_SETTEXT, 0, strWndText);
  }

        /// <summary>
        /// The BitBlt function performs a bit-block transfer of the color data corresponding to a rectangle of pixels from

        /// the specified source device context into a destination device context.

        /// </summary>
        /// <param name="hdcDest"></param>
        /// <param name="nXDest"></param>
        /// <param name="nYDest"></param>
        /// <param name="nWidth"></param>
        /// <param name="nHeight"></param>
        /// <param name="hdcSrc"></param>
        /// <param name="nXSrc"></param>
        /// <param name="nYSrc"></param>
        /// <param name="dwRop"></param>
        /// <returns></returns>
        [DllImport("gdi32.dll")]
        public static extern bool BitBlt(IntPtr hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, IntPtr hdcSrc, int nXSrc, int nYSrc, int dwRop);

  public const uint PROCESS_VM_OPERATION = 0x0008;
  public const uint PROCESS_VM_READ = 0x0010;
  public const uint PROCESS_VM_WRITE = 0x0020;

  [DllImport("kernel32.dll")]
  public static extern IntPtr OpenProcess(uint dwDesiredAccess,bool bInheritHandle, uint dwProcessId);

  public const uint MEM_COMMIT = 0x1000;
  public const uint MEM_RELEASE = 0x8000;
  public const uint MEM_RESERVE = 0x2000;
  public const uint MEM_DECOMMIT = 0x4000;  

  public const uint PAGE_READWRITE = 4;
       

  [DllImport("kernel32.dll")]
  public static extern IntPtr VirtualAllocEx(IntPtr hProcess, IntPtr lpAddress,uint dwSize, uint flAllocationType, uint flProtect);

  [DllImport("kernel32.dll")]
  public static extern bool VirtualFreeEx(IntPtr hProcess, IntPtr lpAddress,uint dwSize, uint dwFreeType);

  [DllImport("kernel32.dll")]
  public static extern bool CloseHandle(IntPtr handle);

  [DllImport("kernel32.dll")]
  public static extern bool WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress,IntPtr lpBuffer, int nSize, ref uint vNumberOfBytesRead);

  [DllImport("kernel32.dll")]
  public static extern bool ReadProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress,IntPtr lpBuffer, int nSize, ref uint vNumberOfBytesRead);
  [DllImport("kernel32.dll")]
  public static extern IntPtr LoadLibrary(string lpFileName);// ref lpFileName ?
  [DllImport("kernel32.dll")]
  public static extern bool FreeLibrary(IntPtr hModule);
  [DllImport("kernel32.dll")]
  public static extern uint GetProcAddress(IntPtr hModule,string lpProcName);// ref lpProcName ?

        [DllImport("User32.dll")]  
        public   static   extern   IntPtr SetWindowsHookEx(int idHook, CallbackHookProc lpfn, IntPtr hDLL,Int32   dwThreadId);
        [DllImport("User32.dll")]  
        public   static   extern   bool   UnhookWindowsHookEx(IntPtr   hhk);  
        [DllImport("User32.dll")]  
        public   static   extern   int   CallNextHookEx(IntPtr   hhook, int   nCode,uint wParam, int lParam);

        static IntPtr warningHook = IntPtr.Zero;
        public int Function_HookProc(int nCode, uint wParam, int lParam)
        {
            return CallNextHookEx(warningHook,nCode,wParam,lParam);
        }
        // 安装钩子
        public IntPtr Start()
        {
            if (warningHook == IntPtr.Zero)
            {
                IntPtr lockHwnd = Marshal.GetHINSTANCE(Assembly.GetExecutingAssembly().GetModules()[0]);
                warningHook = SetWindowsHookEx(4, new CallbackHookProc(Function_HookProc), lockHwnd, 0);//安装钩子 

            }
            return warningHook;
        }

        // 卸载钩子  
        public bool Stop()
        {
            bool b = false;
            if (warningHook != IntPtr.Zero)
            {
                b = UnhookWindowsHookEx(warningHook);
            }
            return b;
        }

    }
}

抱歉!评论已关闭.