Hooking problem...

T

TMP

Below is the code snippet that I'm having problems with, the hook seems to
work (hookResult returns a value other than zero) but then explorer
crashes.Also I'm aware of the fact that instead of specifying a dll with my
hook function embedded, I used my executable's module HINSTANCE. But I guess
no problem there since it works with different hook types.So can anyone
explain why explorer keeps crashing? (on Windows XP Professional) Thanks in
advance.

....

{


IntPtr taskBarHandle = IntPtr.Zero;

taskBarHandle = API.FindWindow("Shell_TrayWnd", null);

API.HOOKPROC msgHookProc = new TMP.WinXP.API.HOOKPROC(MsgHookProc);

GCHandle gcHandle = GCHandle.Alloc(msgHookProc, GCHandleType.Normal);


uint threadId = 0;

uint processId = 0;

threadId = API.GetWindowThreadProcessId(taskBarHandle, out processId);



if(threadId != 0)

hookResult = API.SetWindowsHookEx(API.WH_GETMESSAGE,
msgHookProc,Marshal.GetHINSTANCE((typeof(Form1).Module)), threadId);

Console.WriteLine("Hook Result = " + hookResult.ToString());

}

....

private IntPtr MsgHookProc(int nCode, IntPtr wParam, IntPtr lParam)

{

if(nCode < 0 )

return API.CallNextHookEx(hookResult, nCode, wParam, lParam);


API.MSG message = (API.MSG) Marshal.PtrToStructure(lParam, typeof(API.MSG));

MessageBox.Show(message.pt.x.ToString());


return API.CallNextHookEx(hookResult, nCode, wParam, lParam);

}
 
S

Stoitcho Goutsev \(100\) [C# MVP]

Hi TMP,

You are trying to install a hook to a thread which is not created by your
process. In this case your hook procedure has to be in a DLL because what
windows does is to inject that dll to the target process (like a code
executed in the target thread calls LoadLibrary). The problem is that
unmanaged code cannot load and use managed DLL that's why such a hooks are
not possible using .NET. With managed code you can only hook your own
process.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top