C#按键扫描码

C# key scan codes

我能否在 C# WPF KeyEventArgs 中获取这里 https://www.freepascal.org/docs-html/current/rtl/keyboard/kbdscancode.html 描述的扫描代码?

您可以为此使用 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://docs.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 取代。

EditSystem.Windows.Input.Key 枚举中的值似乎与我示例中来自 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);