title: Hooking DirectX EndScene from an injected DLL
body: <p>I want to detour <code>EndScene</code> from an arbitrary DirectX 9 application to create a small overlay. As an example, you could take the frame counter overlay of FRAPS, which is shown in games when activated.</p>
  
  <p>I know the following methods to do this:</p>
  
  <ol>
  <li><p>Creating a new <code>d3d9.dll</code>, which is then copied to the games path. Since the current folder is searched first, before going to system32 etc., my modified DLL gets loaded, executing my additional code.<br>
  <strong>Downside:</strong> You have to put it there before you start the game.</p></li>
  <li><p>Same as the first method, but replacing the DLL in system32 directly.<br>
  <strong>Downside:</strong> You cannot add game specific code. You cannot exclude applications where you don't want your DLL to be loaded.</p></li>
  <li><p>Getting the EndScene offset directly from the DLL using tools like IDA Pro 4.9 Free. Since the DLL gets loaded as is, you can just add this offset to the DLL starting address, when it is mapped to the game, to get the actual offset, and then hook it.<br>
  <strong>Downside:</strong> The offset is not the same on every system.</p></li>
  <li><p>Hooking <code>Direct3DCreate9</code> to get the D3D9, then hooking <code>D3D9-&gt;CreateDevice</code> to get the device pointer, and then hooking <code>Device-&gt;EndScene</code> through the virtual table.<br>
  <strong>Downside:</strong> The DLL cannot be injected, when the process is already running. You have to start the process with the <code>CREATE_SUSPENDED</code> flag to hook the initial <code>Direct3DCreate9</code>.</p></li>
  <li><p>Creating a new Device in a new window, as soon as the DLL gets injected. Then, getting the <code>EndScene</code> offset from this device and hooking it, resulting in a hook for the device which is used by the game.<br>
  <strong>Downside:</strong> as of some information I have read, creating a second device may interfere with the existing device, and it may bug with windowed vs. fullscreen mode etc.</p></li>
  <li><p>Same as the third method. However, you'll do a pattern scan to get <code>EndScene</code>.<br>
  <strong>Downside:</strong> doesn't look that reliable.</p></li>
  </ol>
  
  <p>How can I hook <code>EndScene</code> from an injected DLL, which may be loaded when the game is already running, without having to deal with different <em>d3d9.dll</em>'s on other systems, and with a method which is reliable? How does FRAPS for example perform it's DirectX hooks?
  The DLL should not apply to all games, just to specific processes where I inject it via <code>CreateRemoteThread</code>.</p>