Search code examples
applescriptcalculatorclipboard

How can I copy result from Calculator.app to the clipboard using AppleScript


How do I copy the result of the Calculator.app including decimals.

By defaults is selected, so if you just do a CMD+C it copies it into your clipboard. I got this code from @jweaks

set the clipboard to {?????}

I tried entering many different options but I don't know what I should put.


Solution

  • How do I copy the result of the Calculator.app including decimals.

    set the clipboard to {?????}

    As you already know ⌘C can do it, however, if you want to use a set clipboard to method, then here is one way to go about it:

    Example AppleScript code:

    if not running of application "Calculator" then return
    
    tell application "System Events" to ¬
        set the clipboard to ¬
            (get the value of ¬
                static text 1 of ¬
                group 1 of ¬
                window 1 of ¬
                process "Calculator")
    

    Notes:

    • Does not require Calculator to be frontmost.

    • Does not require the use of keystroke or key code to accomplish the task.

    • Can set the value to a variable instead of the clipboard, if wanting to process it in a different manner.

    The example AppleScript code, shown below, was tested in Script Editor under macOS Catalina and macOS Monterey with Language & Region settings in System Preferences set to English (US) — Primary and worked for me without issue1.

    • 1 Assumes necessary and appropriate settings in System Preferences > Security & Privacy > Privacy have been set/addressed as needed.

    In testing, the Replies pane in Script Editor returned, e.g.,:

    tell application "System Events"
        get value of static text 1 of group 1 of window 1 of process "Calculator"
        --> "6200.549407114624506"
        set the clipboard to "6200.549407114624506"
    end tell
    

    Then when pasting into a document it pasted as: 6200.549407114624506



    Update to address comments

    To address the ensuing comments by sebseb under my answer and specifically…

    Is it possible to run the script every time I hit enter on Calculator? then copy the result.

    Basic vanilla AppleScript is not that intelligent and does not have the ability in of and by itself to understand what one is doing in Calculator and know when one has pressed the enter key to then place the result on the clipboard.

    One would have to use an intermediary, an application like Hammerspoon, where it can wait for the Calculator application being activated/deactivated or its window being focused/unfocused to then enabled/disable trapping the enter key being pressed on the keyboard to then run the script to perform an action to calculate the result by pressing the = key then copy the result to the clipboard.

    This works because pressing the = key in Calculator is equivalent to pressing the enter key, thus enabling trapping the enter key to perform the necessary actions using AppleScript. It quite possibly can be done without using AppleScript and just Lua, the language used by Hammerspoon and its API. However, since I already use various AppleScript scripts in conjunction with Hammerspoon and can easily recycle some existing code I'll present an addendum to the original answer using both methods in Hammerspoon.

    The following example Lua code and API of Hammerspoon is placed in the ~/.hammerspoon/init.lua file.:

        --  Create a hotkey used to trap the enter key and disable it.
        --  It will then be enabled/disabled as Calculator is focused/unfocused
        --  When enabled and the enter key is pressed it runs the AppleScript script.
    
    local applicationCalculatorEnterHotkey = hs.hotkey.bind({}, "return", function()
        local asFile = "/.hammerspoon/Scripts/CalculatorResultToClipboard.applescript"
        local ok, status = hs.osascript.applescriptFromFile(os.getenv("HOME") .. asFile)
        if not ok then              
            msg = "An error occurred running the CalculatorResultToClipboard script."
            hs.notify.new({title="Hammerspoon", informativeText=msg}):send()            
        end
    end)
    applicationCalculatorEnterHotkey:disable()
    
    
        --  One of two methods of watching Calculator.
        --  
        --  The other is below this one and commented out.
    
        --  Initialize a Calculator window filter.
    
    local CalculatorWindowFilter = hs.window.filter.new("Calculator")
    
        --  Subscribe to when the Calculator window is focused/unfocused.
    
    CalculatorWindowFilter:subscribe(hs.window.filter.windowFocused, function()
            --  Enable hotkey when Calculator is focused.
        applicationCalculatorEnterHotkey:enable()
    end)
    CalculatorWindowFilter:subscribe(hs.window.filter.windowUnfocused, function()
            --  Disable hotkey when Calculator is unfocused.
        applicationCalculatorEnterHotkey:disable()
    end)
    
    
            --  Alternate method to wait for Calculator and enable/disable the hotkey.
            --  
            --  Uncomment below method and comment the above method to test between them. Adding the 
            --  multiple line opening '--[[' and closing '--]]' to above method and removed from below,
            --  leaving 'local CalculatorWindowFilter = hs.window.filter.new("Calculator")' uncommented.
    
    --[[    
    
    function applicationCalculatorWatcher(appName, eventType, appObject)
        if (eventType == hs.application.watcher.activated) then
            if (appName == "Calculator") then
                    --  Enable hotkey when Calculator is activated.
                applicationCalculatorEnterHotkey:enable()
            end
        end
        if (eventType == hs.application.watcher.deactivated) then
            if (appName == "Calculator") then
                    --  Disable hotkey when Calculator is deactivated.
                applicationCalculatorEnterHotkey:disable()
            end
        end
    end
    appCalculatorWatcher = hs.application.watcher.new(applicationCalculatorWatcher)
    appCalculatorWatcher:start()
    -- appCalculatorwWatcher:stop()
    
    --]]
    

    The following example AppleScript code is used in conjunction with Hammerspoon and is saved as CalculatorResultToClipboard.applescript in ~/.hammerspoon/Scripts/, and you'll need to create the hierarchical folder structure.

    Example AppleScript code:

    One can use either:

    tell application "Calculator" to activate
    tell application "System Events"
        key code 24
        delay 0.5
        set the theResult to the value of static text 1 of group 1 of window 1 of process "Calculator"
    end tell
    set the clipboard to theResult
    

    Or:

    tell application "Calculator" to activate
    tell application "System Events"
        key code 24
        delay 0.5
        key code 8 using command down
    end tell
    

    To accomplish the task.

    An alternate option, as previously mentioned, is to forgo the use of AppleScript and use the following example Lua code:

    local applicationCalculatorEnterHotkey = hs.hotkey.bind({}, "return", function()
            --  Press the '=' key to finish the calculation.
        hs.eventtap.keyStroke({}, "=")
            --  Copy the result to the clipboard.
        hs.eventtap.keyStroke({"cmd"}, "C")
    end)
    applicationCalculatorEnterHotkey:disable()
    

    This function would be used instead of the same function further above. It replaces the execution of the AppleScript script with keystrokes generated by Hammerspoon to accomplish the same tasks, while using the remaining example Lua code and the API of Hammerspoon already presented.

    Notes:

    With the example Lua code, as coded, the behavior of pressing the enter key is only trapped and modified to trigger the example AppleScript code, or if using the alternate option send Hammerspoon keystrokes, while Calculator has focus. The enter key should work normally in all other applications.

    See my other Hammerspoon related answers for instructions to install it and utilize the information contained herein.

    One in particle is:

    If using Script Editor, the example AppleScript code is saved as Text in the File Format: pop-up menu in the Save dialog box.

    The example Lua code and API of Hammerspoon and AppleScript code, shown directly above, were tested respectively with Hammerspoon and Script Editor under macOS Mojave and macOS Catalina with Language & Region settings in System Preferences set to English (US) — Primary and worked for me without issue1.

    • 1 Assumes necessary and appropriate settings in System Preferences > Security & Privacy > Privacy have been set/addressed as needed.