Imports System
Imports System.Text
Imports System.Windows
Imports System.Windows.Input
Imports System.Runtime.InteropServices

Namespace Calculator
''  See https://stackoverflow.com/questions/5825820/how-to-capture-the-character-on-different-locale-keyboards-in-wpf-c
Public Class KeyToAscii
   Public Sub New()
      MyBase.New()
   End Sub

   Public Shared Function GetAsciiFromKey(ByVal key As Key) As Integer
      Dim chars As Char = Strings.ChrW(0)
      Dim num As Integer = KeyInterop.VirtualKeyFromKey(key)
      Dim numArray(256) As Byte
      KeyToAscii.GetKeyboardState(numArray)
      Dim num1 As UInteger = KeyToAscii.MapVirtualKey(num, KeyToAscii.MapType.MAPVK_VK_TO_VSC)
      Dim stringBuilder As StringBuilder = New StringBuilder(2)
      Dim unicode As Integer = KeyToAscii.ToUnicode(num, num1, numArray, stringBuilder, stringBuilder.Capacity, 0)
      Select Case unicode
      Case -1
         Exit Select
      Case 0
         Exit Select
      Case 1
         chars = stringBuilder(0)
         Exit Select
      Case Else
         chars = stringBuilder(0)
         Exit Select
      End Select
      Dim num2 As Integer = AscW(chars)
      Return num2
   End Function

   <DllImport("user32.dll", CharSet:=CharSet.None)>
   Private Shared Function GetKeyboardState(ByVal lpKeyState As Byte()) As Boolean
   End Function
   <DllImport("user32.dll", CharSet:=CharSet.None)>
   Private Shared Function MapVirtualKey(ByVal uCode As UInteger, ByVal uMapType As MapType) As UInteger
   End Function
   <DllImport("user32.dll", CharSet:=CharSet.None)>
   Private Shared Function ToUnicode(ByVal wVirtKey As UInteger, ByVal wScanCode As UInteger, ByVal lpKeyState As Byte(), ByVal pwszBuff As StringBuilder, ByVal cchBuff As Integer, ByVal wFlags As UInteger) As Integer
   End Function

   Enum MapType As UInteger
      MAPVK_VK_TO_VSC = 0
      MAPVK_VSC_TO_VK = 1
      MAPVK_VK_TO_CHAR = 2
      MAPVK_VSC_TO_VK_EX = 3
   End Enum

End Class
End Namespace
