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

前端 未结 9 2324
粉色の甜心
粉色の甜心 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:06

    Quite an old question but in case anyone comes across this and doesn't want to use external dll's, you could just enumerate the possible keys and loop over them.

    bool IsAnyKeyPressed()
    {
        var allPossibleKeys = Enum.GetValues(typeof(Key));
        bool results = false;
        foreach (var currentKey in allPossibleKeys)
        {
            Key key = (Key)currentKey;
            if (key != Key.None)
                if (Keyboard.IsKeyDown((Key)currentKey)) { results = true; break; }
        }
        return results;
    }
    

    You could optimize this a bit by doing the enum outside of the function and retaining the list for later.

提交回复
热议问题