Search code examples
textapplescriptselectiondetect

How can I detect whether something is selected with AppleScript?


I'm using some software called controllermate with allows you to customize the behavior of buttons on a keyboard or mouse. One of the 'building blocks' you can use in a particular function in an apple script. I would like to create a custom behavior for my mouse such that a certain button will execute CMD+C if something that can be copied is currently selected, but otherwise execute a different keyboard shortcut. It seems I will have to use an appleScript in order to determine whether text is selected, but after reading other some other people's solutions online I was unable to figure out how to implement it myself. Thanks for any help.


Solution

  • Here's a solution:

    Put an empty string to the clipboard, do CMD+C, check the clipboard.

    set the clipboard to ""
    tell application "System Events" to keystroke "c" using command down
    delay 0.2
    
    set b to false
    try
        set b to (the clipboard as string) is not ""
    on error -- error when the clipboard contains a custom type (like a copy in the Photos Application)
        set b to true
    end try
    if b then -- the clipboard does not contains an empty string
        -- *** script to execute a different keyboard shortcut ***
        --tell application "System Events" to keystroke someChar using someModifier
    end if