Switch to Target Display Mode without keyboard
Solution 1:
I found a way to do it with an old, white apple keyboard, haven't tested with others but it might work.
I used a tool called Karabiner from https://pqrs.org/osx/karabiner/. When you install it, enable following options to get Command + F2 to work:
F1..F12 to Functional Keys (Brightness Adjust, Music Control, etc)
- F1,F2 to Brightness Adjust
--- F1 to Brightness Down
--- F2 to Brightness Up
After enabling this option, hit Command + F2 having previously connected your macbook using thunderbolt cable. If you're lucky you'll have a new external display working!
Solution 2:
VirtualKVM will allow you to use your "iMac as a monitor for [your] Macbook". This is super easy and free.
Solution 3:
I was in that situation some time ago. The only way that seems to work without issuing the shortcut with Apple keyboard I found was this in Logitech forums.
I have successfully implemented what I believe is a reasonable workaround. Here's what I did...
Purchased and installed Keyboard Maestro from Stairways Software.
Within Keyboard Maestro I created a new Macro in the Global Macro Group.
For "Triggered by any of the following:" I selected "This device key:" and then hit the mute button (i.e. F10) on my Logitech keyboard. Keyboard Maestro correctly captured this as "USB Receiver Mute".
For "Will execute the following actions:" I had Keyboard Maestro record my keystrokes and then I hit ;⌘-F2 USING MY APPLE KEYBOARD. Keyboard Maestro captured this as ⌘-? (I'm sure the ? is just a place holder). It looks odd, but it works.
Now when I hit the mute button (F10) I can enter AND EXIT Target Display Mode from my Logitech keyboard.
I originally tried another key (F15), but that didn't work for me. It allowed me to enter, but not exit, Target Display Mode. I suspect that this is due to the fact that your Mac ignores most all of the keys on the keyboard when in Target Display Mode. However, I knew it still "listened" to the keys that control music playback. I selected mute as it was the least offensive to use. I haven't tried any others yet.
But, this method as the author says in his following post, have a really nasty disadvantage:
Turns out the solution isn't perfect. After I took the batteries out of my Apple wireless keyboard, the mute/F10 trick on the Logitech keyboard stopped working. So, now I have the Apple wireless keyboard turned on, but not in use - the mute/F10 trick on the Logitech keyboard works again.
So, It's a pity, but the best method is to maintain and use the Apple keyboard.