Keep dual screen active with MBP and iMac, after hibernation/sleep I have an older iMac (2009) as a second monitor for a MacbookPro (2015). Both are running El Capitan. By hooking up a thunderbolt cable I can activate the second monitor feature using Cmd+F2 just fine. I only have one (wired) keyboard, so once activated I pull out the plug from the iMac into the MBP. 

However, a couple of times a day I leave my system and it'll go into energy saving or hibernation. Afterwards, the dual monitor link is broken. I have to switch the keyboard from MBP => iMac, press Cmd+F2 and replug the cable back into the MBP.

It's kind of a nuisance really. Is there a neat way to prevent the "link" from breaking when the system goes to sleep?

Of course I'm not really interested in disabling sleep mode entirely, nor using a tool like caffeine for this purpose.
You are probably best served by this app here:

https://github.com/duanefields/VirtualKVM

Download here: https://github.com/duanefields/VirtualKVM/releases

Basically "Automatically toggles Bluetooth and Target Display Mode when you connect a Macbook to your iMac via Thunderbolt."