Always I found a thrid party app beetwen keyboard and autohotkey, like LuaMacros.
AHKHID seemed the ultimate solution but... didn't work. No like I wanted.
However I didn't give up. I continued researching on my own, and finally my quest paid off.
The key is wait. Yes, waiting for until OS give you the ID for the Keyboard used. So simple, so hard
In my system I have to wait about 50 ms for the response. A very old dual core cpu.
How it works?
Mandatory is AHKHID lib, of course
Then, intercept WM_INPUT message (see AHKHID examples)
Write a rutine with a loop, waiting for identification of the keyboard
And... that's all
The code:
Code: Select all
#include AHKHID.ahk
Global KEYBOARD_USED ; a global variable to identify the last keyboard used
, ID_Keyb_1 := ""\\?\HID#VID_046D&PID_B301&" ; ID for keyboard you want to monitor, first characters enough for me
;Create GUI
Gui +LastFound -Resize -MaximizeBox -MinimizeBox
Gui, Add, Text, , Multiple Keyboards
;Keep handle
GuiHandle := WinExist()
;Show GUI
Gui, Show
;Dimension the array
AHKHID_AddRegister(1)
;Add for registration
AHKHID_AddRegister(1, 6, GuiHandle, RIDEV_INPUTSINK) ; intercept keys even if this window is in background
;Register
AHKHID_Register()
;Intercept WM_INPUT
OnMessage(0x00FF, "InputMsg")
return
; -----------------------------------------
GuiClose:
ExitApp
;-----------------------------------------
InputMsg(wParam, lParam)
{
Critical
;Get device type
r := AHKHID_GetInputInfo(lParam, II_DEVTYPE)
If (r = -1)
OutputDebug %ErrorLevel%
if (r <> RIM_TYPEKEYBOARD) ; only keyboards
return
h := AHKHID_GetInputInfo(lParam, II_DEVHANDLE)
DeviceName := AHKHID_GetDevName(h,True)
n := InStr( DeviceName, "&", false, 1, 2 )
; In my case, first characters enough
; You may need more if 2 keyboards are identical and you need to identify
; the USB port to which they are connected to differentiate them
if n
KEYBOARD_USED := SubStr( DeviceName, 1, n )
Critical, off
}
Which_Keyboard()
{
KEYBOARD_USED := ""
while ( KEYBOARD_USED = "")
{
; only wait
}
return KEYBOARD_USED
}
z:: ; your hotkey
{
if (Which_Keyboard() = ID_Keyb_1)
{
;whatever you want to do
}
else
{
;another thing
}
return
}
One last thing
If you use any #IF sentence to create a context-sensitive hotkey, then this method doesn't work. InputMsg() never executed
I don't know why
P.S.: Sorry. English is not my first language