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

前端 未结 9 2312
粉色の甜心
粉色の甜心 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:11
    normally I would use an event
    

    You should still be using an event, preferably KeyDown since you don't mind what key is pressed, if you are programming on windows. If not, you could use something like Console.ReadLine();.

    edit: If you are looking for something like

    if (Keyboard.IsKeyDown(Key.AnyKey)) return true;
    

    then you must be joking...

    edit 2: Well, the approach of your logger is interesting, but I think that you are reinventing the wheel. All programming languages provides some way to handle wich key was pressed, when this can be known. In C# for Windows, this is done using events. Besides, I think you won't be able to handle this kind of things by yourself in .NET, since you need to access some system functions from the Win32 API, and AFAIK you aren't allowed to do this (at least easily...) in managed code. Some solution would be to create a HOOK and send messages from there to your application, but I don't know how to do this in C#. This was the way in Delphi, where I have more experience.

    0 讨论(0)
  • 2020-12-01 09:12

    Where is this code running from? Is it in an event handler? Many forms and controls will fire a KeyPress event as well as a KeyDown event. You may want to look into those events and set your flag to true when one of them occurs. You'd also have to listen for the corresponding event that tells you when the key is released (KeyUp, also, I think).

    0 讨论(0)
  • 2020-12-01 09:21

    Using the XNA framework you can use thw follow for checking if any key has been pressed.

    Keyboard.GetState().GetPressedKeys().Length > 0
    
    0 讨论(0)
提交回复
热议问题