Solved

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

Posted on 2007-04-08
10
1,048 Views
Last Modified: 2008-01-09
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
0
Comment
Question by:Mortaza Doulaty
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 8
10 Comments
 
LVL 22

Accepted Solution

by:
danaseaman earned 125 total points
ID: 18872122
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:
   Case WM_KEYDOWN
      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
Private Const LOCALE_IDEFAULTCODEPAGE = &HB
Private Const LOCALE_IDEFAULTANSICODEPAGE = &H1004

Private Type OSVERSIONINFO
   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)
   Else
      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

'----------------------------------------------------------------------------------------
'CpgFromLcid
'----------------------------------------------------------------------------------------
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))
   Else
      CpgFromLcid = CP_ACP
   End If
End Function

'--------------------------------------
'AToW
'
'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
   Else
      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
      Next
   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
0
 
LVL 12

Author Comment

by:Mortaza Doulaty
ID: 18896427
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.
0
 
LVL 12

Author Comment

by:Mortaza Doulaty
ID: 19132643
Sorry about that...
I am really busy these days, so I did not have enough free time to check the solution...
0
Salesforce Has Never Been Easier

Improve and reinforce salesforce training & adoption using WalkMe's digital adoption platform. Start saving on costly employee training by creating fast intuitive Walk-Thrus for Salesforce. Claim your Free Account Now

 
LVL 12

Author Comment

by:Mortaza Doulaty
ID: 21375965
Dear danaseaman,

Would you please provide me with the complete source code?
0
 
LVL 12

Author Comment

by:Mortaza Doulaty
ID: 21376026
It seems to be some problems with your code:
'In Hook code:
   Case WM_KEYDOWN
      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 :
wParam
    [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...
0
 
LVL 12

Author Comment

by:Mortaza Doulaty
ID: 21376084
With some corrections, finally it worked:
(m_KeyCodeCached should be declared as Static)
    Case WM_KEYDOWN
      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

0
 
LVL 12

Author Comment

by:Mortaza Doulaty
ID: 21376495
Still not working very well, any suggestions... ?
0
 
LVL 12

Author Comment

by:Mortaza Doulaty
ID: 21409680
The problem is:
WM_KEYUP is not hooked...
0
 
LVL 12

Author Comment

by:Mortaza Doulaty
ID: 21409686
Sorry, my previous post has a type,
WM_CHAR is not hooked...
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction I needed to skip over some file processing within a For...Next loop in some old production code and wished that VB (classic) had a statement that would drop down to the end of the current iteration, bypassing the statements that were c…
I’ve seen a number of people looking for examples of how to access web services from VB6.  I’ve been using a test harness I built in VB6 (using many resources I found online) that I use for small projects to work out how to communicate with web serv…
Get people started with the process of using Access VBA to control Outlook using automation, Microsoft Access can control other applications. An example is the ability to programmatically talk to Microsoft Outlook. Using automation, an Access applic…
Get people started with the process of using Access VBA to control Excel using automation, Microsoft Access can control other applications. An example is the ability to programmatically talk to Excel. Using automation, an Access application can laun…

751 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question