Run script on screen lock in KDE

On KDE and some other Desktop Environments, you can listen on dbus for the interface org.freedesktop.ScreenSaver.

A script to do this would look like this:

dbus-monitor --session "type='signal',interface='org.freedesktop.ScreenSaver'" |
  while read x; do
    case "$x" in 
      # You can call your desired script in the following line instead of the echo:
      *"boolean true"*) echo SCREEN_LOCKED;;
      *"boolean false"*) echo SCREEN_UNLOCKED;;  
    esac
  done

Please also see this question for more information.


It might depend on which version of KDE you're running, but if you've got a Notifications Entry in System Settings, then you can use the Screensaver controls to run scripts on both screen lock and unlock.

KDE Notifications System Settings Module


One workaround I can think of is (if you normally use a keyboard shortcut to lock) to rebind the keyboard shortcut from lock to instead execute your script, then locking the session, which can be achieved using this command in your script:

qdbus org.freedesktop.ScreenSaver /ScreenSaver Lock

However, I'm not on kde, so can't test it.

If you don't use a keyboard shortcut, I think it will be harder to do this. One possible method is forking the locking program to look for a script and execute it.