Sending Keystrokes to a Window when it Loses Focus I am running virtual machines for testing on a second Space using Virtualbox, and the problem is that when I'm on the primary space, the virtual machine continues to use a lot of CPU time and kills the battery.

Right now I try to remember to manually Pause the virtual machine every time I switch back to my primary space, but that gets tedious and I'd like to do it automatically.

So the question is: 

How can I send the CTRL + CMD + P shortcut key combination to the virtual machine to pause it every time it loses focus, or alternatively whenever I switch back to Space 1.

Ideally it would also send the combination again when I switch to the Space with Virtualbox running on it, but that isn't as important.

[edit]

I've been able to solve the problem using third-party software - Keyboard Maestro triggering the command-line VBoxManage tool and sending a Pause command that way. But there must be a way to do it without paying for software.
A way to trigger it with a global keyboard shortcut (and without having to switch back) is to create a little applescript to do it for you.  I'm not familiar with Virtualbox's windows, so you'll need to modify the below to suit your needs.  You can run it as is, and note that 1) Terminal does NOT take focus when you run this, it stays in the background and 2) when you do switch to terminal, the Inspector will be showing.

tell application "System Events"
  tell process "Terminal"
  click menu item "Show Inspector" of menu "Shell" of menu bar 1
  end tell
end tell


I'm assuming that the Pause VM command will be available from the VB menus, if not, please let me know in the comments where the command lives, and I can update the answer to reflect that.

Once you have the applescript tested, use Automator to create a service: this will let you activate it with a global keyboard shortcut, no need to switch applications or anything.


Launch Automator
New project if it loads an old one, and select "Service"
In the search box enter, "script" to filter the options and double-click "Run Applescript"
Paste the applescript right in there.
Save it, give it a name like "Pause the dang VM", and quit.


Next, to give it a global keyboard shortcut:


Open System Preferences -> Keyboard -> Shortcuts Tab
Select "Services" in the left pane
Scroll to the bottom of the right pane, and you should see your new service
Click "none" to the right of your new service and you can create a shortcut.


So now if you forget, at least it's just a key press instead of a whole application switch around. 

NOTE: you'll need to allow Automator to control the computer in System Preferences -> Security &amp; Privacy -> Privacy -> Accessibility