While working on AutoHotkey_L's Gui code, I realized that
a) there's no command to retrieve a control's name and
b) I knew how to do it. As far as I know, this hasn't been done before:
GuiControlGetName(Control, Gui=Default)
Retrieves a Gui control's name (the name of it's associated variable if it has one), given its HWND or ClassNN and optionally its Gui number.
Code:
GuiControlGetName(Control, Gui="")
{
return GuiControlGetName_(Control, Gui, 0x8047, "") ; 0x8047 = WM_APP + 'G' (arbitrary)
}
GuiControlGetName_(Control, Gui, msg, hwnd)
{
static name
if (hwnd != "")
{
; We're handling a message. Store the name:
name := A_GuiControl
return 0
}
; Allow Control to be a HWND or ClassNN.
if Control is not integer
GuiControlGet Control, % (Gui="" ? "":Gui ":") "Hwnd", % Control "" ; Bug: Using %Control% alone won't work since it's also the output var.
; Reset name in case the message fails.
name := ""
; Record the previous handler of msg (if any).
prev := OnMessage(msg)
; Register our function as the handler of msg.
OnMessage(msg, A_ThisFunc)
; Post our message to the queue.
PostMessage msg,,,, ahk_id %Control%
if !ErrorLevel
; Check for and dispatch messages in the queue.
loop 50 ; Prevent infinite loop if message goes astray.
if (name = "")
Sleep 10 ; Wait for message to be processed.
else
break
; Restore the previous handler (if any) to prevent conflicts.
OnMessage(msg, prev)
; Return the name which has hopefully been set during Sleep.
return name
}
Example usage:
Code:
Gui Add, Edit, vMyEdit w100
Gui Add, Text, vMyText w100 hwndhwnd
MsgBox % GuiControlGetName("Edit1")
MsgBox % GuiControlGetName(hwnd)
ExitApp
Tested on AutoHotkey Basic and AutoHotkey_L v1.1.02.02. It will continue to work in v1.1.03, but it'll probably become obsolete.
Probable issue: Use of the
Critical command may prevent this function from working.