mehmetseckin
mehmetseckin

Reputation: 3117

Redirecting keydown by hook in C#?

I want to write an application like hotkey helpers for games, for example, in Warcraft 3, I use numpad keys for some reason. Is it possible to send a "Numpad 1 key pressed" message to the OS by pressing the "X" key? I've been trying to do this using hooks but I couldn't figure out. I hope I was clear.

I've used this class for hooks: Global System Hooks in .NET.

Simply my code is like this:

globalKeyboardHook hook = new globalKeyboardHook(); // A Global Hook

private void btnHook_Click(object sender, EventArgs e)
{
    hook.hook(); // Set the hook
    hook.HookedKeys.Add(Keys.X); // Hook the X key
    // i removed other hooks purify the code, six hooks total.
    hook.KeyDown += new KeyEventHandler(hook_KeyDown); // add eventhandler
    Program.hookActive = true; // inform the program that hook is active.
    Guncelle(); // update form components (buttons enabling/disabling according to hook status etc.)
}

private void hook_KeyDown(object sender, KeyEventArgs e)
{
    KeyEventArgs k = new KeyEventArgs(Keys.NoName);
    switch (e.KeyCode)
    {
        case Keys.X:
            k = new KeyEventArgs(Keys.NumPad1);
            OnKeyDown(k);
            break;
            // i removed other cases to purify the code, six cases total.
    }
}

Upvotes: 2

Views: 734

Answers (1)

foxy
foxy

Reputation: 7672

Yes, you can use the WinAPI SendInput() or keyb_event() calls. For example:

keybd_event(VK_NUMPAD1, 0, 0, 0)

Upvotes: 2

Related Questions