With a simple console application it works (except the IF condition where you need to check the value, c# is not able to cast number values to bool condition):
class Program
{
[DllImport("user32.dll")]
public static extern short GetAsyncKeyState(int key);
static void Main(string[] args)
{
while (true)
{
if ((GetAsyncKeyState(32) & 0x8000) > 0)
{
Console.WriteLine("User is holding Space!");
}
}
}
}
If you want to use it on a windows form then you should do it on a background thread to not freeze the application with it and store it in a property or fire up an event back to main thread, it depends on the use-case.
An example to use it in WinForms
public partial class Form1 : Form
{
[DllImport("user32.dll")]
public static extern short GetAsyncKeyState(int key);
bool spaceIsPressed = false;
Thread t = null;
public Form1()
{
InitializeComponent();
t = new Thread(CheckKey);
t.Start();
}
public void CheckKey()
{
try
{
while (true)
{
if ((GetAsyncKeyState(32) & 0x8000) > 0)
{
spaceIsPressed = true;
}
else
{
if (spaceIsPressed)
spaceIsPressed = false;
}
Thread.Sleep(200);
}
}
catch (ThreadInterruptedException ex) { }
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (t != null)
{
t.Interrupt();
t = null;
}
}
}