There are two options that I'm aware of which may meet your needs:
- Use the 1Keyboard app. This allows you to pair your computers via bluetooth and then use 1Keyboard to send the CommandF2 keyboard shortcut. It basically allows you to use one keyboard with multiple devices.
- Use VirtualKVM. This was designed specifically for people wanting to use their iMacs in target display mode, and works especially well in situations where you want to connect a MacBook to the iMac. For example, if you plug your MacBook into your iMac via Thunderbolt, this extention will automatically switch the iMac to Target Display Mode, allowing you to use your iMac as a monitor. It also switches off the Bluetooth on the iMac, freeing up your mouse and keyboard to pair with your MacBook (assuming you're using a bluetooth keyboard and mouse). When you unplug the MacBook, the iMac's Bluetooth will be powered back up and the monitor restored.
The above options should work fine. If you're a more advanced user, you could also check out this Super User question.