Detecting if a text is selected in Autohotkey

168 views Asked by At

I need to check if any text selected in Autohotkey. I have this function which works fine:

IsTextSelected()
{
    SavedClip := ClipboardAll()
    A_Clipboard := ""
    Send("^c")
    Errorlevel := !ClipWait(0.5) ; Wait for the clipboard to contain data
    if (!ErrorLevel) ; There is data on clipboard
        return (true)
    else
        return (false)
    ; Sleep(100)
    A_Clipboard := SavedClip
    SavedClip := ""
    return
}

But its too slow! Is there a way to speed up the process? Or is there another method to achieve that goal?

2

There are 2 answers

1
Afshin Davoudy On BEST ANSWER

Here is the correct answer based on Descolada script. (requires UIA.ahk in the same folder as the script)

#Include UIA.ahk
IsTextSelected()
{
    try if (el := UIA.GetFocusedElement()) && el.IsTextPatternAvailable {
        selectionRange := el.GetSelection()[2]
        If selectionRange.GetText()
            return true
        else
            return false
    }
}
1
V0RT3X On

Don't know if any faster for your need, but perhaps...

F1::
    RetainedClip := ClipboardAll
    Clipboard = 
        Send, ^c
    If Clipboard = 
        MsgBox, , , No text selected., 3
    Else
        MsgBox, , , Text is selected., 3
        Clipboard := RetainedClip
Return