Detect if any key is pressed in C# (not A, B, but any)

前端 未结 9 2325
粉色の甜心
粉色の甜心 2020-12-01 08:32

[EDIT 3] I kind of "solved it" by at using the "strange" version. At least for the most important keys. It is suffient for my case, where I want to check

9条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-01 09:01

    [DllImport("user32.dll", EntryPoint = "GetKeyboardState", SetLastError = true)]
    private static extern bool NativeGetKeyboardState([Out] byte[] keyStates);
    
    private static bool GetKeyboardState(byte[] keyStates)
    {
        if (keyStates == null)
            throw new ArgumentNullException("keyState");
        if (keyStates.Length != 256)
            throw new ArgumentException("The buffer must be 256 bytes long.", "keyState");
        return NativeGetKeyboardState(keyStates);
    }
    
    private static byte[] GetKeyboardState()
    {
        byte[] keyStates = new byte[256];
        if (!GetKeyboardState(keyStates))
            throw new Win32Exception(Marshal.GetLastWin32Error());
        return keyStates;
    }
    
    private static bool AnyKeyPressed()
    {
        byte[] keyState = GetKeyboardState();
        // skip the mouse buttons
        return keyState.Skip(8).Any(state => (state & 0x80) != 0);
    }
    

提交回复
热议问题