2016-07-26 133 views
2

我已經爲WPF寫了一個熱鍵控件,並且想要向用戶顯示友好名稱。爲此我使用GetKeyNameText使用GetKeyNameText和特殊鍵

然而,例如,當使用Key.MediaNextTrack作爲輸入時,GetKeyNameText返回P,顯然看起來錯了。任何人都可以幫助我得到這種神祕鑰匙的正確名稱嗎?

我的代碼並執行以下操作:

  1. 呼叫KeyInterop.VirtualKeyFromKey得到了Win32虛擬鍵
  2. 翻譯虛擬鍵調用MapVirtualKey
  3. 呼叫GetKeyNameText

完整的代碼掃描代碼是這樣的(你需要參考WindowsBase):

using System; 
using System.Runtime.InteropServices; 
using System.Text; 
using System.Windows.Input; 

namespace ConsoleApplication1 { 
    class Program { 
     static void Main() { 
      var key = Key.MediaNextTrack; 
      var virtualKeyFromKey = KeyInterop.VirtualKeyFromKey(key); 
      var displayString = GetLocalizedKeyStringUnsafe(virtualKeyFromKey); 

      Console.WriteLine($"{key}: {displayString}"); 
     } 

     private static string GetLocalizedKeyStringUnsafe(int key) { 
      // strip any modifier keys 
      long keyCode = key & 0xffff; 

      var sb = new StringBuilder(256); 

      long scanCode = MapVirtualKey((uint) keyCode, MAPVK_VK_TO_VSC); 

      // shift the scancode to the high word 
      scanCode = (scanCode << 16); // | (1 << 24); 
      if (keyCode == 45 || 
       keyCode == 46 || 
       keyCode == 144 || 
       (33 <= keyCode && keyCode <= 40)) { 
       // add the extended key flag 
       scanCode |= 0x1000000; 
      } 

      GetKeyNameText((int) scanCode, sb, 256); 
      return sb.ToString(); 
     } 

     private const uint MAPVK_VK_TO_VSC = 0x00; 

     [DllImport("user32.dll")] 
     private static extern int MapVirtualKey(uint uCode, uint uMapType); 

     [DllImport("user32.dll", EntryPoint = "GetKeyNameTextW", CharSet = CharSet.Unicode)] 
     private static extern int GetKeyNameText(int lParam, [MarshalAs(UnmanagedType.LPWStr), Out] StringBuilder str, int size); 
    } 
} 

回答

0
  1. 虛擬鍵不包含修飾符因此不需要做&ffff
  2. MapVirtualKey不適用於擴展密鑰,我懷疑是您的問題。嘗試使用MapVirtualKeyEx