Skip to content

Instantly share code, notes, and snippets.

@michel-pi
Last active December 23, 2018 08:48
Show Gist options
  • Save michel-pi/dfb2e9d35ddf19ba05d08c1d9acda885 to your computer and use it in GitHub Desktop.
Save michel-pi/dfb2e9d35ddf19ba05d08c1d9acda885 to your computer and use it in GitHub Desktop.
GetAsyncKeyState wrapper
using System;
using System.Runtime.InteropServices;
namespace System.Input
{
public static class AsyncKeyState
{
[DllImport("user32.dll")]
private static extern short GetAsyncKeyState(int key);
public static readonly int MaxKeyCode = 0xFF;
public static readonly int MinKeyCode = 0x00;
public static bool IsPressed(VirtualKeyCode key)
{
if ((int)key < MinKeyCode || (int)key > MaxKeyCode) throw new ArgumentOutOfRangeException(nameof(key));
return (GetAsyncKeyState((int)key) & 0x8000) != 0;
}
public static bool WasPressed(VirtualKeyCode key)
{
if ((int)key < MinKeyCode || (int)key > MaxKeyCode) throw new ArgumentOutOfRangeException(nameof(key));
var result = GetAsyncKeyState((int)key);
return (result & 0x8000) == 0
&& (result & 0x0001) != 0;
}
public static bool IsFirstTimePressed(VirtualKeyCode key)
{
if ((int)key < MinKeyCode || (int)key > MaxKeyCode) throw new ArgumentOutOfRangeException(nameof(key));
var result = GetAsyncKeyState((int)key);
return (result & 0x8000) != 0
&& (result & 0x0001) != 0;
}
public static bool IsUp(VirtualKeyCode key)
{
if ((int)key < MinKeyCode || (int)key > MaxKeyCode) throw new ArgumentOutOfRangeException(nameof(key));
var result = GetAsyncKeyState((int)key);
return (result & 0x8000) == 0;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment