using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace test3 { public partial class ExampleForm : Form{ [System.Runtime.InteropServices.DllImport("user32.dll")] protected static extern IntPtr SetWindowsHookEx(HookType code, HookProc func, IntPtr hInstance, int threadID); [System.Runtime.InteropServices.DllImport("user32.dll")] static extern int CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam); [System.Runtime.InteropServices.DllImport("kernel32.dll", SetLastError = true)] private static extern IntPtr GetModuleHandle(string lpModuleName); public enum HookType : int { WH_KEYBOARD = 2, }; public delegate int HookProc(int nCode, IntPtr wParam, IntPtr lParam); private HookProc myCallbackDelegate = null; public ExampleForm(){ this.myCallbackDelegate = new HookProc(this.MyCallbackFunction); SetWindowsHookEx(HookType.WH_KEYBOARD, this.myCallbackDelegate, GetModuleHandle("user32")/*IntPtr.Zero*/, /*AppDomain.GetCurrentThreadId()*/0); } private int MyCallbackFunction(int code, IntPtr wParam, IntPtr lParam){ if (code < 0) { return CallNextHookEx(IntPtr.Zero, code, wParam, lParam); } // convert to a System.Windows.Forms.Keys enum constant Keys key = (Keys)wParam.ToInt32(); // if (lParam.ToInt32() < 0 /*&& wParam.ToInt32() == (int)'A'*/) Console.WriteLine(key); //return the value returned by CallNextHookEx return CallNextHookEx(IntPtr.Zero, code, wParam, lParam); } } }