简体   繁体   中英

How to detect if multiple keys are pressed in C# forms

I have looked for a solution to detect if multiple keys are pressed in C# (I couldn't find a solution!). I have this game with two players and I need to detect if a key is pressed to move them around. (I'm Using C# Forms) I've only found answers to detect if two keys are held down at the same time and they didn't help.

--EDIT--

How to detect if a key is pressed using KeyPressed (C#)

The source of the problems is that this simple request is simply not supported under Winforms.

Sounds weird? It is. Winforms is often painfully close to the hardware layers and while this may be quite interesting at times, it also may be just a pita..

((One hidden hint by Hans should be noted: In the KeyUp you get told which key was released so you can keep track of as many keys as you want..))

But now for a direct solution that desn't require you to keep a bunch of bools around and manage them in the KeyDown and KeyUp events..: Enter Keyboard.IsKeyDown .

With it code like this works:

Uses the Keyboard.IsKeyDown to determine if a key is down. e is an instance of KeyEventArgs .

 if (Keyboard.IsKeyDown(Key.Return)) { btnIsDown.Background = Brushes.Red; } ...

Of course you can ceck for multiple key as well:

if (Keyboard.IsKeyDown(Key.A) && Keyboard.IsKeyDown(Key.W)) ...

The only requirement is that you borrow this from WPF :

First: Add the namespace:

using System.Windows.Input;

Then: Add two references to the project:

PresentationCore
WindowsBase

在此处输入图像描述

Now you can test the keyboard at any time, including the KeyPress event..

也许用于打印到控制台...

if (Input.GetKeyDown(KeyCode.G))     {print ("G key pressed");}

The easiest way to do this is:

  1. Create a KeyDown event for the form

  2. Write down the DllImports below in the class:

     [DllImport("user32")] public static extern int GetAsyncKeyState(int vKey); [DllImport("user32.dll")] public static extern int GetKeyboardState(byte[] keystate);
  3. Write down the code below in the KeyDown Event:

     byte[] keys = new byte[256]; GetKeyboardState(keys); if ((keys[(int)Keys.ControlKey] & keys[(int)Keys.S] & 128) == 128) // change the keys if you want to { // it worked }
  4. Paste the code this.KeyPreview = true; in the Form_Load event and boom, there you go.

This is currently the best way to handle multiple Key events as it's a simple and straight up way for WinForms.

You can achieve it using program level keyboard hook. You can use Win-API functions like SetWindowsHookEx in user32.dll.

Here are some examples of it :

A Simple C# Global Keyboard Hook
Global keyboard capture in C# application

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM