我正在尝试将程序中的 Windows Hook 设置为外部 EXE。这将用于监 window 口的大小调整/最小化,因此我可以类似地调整程序大小,停靠到窗口。
如何解决下面的错误代码 1428 和 126?
当使用 null hMod 调用 SetWindowsHookEx 时,我收到此错误 1428。如果传递当前模块(而不是 IntPtr.Zero),我会得到相同的错误,这似乎是正确的,如下所示:
IntPtr module = PInvoke.GetModuleHandle(null);
[...]
SetWindowsHookEx(...,...,module,...);
int error = PInvoke.GetLastError();
1428 = 在没有模块句柄的情况下无法设置非本地钩子(Hook)
我还尝试使用GetModuleHandle来获取我作为模块 Hook 的外部程序:
IntPtr module = PInvoke.GetModuleHandle("communicator.exe");
int error = PInvoke.GetLastError();
但是错误随后设置为:
126 = 找不到指定的模块。
我正在使用以下 PInvoke 语句:
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern IntPtr GetModuleHandle(string lpModuleName);
[DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr SetWindowsHookEx(HookType hookType, HookProc lpfn, IntPtr hMod, uint dwThreadId);
这是出现问题的过程:
public void Install(IntPtr hWnd)
{
uint threadId;
uint processId;
if (hWnd == IntPtr.Zero)
{
threadId = (uint)AppDomain.GetCurrentThreadId();
throw new Exception("Lync thread not found!");
}
else
{
threadId = PInvoke.GetWindowThreadProcessId(hWnd, out processId);
}
//IntPtr module = PInvoke.GetModuleHandle(null);
//IntPtr module = PInvoke.GetModuleHandle(GetType().Module.FullyQualifiedName);
IntPtr module = PInvoke.GetModuleHandle("communicator.exe");
int error = PInvoke.GetLastError();
m_hhook = PInvoke.SetWindowsHookEx(
m_hookType,
m_filterFunc,
//Process.GetCurrentProcess().Handle,
//threadId);
//IntPtr.Zero,
//module,
//Marshal.GetHINSTANCE(
// System.Reflection.Assembly.GetExecutingAssembly().GetModules()[0]
// ).ToInt32()
module,
threadId);
//IntPtr hinst = Marshal.GetHINSTANCE(Process.GetCurrentProcess().Handle);
// http://msdn.microsoft.com/en-us/library/ms681385
// ERROR_HOOK_NEEDS_HMOD - 1428 = Cannot set nonlocal hook without a module handle
error = PInvoke.GetLastError();
}
最佳答案
您不能使用GetModuleHandle对于外部进程。它必须是已加载到当前进程中的模块。
关于c# - PInvoke 调用外部 SetWindowsHookEx 和 GetModuleHandle 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7774509/