要运行此代码:
>创建控制台应用程序
>添加对System.windows.Forms.dll程序集的引用
>粘贴此代码并进行测试.
码:
using System;using System.Diagnostics;using System.windows.Forms;using System.Runtime.InteropServices;class Program{ class InterceptKeys { // https://blogs.msdn.microsoft.com/toub/2006/05/03/low-level-keyboard-hook-in-c/ private const int WH_KEYBOARD_LL = 13; private const int WM_KEYDOWN = 0x0100; private static LowLevelKeyboardProc _proc = HookCallback; private static IntPtr _hookID = IntPtr.Zero; private static IntPtr SetHook(LowLevelKeyboardProc proc) { using (Process curProcess = Process.GetCurrentProcess()) using (ProcessModule curModule = curProcess.MainModule) { return SetwindowsHookEx(WH_KEYBOARD_LL,proc,GetModuleHandle(curModule.Modulename),0); } } private delegate IntPtr LowLevelKeyboardProc(int nCode,IntPtr wParam,IntPtr lParam); private static IntPtr HookCallback(int nCode,IntPtr lParam) { if (nCode >= 0 && wParam == (IntPtr)WM_KEYDOWN) { int vkCode = Marshal.ReadInt32(lParam); OnKeyDown?.Invoke(new KeyEventArgs((Keys)vkCode)); } return CallNextHookEx(_hookID,nCode,wParam,lParam); } [Dllimport("user32.dll",CharSet = CharSet.auto,SetLastError = true)] private static extern IntPtr SetwindowsHookEx(int IDHook,LowLevelKeyboardProc lpfn,IntPtr hMod,uint DWThreadID); [Dllimport("user32.dll",SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool UnhookwindowsHookEx(IntPtr hhk); [Dllimport("user32.dll",SetLastError = true)] private static extern IntPtr CallNextHookEx(IntPtr hhk,int nCode,IntPtr lParam); [Dllimport("kernel32.dll",SetLastError = true)] private static extern IntPtr GetModuleHandle(string lpModulename); private static event OnKeyDownDelegate OnKeyDown = null; public delegate voID OnKeyDownDelegate(KeyEventArgs e); public static voID SetupHook(OnKeyDownDelegate OnKeyDown) { InterceptKeys.OnKeyDown = OnKeyDown; System.Threading.Tasks.Task.Run(() => { _hookID = SetHook(_proc); Application.Run(); UnhookwindowsHookEx(_hookID); }); } public static voID ReleaseHook() { Application.Exit(); } } static voID KeyDown(KeyEventArgs e) { Console.Writeline("Hook: "+ e.KeyCode); } static voID Main() { InterceptKeys.SetupHook(KeyDown); while (true) { ConsoleKey key = Console.ReadKey(true).Key; Console.Writeline("ReadKey: "+ key); if (key == ConsoleKey.Escape) break; } InterceptKeys.ReleaseHook(); }}总结
以上是内存溢出为你收集整理的如何在C#控制台应用程序中捕获修改器(ctrl,alt,shift)按键作为单键按下?全部内容,希望文章能够帮你解决如何在C#控制台应用程序中捕获修改器(ctrl,alt,shift)按键作为单键按下?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)