• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1079
  • Last Modified:

Trap which key is pressed in different keyboard layouts...

I want to write a function that returns the equilent character of the pressed key on keyboard.
For this reason, I have written a programs that hooks keyboard, when a key is pressed, an event fires and KeyCode and Shift are the input parameters of that sub.
Now I want to recognize which character was pressed, the keyboard have different layouts, for example English, Arabic, Turkish and etc.
I want to trap all keys.
I have found some functions like:
ch=ChrW$(MapVirtualKeyEx(KeyCode, 2,  GetKeyboardLayout(GetWindowThreadProcessId(GetForegroundWindow,  0))))

But it does not distimquish between smalls and capital letters and it is workign just for English keyboard layout, not others.

I want a piece of code that ocnverts the KeyCode,Shift and Keyboard layout to a character.

My program is being developed vb Visual Basic 6.0
Mortaza Doulaty
Mortaza Doulaty
  • 8
1 Solution
When you hook the keyboard add this code. It will return the character based on the current keyboard language selected. Code has been tested using English, Portuguese, Arabic, Armenian. Please note that this does not address complex IME such as Chinese where several characters can be returned at once. In this case you will see m_KeyCodeCached = 229 which indicates that the IME is busy. :

Dim m_KeyCodeCached As Long
Dim sChar as String

'In Hook code:
      m_KeyCodeCached = LOWORD(wParam)
   Case WM_CHAR
      sChar = ToCharacterEx(wParam, m_KeyCodeCached, 0&))
     'Note this may be ANSI or Unicode so use a Unicode aware control to display this character

'In Module add following code:

Option Explicit

Private Declare Function GetKeyboardState Lib "user32" (pbKeyState As Byte) As Long
Private Declare Function GetLocaleInfoA Lib "kernel32" (ByVal Locale As Long, ByVal LCType As Long, ByVal lpLCData As String, ByVal cchData As Long) As Long
Private Declare Function MultiByteToWideChar Lib "kernel32" (ByVal CodePage As Long, ByVal dwFlags As Long, ByVal lpMultiByteStr As Long, ByVal cchMultiByte As Long, ByVal lpWideCharStr As Long, ByVal cchWideChar As Long) As Long
Private Declare Function GetVersionEx Lib "kernel32" Alias "GetVersionExA" (lpVersionInformation As OSVERSIONINFO) As Long
Private Declare Function ToAsciiEx Lib "user32" (ByVal uVirtKey As Long, ByVal uScanCode As Long, lpKeyState As Byte, ByVal lpChar As Long, ByVal uFlags As Long, ByVal dwhkl As Long) As Long
Private Declare Function ToUnicodeEx Lib "user32" (ByVal uVirtKey As Long, ByVal uScanCode As Long, lpKeyState As Byte, ByVal pwszBuff As Long, ByVal cchBuff As Long, ByVal wFlags As Long, ByVal dwhkl As Long) As Long
Private Declare Function lstrlenW Lib "kernel32" (ByVal lpString As Any) As Long
Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (hpvDest As Any, hpvSource As Any, ByVal cbCopy As Long)

Private Const CP_ACP  As Long = 0
Private Const VER_PLATFORM_WIN32_NT As Long = 2

   dwOSVersionInfoSize  As Long
   dwMajorVersion       As Long
   dwMinorVersion       As Long
   dwBuildNumber        As Long
   dwPlatformId         As Long
   szCSDVersion         As String * 128 ' Maintenance string
End Type

Public Function ToCharacterEx(ByVal KeyAscii As Integer, _
   ByVal KeyCode As KeyCodeConstants, hKL As Long) As String
   Dim stBuff           As String
   Dim cch              As Long
   Dim cpg              As Long
   Dim lPtr             As Long
   Dim rgvkc(0 To 255)  As Byte

   stBuff = String$(32, vbNullChar)
   Call GetKeyboardState(rgvkc(0))
   If IsNT Then
      lPtr = StrPtr(stBuff)
      cch = ToUnicodeEx(KeyCode, 0, rgvkc(0), lPtr, Len(stBuff), 0, hKL)
      If cch = -1 Then cch = 2
      ToCharacterEx = Left$(stBuff, cch)
      cch = ToAsciiEx(KeyCode, 0, rgvkc(0), StrPtr(stBuff), 0, hKL)
      If cch = -1 Then cch = 2
      cpg = CpgFromLcid(LOWORD(hKL))
      stBuff = Left$(stBuff, cch)
      ToCharacterEx = AToW(stBuff, cpg)
   End If

   'If no Unicode returned from above assume a normal kybd input.
   'This includes accented Português such as ~a which is م.
   If Not IsUnicode(ToCharacterEx) Then
      ToCharacterEx = ChrW$(KeyAscii)
   End If

