[英]Retrieve process- or thread-id of global keypress using SetWindowsHookEx
[英]SetWindowsHookEx doesn't work with thread Id
您好,在此先感謝任何嘗試提供幫助的人。 我正在嘗試設置一個CBT Windows掛鈎,當我在全局設置它時,它會很好地工作,但是當我嘗試將其附加到單個線程時會失敗。 據我所知,我通過本書來做所有事情:-我從非托管dll暴露了鈎子程序-我的應用程序,dll和線程的進程都是32位-我使用的線程ID是正確的(與spy ++確認)
當我嘗試從C ++代碼中僅掛接一個線程時,我設法做到了...您可以僅從非托管代碼中掛接單個線程嗎?
無論如何這是我的代碼:
[DllImport( "user32.dll", SetLastError = true )]
static extern IntPtr SetWindowsHookEx ( int hookType, UIntPtr lpfn, IntPtr hMod, uint dwThreadId );
[DllImport( "kernel32", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true )]
public static extern UIntPtr GetProcAddress ( IntPtr hModule, string procName );
[DllImport( "kernel32", SetLastError = true, CharSet = CharSet.Unicode )]
public static extern IntPtr LoadLibrary ( string libraryName );
const int WH_CBT = 5;
void SetHook ()
{
IntPtr dll = LoadLibrary( LIBRARY );
UIntPtr proc = GetProcAddress( dll, PROC );
uint threadId = GetAppWindowThreadId();
//assume that the threadId of the external window is correct, as I said I verified with spy++
//and assume that dll and proc both get correct values
IntPtr hookAddress = SetWindowsHookEx( WH_CBT , proc, dll, threadId );
//hookAddress is 0
}
[DllImport( "user32.dll", SetLastError = true )]
static extern IntPtr SetWindowsHookEx ( int hookType, UIntPtr lpfn,
IntPtr hMod, ulong dwThreadId );
該聲明是錯誤的。 最后一個參數(dwThreadId)的類型為DWORD,C#中的uint。
奇怪的是,您沒有收到有關此的PInvokeStackImbalance調試器警告。 這表明您正在64位操作系統上運行。 這就增加了其他幾種故障模式,注入的DLL必須包含未經編譯的代碼,這些代碼必須已編譯為正確的進程和要掛接的進程的正確位。 根據需要設置項目的平台目標。 您的代碼缺少所有錯誤檢查,因此您將不知道為什么它不起作用,請確保在收到失敗返回代碼時拋出新的Win32Exception()。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.