From a .net application I wish to capture all keyboard events, globally.
I set a callback using a win32-method SetWindowsHookEx(WH_KEYBOARD, HINSTANCE). (Using dllimport and some mashall-call.)
One the first key is pressed I get a nice response saying which key is pressed.
My callback-function calls CallNextHookEx as is should do.
But after the first event I get no more events.
Any-one has any idea of common causes for events to stop coming?
WH_KEYBOARD is not supported from a managed wrapper, it needs to inject itself into the process.
You can use WH_KEYBOARD_LL which will be called in the declaring thread.
see: http://support.microsoft.com/kb/318804
Global hooks are not supported in the
.NET Framework Except for the
WH_KEYBOARD_LL low-level hook and the
WH_MOUSE_LL low-level hook, you cannot
implement global hooks in the
Microsoft .NET Framework. To install a
global hook, a hook must have a native
DLL export to inject itself in another
process that requires a valid,
consistent function to call into. This
behavior requires a DLL export. The
.NET Framework does not support DLL
exports. Managed code has no concept
of a consistent value for a function
pointer because these function
pointers are proxies that are built
dynamically.
Low-level hook procedures are called
on the thread that installed the hook.
Low-level hooks do not require that
the hook procedure be implemented in a
DLL.
If your hook callback function takes too long to return, windows will stop calling it to preserve system performance. Try just a simple call to OutputDebugString and CallNextHookEx and see if that helps...
Related
subjective...HA
ok so i've been looking around the internetz for a reasonable solution to trapping multiple keystrokes and came accross a few solutions that use the same thing (keyboard hook). One soltuion used a native call to get the IntPtr of a process by name, and the other used LoadLibrary("User32.dll")
so i figured I would be "smart" and did this (with success)
IntPtr hInstance = Process.GetCurrentProcess().MainModule.BaseAddress;
callbackDelegate = new HOOKPROC(HookCallback);
hhook = SetWindowsHookEx(WH_KEYBOARD_LL, callbackDelegate, hInstance, 0);
as apposed to using this
IntPtr hInstance = LoadLibrary("User32.dll");
callbackDelegate = new HOOKPROC(HookCallback);
hhook = SetWindowsHookEx(WH_KEYBOARD_LL, callbackDelegate, hInstance, 0);
is one safer than the other? am I making a fatal error that isn't showing it's head?
SetWindowsHookEx() requires a valid module handle. It uses it to figure out what DLL needs to be injected into other processes to make the hook work.
But that's only a requirement for global hooks. The two low-level hooks (WH_MOUSE_LL and WM_KEYBOARD_LL) are special, they don't require DLL injection. Windows calls the hook callback in your own process only. The sole requirement is that your thread pumps a message loop so that Windows can make the callback. Application.Run() is required.
Also the reason that you can make low-level hooks work in C#, the DLL used by global hooks cannot be written in a managed language because the injected process will not have the CLR loaded.
The quirk is that SetWindowsHookEx() checks if you passed a valid module handle but then doesn't actually use it for the low-level hooks. So any valid handle you pass will work. This quirk was fixed in Windows 7 SP1 btw, it no longer performs that check.
EDIT: My original answer left the IntPtr.Zero option open, and gave the neccesary information to help you decide. I'm adding another quote from the docs, which discusses when not to use null:
An error may occur if the hMod parameter is NULL and the dwThreadId
parameter is zero or specifies the identifier of a thread created by
another process.
Since you're using 0 as the thread id (which means "all existing threads running in the same desktop as the calling thread", as per the docs), you should NOT be using null but Marshal.GetHINSTANCE instead.
I think you should be passing either IntPtr.Zero or Marshal.GetHINSTANCE(your current module)
According to these docs, the third argument (hMod) is -
A handle to the DLL containing the hook procedure pointed to by the
lpfn parameter. The hMod parameter must be set to NULL if the
dwThreadId parameter specifies a thread created by the current process
and if the hook procedure is within the code associated with the
current process.
Also as mentioned in this article ("Windows Hooks in the .NET Framework"),
The third argument should be the HINSTANCE handle of the DLL that contains the code for the filter function. Typically, this value is set to NULL for local hooks. Do not use the .NET null object, though; use the IntPtr.Zero expression, which is the correct counterpart for Win32 null handles. The HINSTANCE argument cannot be null for systemwide hooks, but must relate to the module that contains the hook code—typically an assembly. The Marshal.GetHINSTANCE static method will return the HINSTANCE for the specified .NET module.
Also, see this question.
I'm writing code that is part of an automation system. I wanted to add a keyboard hook to end the test prematurely, and I did this by using SetWindowHookEx.
My code looks pretty much like this: http://support.microsoft.com/kb/318804
Here's my SetWindowsHookEx call:
hHook = SetWindowsHookEx(WH_KEYBOARD_LL, KeyboardHookProcedure, GetModuleHandle(Process.GetCurrentProcess().MainModule.ModuleName), 0);
Now, when I run my automation, keypresses from within the automation system (from SendKeys) trigger the keyboard hook method, but when I hit the keyboard manually it isn't triggered.
I can share more code if that helps, but it's part of a much larger system. I'm pretty sure that either:
My SetWindowsHookEx isn't correct, or
Something in the automation system is bypassing my keyboard hook (I don't really know how to tell though).
I've written a test application that uses the sample code from microsoft.com to determine that my approach has merit (i.e., it works), but I'm having trouble integrating it with the automation system.
Any thoughts on how to determine where things are going wrong would be greatly appreciated.
Edit: There are no other instances of SetWindowsHookEx in the automation harness. I'm not too clear the nuances of global keyboard hooks w.r.t. threads and the desktop. If I add a global keyboard hook, should it matter from where it was added?
George Mamaladze's article Processing Global Mouse and Keyboard Hooks in C# which works if the application is "in the background" on CodeProject has been around since 2004, been through multiple revisions, and he's still supporting it and updating it : as I understand it, he started his project because he could not implement global hooks in .NET, that worked when the app was running in the background, but later discovered you could hook certain "lower level" events : formerly Q318804 : now MSDN article revised (?) that says you can hook WH_KEYBOARD_LL.
Perhaps, since George's code has been field-tested by so many C# programmers, over so many years, and extensively revised against bugs or problems : there's some possible value in his code for you ? In his article, in the Version 1 "FAQ" he shows code that will make the hook application specific, rather than global.
The MSDN article cited above mentions ... in the context of the allowed hooking of low level events, as you are doing :
"Low-level hook procedures are called
on the thread that installed the hook.
Low-level hooks do not require that
the hook procedure be implemented in a
DLL."
Hypothesis : could threading be related to what you are observing ?
I'm assuming you've already been through and considered all the details on : MSDN : LowLevelKeyboardProc Function
Responding to your comment -
If you just need to test whether a key is down in order to exit your test, you could just poll on GetAsyncKeyState(), this will tell you if a particular key is down regardless of who currently has keyboard focus.
You user would have to hold a key or set of keys down long enough for your polling to notice, which means either they hold it down for a few seconds, or you have to poll more frequently than a second.
But that would be a lot less intrusive than a global keyboard hook.
Global hooks supposedly serialize parts of the kernel that normally would be async from each other, so they also harm system performance.
Edited........
sorry Sir I was referring this piece of code from Stephen Toub's article..
private static IntPtr SetHook(LowLevelKeyboardProc proc)
{
using (Process curProcess = Process.GetCurrentProcess())
using (ProcessModule curModule = curProcess.MainModule)
{
return SetWindowsHookEx(WH_KEYBOARD_LL, proc,
GetModuleHandle(curModule.ModuleName), 0);
}
}
Can some one explain this to me in short...??
In short this code initializes a key logger. The passed in parmeter, proc, is a callback function that will be called on every key press.
The using statement just ensures immediate calls to dispose() on the declared variables (curProcess and curModule) when they leave scope, thus properly releasing resources in a expedient manner rather than waiting for the garbage collector to release them which may take a while.
SetWindowsHookEx is a win32 api call that allows you to register a callback to be called when a specific OS level event occurs. In this case the first parameter, WH_KEYBOARD_LL, specifies that you would like to register for low level keyboard events. The second parameter is the callback (a Delegate in .Net) that will be called. The third parameter is a windows handle (a pointer managed by the OS) to the module where the callback is located, in this case the main .exe for the process. Note that a process has multiple modules (exe's or dll's) loaded at any given time. The last parameter is the thread id that you would like to monitor; because 0 is passed in, the callback will be called for any key events for any window opened on the OS.
More info here about SetWindowsHookEx
GetModuleHandle() is a Windows API which in simple word returns you the handle of the loaded DLL or EXE.
You can see the detailed description of this API at this link
Straight From MSDN:
The GetModuleHandle function returns a handle to a mapped module without incrementing its reference count. Therefore, use care when passing the handle to the FreeLibrary function, because doing so can cause a DLL module to be unmapped prematurely.
This function must be used carefully in a multithreaded application. There is no guarantee that the module handle remains valid between the time this function returns the handle and the time it is used. For example, a thread retrieves a module handle, but before it uses the handle, a second thread frees the module. If the system loads another module, it could reuse the module handle that was recently freed. Therefore, first thread would have a handle to a module different than the one intended.
First as a general point for questions on Windows library functions, you should consider searching MSDN. Here is the MSDN page for GetModuleHandle(), it contains much of the relevant information.
To your question (and anyone more familiar with the Windows API feel free to correct me), a "module" is a sort of catch-all term for a program in Windows, usually specifically referring to either an executable(.exe) or a library(.dll). A "handle" is a term referring to a pointer. GetModuleHandle() returns a pointer (handle) to the specific program (module). As Pavel commented, both are very broad terms.
As for the code snippet you posted:
It's getting the current running process, as well as the current module (obvious.)
It is then calling SetWindowsHookEx (refer to the MSDN for more information) which takes in the event to hook (In this case, low level Keyboard events.), a procedure to call (proc) when the hooked event happens, and a pointer to the current program.
Refer to Hooks on the MSDN for more information on hooking.
Essentially the message of this post is make more use of the MSDN, it's a pretty solid piece of documentation :)
i want to write a C# lib, or a reference service,
so that if a application reference my lib, and when the application runs,
the function in my function can be run without any invoked?
for example, i got a lib, keep reading the memory usage of the platform,
when the memory was up to 80%, i pop up a message to the user, it is time to close the application.
so..when i create a another application, and want my new application has the mem check feature, i just need to reference it then after my new application run, the mem check will be fired together..
so..how can i do these?
Create a static constructor for your class - this constructor will be run once, and only once, the first time the host application references anything related to your class.
You could create a thread to run some background checking process, hook into an event of the Application object, or whatever you need.
Note however, that you'll need to do more than just add a project reference to your assembly - an assembly is only loaded into an App Domain when something in that assembly is referenced by existing code.
The term you're looking for is "Win32 application hook." There's a decent introduction to managed hook injection here: http://msdn.microsoft.com/en-us/magazine/cc188966.aspx
I'm not sure you can monitor system memory consumption with an application hook, though. And unfortunately, you cannot write a global hook in managed code because global hooks require a well-defined entry point (a DLL export). This is really something best suited for C++.
It is possible to create traditional DLL exports in an assembly (via ILASM or the now defunct Delphi.NET) but not really recommended. (search for reverse p/invoke)
Another approach is to create a C++/CLI intermediate dll to call your managed code. But to be perfectly honest, I reckon you are simply better off just creating a native DLL with C++ or Delphi.
Edit:
Ok, firstly a disclaimer, I work for Quest Software (the company that makes this tool that I am about to plug). That said...
OS Monitoring is actually not as straight forward as you might think, things like memory consumption, process monitoring etc is...well, pernickety. You may find that somthing like Spotlight on Windows (Freeware for first 10 licences) would suit your purpose ?
I'm trying to write an application that responds whenever the Shift key is pressed, no matter what application currently has focus.
I tried this with SetWindowsHookEx() and with GetKeyboardState(), but both of these only work when the application's window has focus. I need it to work globally.
How do I do this?
None of the provided answers helped me solve my problem, but I found the answer myself. Here it is.
Using SetWindowsHookEx() with WH_KEYBOARD_LL was the correct approach. However, the other parameters to SetWindowsHookEx() are unintuitive:
The last parameter, dwThreadId, needs to be 0.
The second-last parameter, hMod, needs to point to some DLL. I used
User32, which is a DLL that is always loaded anyway and is used by all
processes with a GUI. I got this idea from a CodeProject post about this.
Thus, the code looks a bit like this:
instance = LoadLibrary("User32");
hhook = SetWindowsHookEx(WH_KEYBOARD_LL, hookFunction, instance, 0);
The documentation is unclear about the second-last parameter. It says:
The hMod parameter must be set to NULL [...] if the hook procedure is within the code associated with the current process.
It doesn't state that this only applies to some types of hooks, but not to WH_KEYBOARD_LL and WH_MOUSE_LL.
You'll have to use SetWindowsHookEx(). There are only two types of hooks that you can implement in a managed language, WH_KEYBOARD_LL and WH_MOUSE_LL. All other hooks require a DLL that can be injected into another process. Managed DLLs cannot be injected, the CLR cannot be initialized.
This blog post has a functional example.
If you use the technique in the post referenced by nobugz, you will need to make sure the delegate doesn't get garbage-collected, e.g. by using GC.KeepAlive(_proc) when setting the hook, otherwise after an indeterminate period the hook will stop working when the delagate gets GCed.
Setup a CBT hook look here http://www.codeproject.com/KB/DLL/keyboardhook.aspx