It logs the keys to textbox currently so its safe.
PROBLEM The problem is when i run this at virtual machine, or my friends laptop, it hangs after pressing certain a
Try debugging your application with the "CallbackOnCollectedDelegate" MDA turned on (Debug -> Exceptions -> Managed Debugging Assistants -> check "CallbackOnCollectedDelegate").
The common bug here is that the delegate for your hook procedure is automatically collected by the GC after you set the hook (it gets created as part of the P/Invoke marshaling to SetWindowsHookEx
). After the GC collects the delegate, the program crashes when trying to call the callback. This would also explain the randomness.
If this is your issue, you'll see an error like the following:
A callback was made on a garbage collected delegate of type '...'. This may cause application crashes, corruption and data loss. When passing delegates to unmanaged code, they must be kept alive by the managed application until it is guaranteed that they will never be called.
Try keeping a reference to your hook procedure as a member in your class, e.g.:
public delegate int KeyboardHookProc(int nCode, int wParam, ref GlobalKeyboardHookStruct lParam);
public int hookProc(int nCode, int wParam, ref GlobalKeyboardHookStruct lParam)
{
// ...
}
public void hook()
{
_hookProc = new KeyboardHookProc(hookProc);
IntPtr hInstance = LoadLibrary("user32");
hookHandle = SetWindowsHookEx(WH_KEYBOARD_LL, _hookProc, hInstance, 0);
}
KeyboardHookProc _hookProc;