C# key scan codes

1k views Asked by At
1

There are 1 answers

1
Wesley On BEST ANSWER

You can use MapVirtualKey from user32.dll for this

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();
    }
}

Unfortunately dotnetfiddle does not allow running the above code, but it outputs 3F. VK_F5 would be replaced by (uint)KeyEventArgs.Key for your case I believe.

Edit: It appears the value in the System.Windows.Input.Key enum don't match up with the value in my example which are from the System.Windows.Forms.Keys namespace, so the above code will not work on KeyEventArgs.Key directly.

Edit 2: You can use KeyInterop.VirtualKeyFromKey from the System.Windows.Input namespace to convert from System.Windows.Input.Key to System.Windows.Forms.Keys.

So for your case this should work; var scanCodeForF5 = MapVirtualKey(KeyInterop.VirtualKeyFromKey(Key.F5), MAPVK_VK_TO_VSC);