C# hold key in a game application

10,853

Solution 1

I did it with Windown API and SendInput method.

Solution 2

"Hold key A for 150ms, Hold left arrow for 500ms"

See if this works:

        Keyboard.HoldKey((byte)Keys.A, 150);
        Keyboard.HoldKey((byte)Keys.Left, 500);

Using:

public class Keyboard
{
    [DllImport("user32.dll", SetLastError = true)]
    static extern void keybd_event(byte bVk, byte bScan, int dwFlags, int dwExtraInfo);

    const int KEY_DOWN_EVENT = 0x0001; //Key down flag
    const int KEY_UP_EVENT = 0x0002; //Key up flag

    public static void HoldKey(byte key, int duration)
    {
        int totalDuration = 0;
        while (totalDuration < duration)
        {
            keybd_event(key, 0, KEY_DOWN_EVENT, 0);
            keybd_event(key, 0, KEY_UP_EVENT, 0);
            System.Threading.Thread.Sleep(PauseBetweenStrokes);
            totalDuration += PauseBetweenStrokes;
        }
    }
}

Solution 3

You can get it to work with that, this works great for holding down keys:

    public class Keyboard
{

    const int PauseBetweenStrokes = 50;
    [DllImport("user32.dll", SetLastError = true)]
    static extern void keybd_event(byte bVk, byte bScan, int dwFlags, int dwExtraInfo);

    const int KEY_DOWN_EVENT = 0x0001; //Key down flag
    const int KEY_UP_EVENT = 0x0002; //Key up flag

    public static void HoldKey(byte key, int duration)
    {
        keybd_event(key, 0, KEY_DOWN_EVENT, 0);
        System.Threading.Thread.Sleep(duration);
        keybd_event(key, 0, KEY_UP_EVENT, 0);
    }
}
Share:
10,853
Deepsy
Author by

Deepsy

My name is Viktor Kirilov and I'm living in Montana, BG. I started working on the web about 6 years ago. Since then I have been using many technologies and tools for software developing. I have been participated in different IT competitions and I've achieved top positions. In the past few years I've practiced and tried to master languages such as PHP and JavaScript, HTML and CSS. In my lastest projects I've been using some of the most famous Javascript frameworks/libs such as BackBone, Angular, Require, jQuery. I've created my own PHP MVC framework called AlbaFramework. My experience with databases includes MongoDB and MySQL as well as Redis and Memcached. Since I found NodeJS I'm in love with it and I'm currently running FinalBurnout and Smartly on it. Also I've been in touch with python, java and many more. I've been building simple application with C++, C# and VB. My experience with mobile devices includes Java and Android. I got big experience with Linux based system ( Fedora, Debian, Ubuntu ).

Updated on June 14, 2022

Comments

  • Deepsy
    Deepsy almost 2 years

    I'm trying to make a C# application, which is going to control a game. That I'm trying to do is for example: Hold key A for 150ms, Hold left arrow for 500ms and so on. I was searching a lot and I found the following code. My program firstly target the game and then holding the keys.

    I'm holding the keys this way:
    
    Keyboard.HoldKey(Keys.Left);
    Thread.sleep(500);
    Keyboard.ReleaseKey(Keys.Left);
    

    Here is the Keyboard class:

    public class Keyboard
     {
        public Keyboard()
        {
        }
    
        [StructLayout(LayoutKind.Explicit, Size = 28)]
        public struct Input
        {
            [FieldOffset(0)]
            public uint type;
            [FieldOffset(4)]
            public KeyboardInput ki;
        }
    
        public struct KeyboardInput
        {
            public ushort wVk;
            public ushort wScan;
            public uint dwFlags;
            public long time;
            public uint dwExtraInfo;
        }
    
        const int KEYEVENTF_KEYUP = 0x0002;
        const int INPUT_KEYBOARD = 1;
    
        [DllImport("user32.dll")]
        public static extern int SendInput(uint cInputs, ref Input inputs, int cbSize);
    
        [DllImport("user32.dll")]
        static extern short GetKeyState(int nVirtKey);
    
        [DllImport("user32.dll")]
        static extern ushort MapVirtualKey(int wCode, int wMapType);
    
    
        public static bool IsKeyDown(Keys key)
        {
            return (GetKeyState((int)key) & -128) == -128;
        }
    
        public static void HoldKey(Keys vk)
        {
            ushort nScan = MapVirtualKey((ushort)vk, 0);
    
            Input input = new Input();
            input.type = INPUT_KEYBOARD;
            input.ki.wVk = (ushort)vk;
            input.ki.wScan = nScan;
            input.ki.dwFlags = 0;
            input.ki.time = 0;
            input.ki.dwExtraInfo = 0;
            SendInput(1, ref input, Marshal.SizeOf(input)).ToString();
        }
    
        public static void ReleaseKey(Keys vk)
        {
            ushort nScan = MapVirtualKey((ushort)vk, 0);
    
            Input input = new Input();
            input.type = INPUT_KEYBOARD;
            input.ki.wVk = (ushort)vk;
            input.ki.wScan = nScan;
            input.ki.dwFlags = KEYEVENTF_KEYUP;
            input.ki.time = 0;
            input.ki.dwExtraInfo = 0;
            SendInput(1, ref input, Marshal.SizeOf(input));
        }
    
        public static void PressKey(Keys vk)
        {
            HoldKey(vk);
            ReleaseKey(vk);
        }
    }
    

    and its working in notepad/browser etc, but it IS NOT working in any game, no matter fullscreen or window mode. Can you help me to figure out how I can hold keys in full screen apps/games? Thanks!

  • Deepsy
    Deepsy almost 11 years
    Hello. Thanks for the answer, but sadly the effect is the same as code posted in my first post: its working in notepad/browsers etc, but its not working in game windows.
  • Idle_Mind
    Idle_Mind almost 11 years
    I changed HoldKey() to rapidly press/release the key until duration has been met. See if that works any better...
  • Deepsy
    Deepsy almost 11 years
    Still the same, Seems the game are handling the key pressed in different way :(
  • Idle_Mind
    Idle_Mind almost 11 years
    Just noticed I didn't include "PauseBetweenStrokes": const int PauseBetweenStrokes = 50; I don't think it will make much difference, though. Sorry it didn't work...good luck!
  • Deepsy
    Deepsy almost 11 years
    Yeah, I tried with 1, 10 and 20 :( Seems not every game is able to handle such operations.
  • Idle_Mind
    Idle_Mind almost 11 years
    Supposedly these guys got SendInput() working with DirectInput here.
  • SJ10
    SJ10 almost 3 years
    Can you explain what you mean by this?