C# - Check if specific key is pressed

Viewed 38323

I'm trying to check if a key is pressed, but I get these Error Message:

Error 1 The name 'Keyboard' does not exist in the current context

Error 2 The name 'Key' does not exist in the current context

Can you tell me how to fix it?

public void Main() 
{
    while(true) 
    {
        if (Keyboard.IsKeyPressed(Key.A)) 
        {
            //...
        }
        return;
    }
}
5 Answers

If you are trying to do this in a windows forms application, maybe you can add these codes into the Form's KeyDown event(or which key event you need to use):

switch (e.KeyData)
{
    //Detects that you pressed the Up Arrow Key, which key do you need, just 
    //write it here.
    case Keys.Up: 
    //enter code here`
    break;
}

You need to add PresentationCore.dll and WindowsBase to references and add to the header of the method [STAThread]

Related