Get all keys pressed

What should I use to be able to "press" all the keys on the keyboard? Because Form.KeyPress += new EventHandler()it does nothing at all when it fills the controls. It does not cause this no matter what I do, nor KeyDown, KeyUp, or anything else ... and yes, I know how to use them.

So, if there is any function in the system that can check pressed keys, which returns an array of keys used or something like that, I would be grateful for pointing it in the right direction.

+5
source share
4 answers

It looks like you want to query the status of all the keys on the keyboard. The best function for this is to call the Win32 APIGetKeyboardState

, . PInvoke

[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool GetKeyboardState(byte [] lpKeyState);

var array = new byte[256];
GetKeyboardState(array);

byte[] / . , . a Key key code byte Key.

public static byte GetVirtualKeyCode(Key key) {
  int value = (int)key;
  return (byte)(value & 0xFF);
}

Key, -. Keys.Alt, Keys.Control Keys.Shift , , . , Keys.ControlKey, Keys.LShiftKey .. ( , )

, , ,

var code = GetVirtualKeyCode(Key.A);
if ((array[code] & 0x80) != 0) {
  // It pressed
} else { 
  // It not pressed
}
+12

JaredPar. :

using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Windows.Input;

private static readonly byte[] DistinctVirtualKeys = Enumerable
    .Range(0, 256)
    .Select(KeyInterop.KeyFromVirtualKey)
    .Where(item => item != Key.None)
    .Distinct()
    .Select(item => (byte)KeyInterop.VirtualKeyFromKey(item))
    .ToArray();

/// <summary>
/// Gets all keys that are currently in the down state.
/// </summary>
/// <returns>
/// A collection of all keys that are currently in the down state.
/// </returns>
public IEnumerable<Key> GetDownKeys()
{
    var keyboardState = new byte[256];
    GetKeyboardState(keyboardState);

    var downKeys = new List<Key>();
    for (var index = 0; index < DistinctVirtualKeys.Length; index++)
    {
        var virtualKey = DistinctVirtualKeys[index];
        if ((keyboardState[virtualKey] & 0x80) != 0)
        {
            downKeys.Add(KeyInterop.KeyFromVirtualKey(virtualKey));
        }
    }

    return downKeys;
}

[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool GetKeyboardState(byte[] keyState);
+3

, , , , KeyPreview .

true . , , , Cancel true.

If you need to get the keys pressed while your application is not active, you need some kind of low-level keyboard hook. I have not tested it, but this CodeProject article looks very promising for this case.

+1
source

I believe that you are looking for a PreviewKeyDown event that will fire when a key is pressed when the focus is in focus, even if another child control in this form currently has focus.

0
source

All Articles