c#键扫描代码



我可以得到这个扫描码描述这里https://www.freepascal.org/docs-html/current/rtl/keyboard/kbdscancode.html在c# WPF KeyEventArgs?

您可以使用user32.dll中的MapVirtualKey

using System;
using System.Runtime.InteropServices;
public class Program
{
private const uint MAPVK_VK_TO_VSC = 0;
private const uint VK_F5 = 116; // https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.keys?view=net-5.0
[DllImport("user32.dll",
CallingConvention = CallingConvention.StdCall,
CharSet = CharSet.Unicode,
EntryPoint = "MapVirtualKey",
SetLastError = true,
ThrowOnUnmappableChar = false)]
private static extern uint MapVirtualKey(uint uCode, uint uMapType);
public static void Main()
{
var scanCodeForF5 = MapVirtualKey(VK_F5, MAPVK_VK_TO_VSC);
Console.WriteLine(scanCodeForF5.ToString("X"));
Console.ReadLine();
}
}

不幸的是,dotnetfiddle不允许运行上面的代码,但它输出3F。

对于您的情况,我相信VK_F5将被(uint)KeyEventArgs.Key

取代。编辑:似乎System.Windows.Input.Keyenum中的值与我的示例中来自System.Windows.Forms.Keys命名空间的值不匹配,因此上述代码将不能直接在KeyEventArgs.Key上工作。

编辑2:您可以使用System.Windows.Input命名空间中的KeyInterop.VirtualKeyFromKeySystem.Windows.Input.Key转换为System.Windows.Forms.Keys

对于你的情况,这应该是可行的;var scanCodeForF5 = MapVirtualKey(KeyInterop.VirtualKeyFromKey(Key.F5), MAPVK_VK_TO_VSC);

最新更新