End Function

Public Function CpgFromLcid(lcid As Long) As Long
   Dim cwc              As Long
   Dim stBuffer         As String
   stBuffer = String$(10, vbNullChar)
   cwc = GetLocaleInfoA(lcid, LOCALE_IDEFAULTANSICODEPAGE, stBuffer, Len(stBuffer))

   If cwc = 0 Then
      cwc = GetLocaleInfoA(lcid, LOCALE_IDEFAULTCODEPAGE, stBuffer, Len(stBuffer))
   End If

   If cwc > 0 Then
      CpgFromLcid = Val(Left$(stBuffer, cwc - 1))
      CpgFromLcid = CP_ACP
   End If
End Function

'Converts a multibyte string to a Unicode (UCS-2) string
Public Function AToW(ByVal st As String, Optional ByVal CodePage As Long = CP_ACP, Optional lFlags As Long = 0) As String
   Dim stBuffer         As String
   Dim cwch             As Long
   Dim pwz              As Long
   Dim pwzBuffer        As Long
   'the buffer is always 2 bytes, as Windows Unicode is always
   'two bytes per character
   stBuffer = String$((Len(st) + 1) * 2, vbNullChar)
   pwz = StrPtr(st)
   pwzBuffer = StrPtr(stBuffer)
   cwch = MultiByteToWideChar(CodePage, lFlags, pwz, -1, pwzBuffer, Len(stBuffer))
   If cwch = 0 Then
      Err.Raise vbObjectError Or 1000, , "MultiByteToWideChar call failed with Error: " & Err.LastDllError
      AToW = Left$(stBuffer, cwch - 1)
   End If
End Function

Public Function LOWORD(ByVal lDWord As Long) As Integer
   LOWORD = lDWord And &HFFFF&
End Function

'Purpose:Returns True if string has a Unicode char.
'Note: Also returns True if MBCS.
Public Function IsUnicode(s As String) As Boolean
   Dim i                As Long
   Dim bLen             As Long
   Dim Map()            As Byte

   If LenB(s) Then
      Map = s
      bLen = UBound(Map)
      For i = 1 To bLen Step 2 'Analise HighByte only.
         If (Map(i) > 0) Then
            IsUnicode = True
            Exit Function
         End If
   End If
End Function

Private Function IsNT() As Boolean
   Dim udtVer           As OSVERSIONINFO

   On Error Resume Next
   udtVer.dwOSVersionInfoSize = Len(udtVer)
   If GetVersionEx(udtVer) Then
      If udtVer.dwPlatformId = VER_PLATFORM_WIN32_NT Then
         IsNT = True
      End If
   End If
End Function
Mortaza DoulatyAuthor Commented:
Thanks for your reply.
i am relly busy these days, so i have not enought free time to check ur solutiuon.
I'm really sorry about that.
Mortaza DoulatyAuthor Commented:
Sorry about that...
I am really busy these days, so I did not have enough free time to check the solution...
Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

Mortaza DoulatyAuthor Commented:
Dear danaseaman,

Would you please provide me with the complete source code?
Mortaza DoulatyAuthor Commented:
It seems to be some problems with your code:
'In Hook code:
      m_KeyCodeCached = LOWORD(wParam)
   Case WM_CHAR
      sChar = ToCharacterEx(wParam, m_KeyCodeCached, 0&))
     'Note this may be ANSI or Unicode so use a Unicode aware control to display this character

According to http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/WindowsUserInterface/Windowing/Hooks/HookReference/HookFunctions/LowLevelKeyboardProc.asp :
    [in] Specifies the identifier of the keyboard message. This parameter can be one of the following messages: WM_KEYDOWN, WM_KEYUP, WM_SYSKEYDOWN, or WM_SYSKEYUP.

So the "Case WM_CHAR" will never execute...
Mortaza DoulatyAuthor Commented:
With some corrections, finally it worked:
(m_KeyCodeCached should be declared as Static)
      m_KeyCodeCached = LOWORD(lParam.vkCode)
   Case WM_KEYUP
      sChar = ToCharacterEx(lParam.vkCode, m_KeyCodeCached, 0&)
     'Note this may be ANSI or Unicode so use a Unicode aware control to display this character
     Debug.Print sChar

Open in new window

Mortaza DoulatyAuthor Commented:
Still not working very well, any suggestions... ?
Mortaza DoulatyAuthor Commented:
The problem is:
WM_KEYUP is not hooked...
Mortaza DoulatyAuthor Commented:
Sorry, my previous post has a type,
WM_CHAR is not hooked...
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

  • 8
Tackle projects and never again get stuck behind a technical roadblock.
Join Now