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
LVL 12
Mortaza DoulatyAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
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...
Determine the Perfect Price for Your IT Services

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden with our free interactive tool and use it to determine the right price for your IT services. Download your free eBook now!

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 :
    [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...
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Visual Basic Classic

From novice to tech pro — start learning today.