luaapplescriptautomatorhammerspoon

How to use AppleScript or Lua to do an ALT + TAB after results on the Calculator.app


I use the Calculator.app, and after hitting the ENTER key, I would like it to automatically do an ALT + TAB to go to the previous App I was using: Excel or Firefox or Chrome, ... you name it.

I have the same question for just .lua, but if it can't be done with .lua I'd like to do it with AppleScript or with the Automator.

What's the hot key for TAB in .lua? hammerspoon?

UPDATE:

As user3439894 says, CMD + TAB works fine.

But in my end, the TAB is not released, therefore, I keeps on showing all the open apps. So, I tried to put a RETURN as of the documentation. I also tried ENTER , but non of them work.

hs.eventtap.keyStroke({"cmd"}, "tab")
hs.eventtap.keyStroke({"return"})
-- hs.eventtap.keyStroke({"enter"})

Solution

  • Assuming your are using this in conjunction of one of the answers I gave you back in mid November regarding Calculator, then the modified Lua code below works for me to switch to the previous application when pressing the enter key while in Calculator.

    Example Lua code:

        --  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 presses = then command C.
    
    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")
            --  Bring up the App Switcher.
        hs.eventtap.keyStroke({"cmd"}, "tab")
            --  Act on the selected App in the App Switcher.
            --  This works in testing with Calculator, however
            --  may not work in other applications.
        hs.eventtap.keyStroke({}, "=")  
    end)
    applicationCalculatorEnterHotkey:disable()
    

    Notes:

    I've added two hs.eventtap.keyStroke to the original code with comments.

    Executing hs.eventtap.keyStroke({"cmd"}, "tab") in the Console Hammerspoon does automatically switch to the previous application without showing the App Switcher, however when used in the applicationCalculatorEnterHotkey function it shows the App Switcher as if āŒ˜-Tab has been pressed and the āŒ˜ key not released. This may be a bug, not sure as not enough testing/research into the issue was done as the obvious solution would be to follow up with programmatically pressing the enter key, however that can not be done from within the applicationCalculatorEnterHotkey function because it is already trapping the enter key in Calculator.

    In this particular use case, however this is where hs.eventtap.keyStroke({}, "=") is used to act as if the enter key had been pressed again and is unique to Calculator.