C# hold key in a game application

落花浮王杯 提交于 2019-11-30 14:59:50

"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;
        }
    }
}

I did it with Windown API and SendInput method.

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);
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!