本文介绍了SetWindowsHookEx函数在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图钩第三方应用程序,这样我可以绘制到它的屏幕。在屏幕上绘图是容易的,我需要与它没有任何帮助,但我似乎有使用SetWindowsHookEx函数来处理WH_GETMESSAGE问题。我想不出什么来传递最后2个参数。

 使用系统;
使用System.Collections.Generic;
使用System.ComponentModel;
使用System.Data这;
使用System.Drawing中;
使用System.Linq的;
使用System.Text;
使用System.Windows.Forms的;命名空间WindowDrawer
{
    公共部分Form1类:表格
    {
        私人委托INT HOOKPROC(INT code,IntPtr的的wParam,lParam的IntPtr的);
        静态的IntPtr HHOOK;
        IntPtr的windowHandle;
        UINT processHandle;        HOOKPROC PaintHookProcedure;        [System.Runtime.InteropServices.DllImport(user32.dll中,入口点=FindWindow函数,SetLastError = TRUE)]
        静态外部System.IntPtr FindWindowByCaption(INT ZeroOnly,串lpWindowName);        [System.Runtime.InteropServices.DllImport(user32.dll中,入口点=SetWindowsHookEx函数,SetLastError = TRUE)]
        静态外部的IntPtr SetWindowsHookEx函数(INT idHook,HOOKPROC lpfn,IntPtr的HMOD,UINT dwThreadId);        [System.Runtime.InteropServices.DllImport(user32.dll中)]
        静态外部INT CallNextHookEx方法(IntPtr的HHK,INT N code,IntPtr的的wParam,lParam的IntPtr的);        //如果你不想进程ID,用这个重载并传递IntPtr.Zero第二个参数
        [System.Runtime.InteropServices.DllImport(user32.dll中)]
        静态外部UINT GetWindowThreadProcessId(IntPtr的的HWND,UINT出lpdwProcessId);        [System.Runtime.InteropServices.DllImport(KERNEL32.DLL,字符集= System.Runtime.InteropServices.CharSet.Auto)
        公共静态外部的IntPtr的GetModuleHandle(字符串lpModuleName);        公共Form1中()
        {
            的InitializeComponent();
        }        私人无效的button1_Click(对象发件人,EventArgs的发送)
        {            PaintHookProcedure =新HOOKPROC(PaintHookProc);
            windowHandle = FindWindowByCaption(0,无标题 - 记事本);
            UINT主题ID = GetWindowThreadProcessId(windowHandle,出processHandle);
            IntPtr的HMOD = System.Runtime.InteropServices.Marshal.GetHINSTANCE(typeof运算(Form1中).Module);            //这是问题所在。什么赫克我传递到最后2 PARAMS?我得到一个空指针
            HHOOK =调用SetWindowsHookEx(WH_GETMESSAGE,PaintHookProcedure,HMOD,主题ID);
        }        公众诠释PaintHookProc(INT N code,IntPtr的的wParam,lParam中的IntPtr)
        {
           //这里做一些画。
            返回CallNextHookEx方法(HHOOK,N code,的wParam,lParam的);
        }        私人const int的WM_PAINT = 15;
        私人const int的WH_GETMESSAGE = 3;
    }}


解决方案

细节的最后两个参数正是如此:


  • HMOD

  • dwThreadId

I'm not sure you can use a .NET dll in the manner required, but you can certainly try.

Grab hMod via Marshal.GetHINSTANCE(typeof(Form1).Module) and dwThreadId via Process.Threads. Alternatively, set dwThreadId to 0 if you want a global hook (ie. a hook for all GetMessage() calls in the current desktop) but beware of the performance penalties.

这篇关于SetWindowsHookEx函数在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 02:42