简体   繁体   中英

Changing keyboard events with global hook doesn't work

I am trying to make a little program that installs a global hook and catches keyboard input. For now, I am trying to make every input changed to 'X' for example. So if i write anywhere "hello" it will actually write "XXXXX". I succeeded with hooking and even stopping any input from passing my hook but I can't figure out how to change the input.

The relevant method:

IntPtr HookCallBack(int nCode, IntPtr wParam, IntPtr lParam)
{
        // Trying to change the input.
        Marshal.WriteInt32(lParam, 88);

        // Locked down
        if (isKeyboardLockedDown)
            return new IntPtr(1); // A non-zero return value blocks additional processing of key strokes.
        // Not locked down.
        else
            return NativeMethods.CallNextHookEx(hookId, nCode, wParam, lParam);
 }

As written above - if I understand right - lParam is the address where the input key is stored. Therefor I overwrite it with "X". That method doesn't work for some reason. Any suggestions?

If the input is X:

Invoke CallNextHookEx()

Otherwise

Do not invoke CallNextHookEx(). Instead, call SendInput to post an X.

SendInput

Synthesizes keystrokes, mouse motions, and button clicks.

Note: In general it is unwise not to invoke CallNextHookEx(). Then again, it is in general not wise to replace all input with X :-)

iv'e done a similar project in C. Instead of changing the data i generated input. It works smoothly and not slowing the typing process down. I used a global flag. True for input i generate and false for input from the user. This is pretty much how it looked:

HookProc(int nCode, WPARAM wParam, LPARAM lParam) 
{  
    if(flag){ 
        flag = FALSE; 
        return CallNextHookEx(NULL, nCode, wParam, lParam);}  
    else{ 
        flag = TRUE; 
        keybd_event(what ever you want); 
        return 0;} 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM