iMac Target Display Mode
Have you tried all the  steps recommended by Apple?

Use Target Display Mode

Follow these steps to start using your iMac as a display:

1   Make sure that your iMac is turned on, and the other Mac is logged in to a macOS user account.
2   Connect the Mini DisplayPort or Thunderbolt cable between the two computers.
3   Press Command-F2 on the keyboard of the iMac that you want to use as a display.


After you press Command-F2, your iMac displays the desktop from the connected Mac.

If Command-F2 doesn't work

If your iMac doesn't switch to Target Display Mode when you press Command-F2, check these things:

•   Make sure that the iMac you're trying to use as a display supports Target Display Mode. 
•   Target Display Mode works only when your primary Mac is logged in to a macOS user account. For example, if your first Mac is at the FileVault login screen, pressing Command-F2 on your iMac does not enable Target Display Mode. You must first log in to your Mac (using a regular display, if necessary) before you can use an iMac in Target Display Mode.
•   Make sure that you're pressing Command-F2 on the keyboard that's connected to the iMac you want to use as a display.
•   In Keyboard System Preferences, if the checkbox is enabled for "Use all F1, F2, etc. keys as standard function keys," the key combination changes to Command-Fn-F2.
•   Make sure that your Mini DisplayPort or Thunderbolt cable is connected to both computers.
•   If you're currently logged in on the iMac you want to use as a display, try logging out to return to the login window. Then press Command-F2 again.
•   Some older Apple keyboards and third-party keyboards might not allow Command-F2 to toggle display modes. If this happens, use the keyboard that came with your iMac to toggle Target Display Mode on and off. 
•   If your iMac is currently started up in Windows, it won't enter Target Display Mode. Target Display Mode isn't supported in Boot Camp.