Search code examples
macosapplescriptvoiceover

Applescript to "start Dictation" and "stop Dictation" depending on menu


I have on Applescript to start and another one to stop Dictation. I tried to run them together and it only starts Dictation but does not stop it. I tried the key code way but this script is to be used with VoiceOver and that method does not work. Is there a way to have this script check if start/stop is ready and to act accordingly?

    tell application "System Events"
        tell (get first process whose frontmost is true)
           tell menu bar 1
                tell menu bar item "Edit"
                    tell menu 1
                        click menu item "Start Dictation"
                    end tell
                end tell
            end tell
        end tell
    end tell
    tell application "System Events"
        tell (get first process whose frontmost is true)
            tell menu bar 1
                tell menu bar item "Edit"
                    tell menu 1
                        click menu item "Stop Dictation"
                    end tell
                end tell
            end tell
        end tell
    end tell

Solution

  • You can use the exists command

    tell application "System Events"
        tell (get first process whose frontmost is true)
            tell menu 1 of menu bar item "Edit" of menu bar 1
                if exists of menu item "Start Dictation" then
                    click menu item "Start Dictation"
                else if exists of menu item "Stop Dictation" then
                    click menu item "Stop Dictation"
                end if
            end tell
        end tell
    end tell
    

    --

    Or you can use a word in the name of the menu, like this:

    tell application "System Events"
        tell (get first process whose frontmost is true)
            tell menu 1 of menu bar item "Edit" of menu bar 1
                click (first menu item whose name contains " Dictation") -- start or stop
            end tell
        end tell
    end tell