Thursday, October 25, 2012

How to pause Windows Media Player or Spotify when locking Windows with AutoHotkey

I'm beginning to use AutoHotkey to automate mundane mouse clicks with keyboard shortcuts and thought I would share how to pause either Windows Media Player (WMP) or Spotify when locking Windows with a couple of keystrokes from any application instead of having to switch context to the player and select pause manually. The following example can be added to your .AHK script to give action to the Windows-S keystroke and the Pause key.

When pressing Windows-S, this will send the pause key (Ctrl-P for WMP and Space for Spotify) to either WMP or Spotify if they are running. When using this, only have either WMP OR Spotify running but not both otherwise one will pause and the other will unpause when you lock the PC. The script can be split to map to two different keys (one for each of WMP and Spotify) but I like the convenience of only having to have one shortcut for both and I'm not usually running both programs at the same time. If either program is already running but paused when deciding to lock the PC, just use the regular Windows-L to lock instead otherwise the player will start playing.

The script also overrides the Pause key so you can pause either WMP or Spotify from any program without having to switch context.


#s::
{
 DetectHiddenWindows, On
 ControlSend, ahk_parent, {Space}, ahk_class SpotifyMainWindow
 ControlSend, ahk_parent, ^{p}, ahk_class WMPlayerApp
 DetectHiddenWindows, Off
 Run, % "rundll32.exe user32.dll,LockWorkStation"ss
 return
}

Pause::
{
 DetectHiddenWindows, On
 ControlSend, ahk_parent, {Space}, ahk_class SpotifyMainWindow
 ControlSend, ahk_parent, ^{p}, ahk_class WMPlayerApp
 DetectHiddenWindows, Off
 return
}