What does GetModuleHandle() do in this code? - c#

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 :)

Related

Using c# to call a function from another process

I'm creating a memory modifying program for my own learning purposes. A friend of mine pointed out a function in another program that I want to trigger.
The function is at 0x004B459C in the other program. I know how to read and write memory, but how can I trigger this function from my program. I do not have the source to this other program.
My question is do I need to inject the function if I know this hex code, or do I just write something to memory to trigger this?
Think a bit about what you really want. You want the other process to execute this function. Processes don't execute code, it's threads that execute code. If you want the other process to call this function as a part of it's normal operations, you will have to figure out inputs etc. which will make one of the other process's threads call it. Generally speaking, any other way you will be running the risk of corrupting the other process. It is possible to inject a thread into another process and have it call the function you're interested in (see CreateRemoteThread). If this function is intended to be called on the message pump thread, you could inject a message hook into the other process, send it a special message and call it from your hook. There are a few more ways (APC) but these are still more complicated for little gain.
you are missing some basic architecture fundamentals :-) you cannot simply call a function knowing its address from another process! think of it, this means that your program can get the memory of any program and execute code! this will be a mess and a complete insecure environment. first some basics:
1) windows guarantees that you only see the memory of your own process, one of the most important principles of an OS (even Windows) is to isolate processes including their memory of course.
2) did think about permissions, usually any code that runs must run under a user account, another process might mean another process account.
the answer is simple, if your program is .NET/C# then check what the .NET framework provides you for inter process communication, this is the thing you must search for, every platform, Java, windows native, .NET provides an offical way how process communicate with each other, it is called interprocess communication, check it in .NET framework

Why use LoadLibrary instead of just getting BaseAddress of your program

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.

SetWindowsHookEx(WH_KEYBOARD) only yields first event, sequential events

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...

Respond to keyboard when not in focus? (C#, Vista)

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

Find the Current Windows Application

I'm trying to write what I hope is a simple application tracker. That is, whenever a new application starts, or a running application becomes current, I want to note the event and start timing it's time "on top".
I have code that lists all the current applications that are running, and some code that tells me the top window (always my test console app, naturally).
What I think I'm missing is the Windows event stream to monitor or something.
I'm using .NET (C# preferred).
Any hints, tips or cheats available?
Thanks - Jonathan
I think the best way to do this would be using windows "hooks" (i.e. SetWindowsHookEx). These allow you to hook in to windows core functionality, specifically there is one called WH_CALLWNDPROC which calls a user function any time any window in the system receives a message.
You could use this to globally listen for messages that bring a window to the foreground, and/or messages for user interaction (mouse, keyboard).
However, this is a raw Windows API function primarily meant for use in a C/C++ windows DLL. You can implement it in C#, but that is a can of worms you may not want to open. But opening it would probably be the best way of doing what you're asking.
I'm not sure if there's a way to hook a Windows event, but simply polling System.Diagnostics.Process.GetProcesses() at regular intervals (say, 100ms) and looking for new/removed processes (comparing by process ID) should do the job. Also, Process.StartTime will give you the time at which the process began.
Caveat: This method may be require a higher amount of processing compare an event-based method (none of which I am aware). Processes that start and end between each poll will not be observed, but this ought to be quite rare indeed for a reasonably high polling frequency (and perhaps you do not even care about these processes anyway). Saying this, these are minor detractions, and I would recommend you at least test this solution as it is fairly simple.
This is increasingly a SO problem, the down-voted answer is the correct one. SetWindowsHookEx() is indeed required to be able to catch the WM_ACTIVATE message that the activated window gets. But that requires a WH_CALLWNDPROC or WH_SHELL hook, hooks that cannot be implemented in C#. Catching those requires injecting a DLL in every process, a managed assembly cannot be injected into another process. The CLR cannot be initialized.
+1 for Noldorin to get him back to 0, that's all I can do. The OP needs to write his code in unmanaged C/C++, creating a DLL and use a standard IPC mechanism like pipes or sockets to notify the host app. Or poll, much easier.
I once wrote a small app that did this to keep track of my own work habits. What I did was call GetForegroundWindow() periodically (every 5 seconds or something) and noted the application that is running. You can get a lot of information from the window handle, not just the title but all the way down to the actual process that created it.
This is what I did using Java's JNA:
final HWND child = User32Ext.INSTANCE.GetForegroundWindow();
final int length = User32.INSTANCE.GetWindowTextLength(child) * 2;
final byte[] buffer = new byte[length];
User32.INSTANCE.GetWindowText(child, buffer, length);
title = new String(buffer, Charset.forName("UTF-16LE"));
where User32Ext is an extension I did because User32 (in JNA's distribution) doesn't have the interface for:
LRESULT callback(int nCode, WPARAM wParam, LPARAM lParam);
I'm periodically polling the active window, since I couldn't use the HCBT_SETFOCUS hook as mentioned in http://msdn.microsoft.com/en-us/library/ms997537.aspx, and I'll be very interested if someone comes up with the solution.

Categories

Resources