Skip to content

Instantly share code, notes, and snippets.

@NaxAlpha
Created July 26, 2016 05:41
Show Gist options
  • Save NaxAlpha/df27dcc11b0b99e79f11e457bdf43e89 to your computer and use it in GitHub Desktop.
Save NaxAlpha/df27dcc11b0b99e79f11e457bdf43e89 to your computer and use it in GitHub Desktop.
Global Input Hook with C#
using System;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;
class Program {
[DllImport("user32.dll")]
static extern short GetAsyncKeyState(Keys vKey);
static void Main(string[] args) {
var keyValues = Enum.GetValues(typeof(Keys));
// Start Infinite Loop with little wait
var wait = new SpinWait();
while (true) {
// Check for every key state
foreach (var vKey in keyValues) {
var state = GetAsyncKeyState((Keys)vKey);
if (state != 0)
Console.Write(((Keys)vKey).ToString() + " ");
}
// To reduce CPU load
wait.SpinOnce();
}
}
}
using System;
using System.Windows.Forms;
using Gma.System.MouseKeyHook;
class Program {
static void Main(string[] args) {
Console.Title = "Global Input Hook";
var hook = Hook.GlobalEvents();
hook.KeyPress += Hook_KeyPress;
// We must setup event loop
// To capture input after
// Adding handlers of all hook events
Application.Run();
}
private static void Hook_KeyPress(object sender, KeyPressEventArgs e) {
Console.Write(e.KeyChar);
if (e.KeyChar == '\r')
Console.Write((char)10);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment