Apple - Move focus to another display with keyboard

Nevermind, I found an app which does it - Amethyst. I've been looking for something like that for ages


Summary:

  1. Install hammerspoon
  2. Copy the following code into init.lua and run hammerspoon
  3. Press Cmd+1 to toggle between screens

For people who are looking for another solution to this, consider using hammerspoon (which is a great application that lets you write scripts for automating osx using lua). I've included the following code in my init.lua file to implement screen switching upon pressing Cmd+1.

local function focus_other_screen() -- focuses the other screen 
   local screen = hs.mouse.getCurrentScreen()
   local nextScreen = screen:next()
   local rect = nextScreen:fullFrame()
   local center = hs.geometry.rectMidPoint(rect)
   hs.mouse.setAbsolutePosition(center)
end 

function get_window_under_mouse() -- from https://gist.github.com/kizzx2/e542fa74b80b7563045a 
   local my_pos = hs.geometry.new(hs.mouse.getAbsolutePosition())
   local my_screen = hs.mouse.getCurrentScreen()
   return hs.fnutils.find(hs.window.orderedWindows(), function(w)
                 return my_screen == w:screen() and my_pos:inside(w:frame())
   end)
end

function activate_other_screen()
   focus_other_screen() 
   local win = get_window_under_mouse() 
   -- now activate that window 
   win:focus() 
end 

hs.hotkey.bind({"cmd"}, "1", function() -- does the keybinding
      activate_other_screen()
end)

This works by moving the mouse to the other screen, then focusing the application which is directly under the mouse. The code is in lua. Please see hammerspoon for more details.