DLL Injection + D3D9 Hook

12/28/2012 16:26 niko_d#1
Hallo elitepvpers,
ich hab mich an [Only registered and activated users can see links. Click Here To Register...] versucht.
Die DLL hab ich einigermaßen hinbekommen. Hier der Code:
Code:
#pragma once
#pragma comment(lib, "d3d9.lib")
#pragma comment(lib, "d3dx9.lib")

#include <windows.h>
#include <cstdio>
#include <d3d9.h>
#include <d3dx9.h>

//Variablen Deklaration
//HRESULT __stdcall EndScene(LPDIRECT3DDEVICE9 pDevice);
typedef HRESULT(__stdcall* EndScene_t)(LPDIRECT3DDEVICE9);
LPDIRECT3DDEVICE9 pDevice;
EndScene_t pEndScene;
DWORD dwDrawIndexedPrimitive;
DWORD dwEndScene;
//--------------------------------------------------------


const D3DCOLOR txtPink = D3DCOLOR_ARGB(255, 255, 0, 255); // Alpha, Rot, Grün, Blau
ID3DXFont *pFont;
LPDIRECT3DTEXTURE9 texPink;
char* charWallhack;

HRESULT GenerateTexture(IDirect3DDevice9 *pD3Ddev, IDirect3DTexture9 **ppD3Dtex, DWORD colour32)
{
	if( FAILED(pD3Ddev->CreateTexture(8, 8, 1, 0, D3DFMT_A4R4G4B4, D3DPOOL_MANAGED,ppD3Dtex, NULL)) )
		return E_FAIL;
	WORD colour16 = ((WORD)((colour32>>28)&0xF)<<12)
					|(WORD)(((colour32>>20)&0xF)<<8)
					|(WORD)(((colour32>>12)&0xF)<<4)
					|(WORD)(((colour32>>4)&0xF)<<0);
	D3DLOCKED_RECT d3dlr;    
	(*ppD3Dtex)->LockRect(0, &d3dlr, 0, 0);
	WORD *pDst16 = (WORD*)d3dlr.pBits;

	for(int xy=0; xy < 8*8; xy++)
		*pDst16++ = colour16;

	(*ppD3Dtex)->UnlockRect(0);
	return S_OK;
}
 

void DrawRect (LPDIRECT3DDEVICE9 Device_t, int X, int Y, int L, int H, D3DCOLOR color)
{
	D3DRECT rect = {X, Y, X+L, Y+H};
	Device_t->Clear(1, &rect, D3DCLEAR_TARGET, color, 0,  0);
}

void DrawFont (int X, int Y, D3DCOLOR Color, char *format, ...)
{
        char buffer[256];
        va_list args; // deswegen: #include <cstdio>
        va_start (args, format);
        vsprintf (buffer,format, args);
                RECT FontRect = { X, Y, X + 120, Y + 16 };
				pFont->DrawText( NULL, (LPCWSTR)buffer, -1, &FontRect, DT_NOCLIP , Color ); // Zeichnen
        va_end (args);
}

HRESULT __stdcall hkEndScene(LPDIRECT3DDEVICE9 pDevice_t)  
{
	if(pDevice == NULL){
		pDevice = pDevice_t;
		GenerateTexture(pDevice, &texPink,txtPink);
	}
	else{
		//DrawFont ( 300, 50, txtPink, "Wallhack %s", charWallhack );
		DrawRect ( pDevice, 10, 10, 200, 200, txtPink);
	}
	return pEndScene(pDevice);
}


//------------------------------------------------------------------------------------------------
//Detour function von Game Deception
void *DetourFunc(BYTE *src, const BYTE *dst, const int len) // credits to gamedeception
{
	BYTE *jmp = (BYTE*)malloc(len+5);
	DWORD dwback;
	VirtualProtect(src, len, PAGE_READWRITE, &dwback);
	memcpy(jmp, src, len); jmp += len;
	jmp[0] = 0xE9;
	*(DWORD*)(jmp+1) = (DWORD)(src+len - jmp) - 5;
	src[0] = 0xE9;
	*(DWORD*)(src+1) = (DWORD)(dst - src) - 5;
	VirtualProtect(src, len, dwback, &dwback);
	return (jmp-len);
}

bool bDataCompare(const BYTE* pData, const BYTE* bMask, const char* szMask)
{
    for(;*szMask;++szMask,++pData,++bMask)
        if(*szMask=='x' && *pData!=*bMask ) 
            return false;
    return (*szMask) == NULL;
} 
DWORD dwFindPattern(DWORD dwAddress,DWORD dwLen,BYTE *bMask,char * szMask)
{
    for(DWORD i=0; i < dwLen; i++)
        if( bDataCompare( (BYTE*)( dwAddress+i ),bMask,szMask) )
            return (DWORD)(dwAddress+i);
    
    return 0;
}

//Um sicher zu gehen, dass die dll geladen wurde
void InitHook()
{        HMODULE hModule = NULL;
        while( !hModule )
        {
                hModule = GetModuleHandleA( "d3d9.dll" ); // Handle zur DLL holen
                Sleep( 100 ); // 100ms warten
        }

		DWORD* VTableStart = 0;                  
		DWORD FoundByGordon = dwFindPattern((DWORD)hModule, 0x128000,
		(PBYTE)"\xC7\x06\x00\x00\x00\x00\x89\x86\x00\x00\x00\x00\x89\x86", "xx????xx????xx");
		if(FoundByGordon != 0){
			memcpy(&VTableStart, (void*)(FoundByGordon+2), 4);
			dwDrawIndexedPrimitive = (DWORD)VTableStart[82]; // für mehr: blick in die d3d9.h werfen!
			dwEndScene = (DWORD)VTableStart[42];

			pEndScene = ( EndScene_t )DetourFunc((PBYTE) 0x73E4412C,(PBYTE)hkEndScene, 5);
			if(pDevice != NULL && pFont != NULL){
				//D3DXCreateFont(pDevice, 14, 0, FW_NORMAL, 1, 0, DEFAULT_CHARSET,  OUT_DEFAULT_PRECIS, ANTIALIASED_QUALITY, DEFAULT_PITCH | FF_DONTCARE, (LPCWSTR)"Arial", &pFont ); 
				GenerateTexture(pDevice, &texPink,txtPink);
			}
		}
		else{
			MessageBox(NULL, TEXT("No Pattern found"), NULL, MB_OK);
		}
}


//Die Main
int WINAPI DllMain(HINSTANCE hInst,DWORD reason,LPVOID reserved)
{
        switch(reason)
        {
        case DLL_PROCESS_ATTACH:
                CreateThread(0, 0, (LPTHREAD_START_ROUTINE) InitHook, 0, 0, 0);
                break;
        }
        return true;
}
Der DLL Injector in C#:
Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;

namespace DLLInjector
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        [DllImport("kernel32")]
        public static extern IntPtr CreateRemoteThread(
          IntPtr hProcess,
          IntPtr lpThreadAttributes,
          uint dwStackSize,
          UIntPtr lpStartAddress, // raw Pointer into remote process
          IntPtr lpParameter,
          uint dwCreationFlags,
          out IntPtr lpThreadId
        );

        [DllImport("kernel32.dll")]
        public static extern IntPtr OpenProcess(
            UInt32 dwDesiredAccess,
            Int32 bInheritHandle,
            Int32 dwProcessId
            );

        [DllImport("kernel32.dll")]
        public static extern Int32 CloseHandle(
        IntPtr hObject
        );

        [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)]
        static extern bool VirtualFreeEx(
            IntPtr hProcess,
            IntPtr lpAddress,
            UIntPtr dwSize,
            uint dwFreeType
            );

        [DllImport("kernel32.dll", CharSet = CharSet.Ansi, ExactSpelling = true)]
        public static extern UIntPtr GetProcAddress(
            IntPtr hModule,
            string procName
            );

        [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)]
        static extern IntPtr VirtualAllocEx(
            IntPtr hProcess,
            IntPtr lpAddress,
            uint dwSize,
            uint flAllocationType,
            uint flProtect
            );

        [DllImport("kernel32.dll")]
        static extern bool WriteProcessMemory(
            IntPtr hProcess,
            IntPtr lpBaseAddress,
            string lpBuffer,
            UIntPtr nSize,
            out IntPtr lpNumberOfBytesWritten
        );

        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        public static extern IntPtr GetModuleHandle(
            string lpModuleName
            );

        [DllImport("kernel32", SetLastError = true, ExactSpelling = true)]
        internal static extern Int32 WaitForSingleObject(
            IntPtr handle,
            Int32 milliseconds
            );

        public Int32 GetProcessId(String proc)
        {
            Process[] ProcList;
            ProcList = Process.GetProcessesByName(proc);
            return ProcList[0].Id;
        }

        public void InjectDLL(IntPtr hProcess, String strDLLName)
        {
            IntPtr bytesout;

            // Length of string containing the DLL file name +1 byte padding
            Int32 LenWrite = strDLLName.Length + 1;
            // Allocate memory within the virtual address space of the target process
            IntPtr AllocMem = (IntPtr)VirtualAllocEx(hProcess, (IntPtr)null, (uint)LenWrite, 0x1000, 0x40); //allocation pour WriteProcessMemory

            // Write DLL file name to allocated memory in target process
            WriteProcessMemory(hProcess, AllocMem, strDLLName, (UIntPtr)LenWrite, out bytesout);
            // Function pointer "Injector"
            UIntPtr Injector = (UIntPtr)GetProcAddress(GetModuleHandle("kernel32.dll"), "LoadLibraryA");

            if (Injector == null)
            {
                MessageBox.Show(" Injector Error! \n ");
                // return failed
                return;
            }

            // Create thread in target process, and store handle in hThread
            IntPtr hThread = (IntPtr)CreateRemoteThread(hProcess, (IntPtr)null, 0, Injector, AllocMem, 0, out bytesout);
            // Make sure thread handle is valid
            if (hThread == null)
            {
                //incorrect thread handle ... return failed
                MessageBox.Show(" hThread [ 1 ] Error! \n ");
                return;
            }
            // Time-out is 10 seconds...
            int Result = WaitForSingleObject(hThread, 10 * 1000);
            // Check whether thread timed out...
            if (Result == 0x00000080L || Result == 0x00000102L || Result == 0xFFFFFFFF)
            {
                /* Thread timed out... */
                MessageBox.Show(" hThread [ 2 ] Error! \n ");
                // Make sure thread handle is valid before closing... prevents crashes.
                if (hThread != null)
                {
                    //Close thread in target process
                    CloseHandle(hThread);
                }
                return;
            }
            // Sleep thread for 1 second
            Thread.Sleep(1000);
            // Clear up allocated space ( Allocmem )
            VirtualFreeEx(hProcess, AllocMem, (UIntPtr)0, 0x8000);
            // Make sure thread handle is valid before closing... prevents crashes.
            if (hThread != null)
            {
                //Close thread in target process
                CloseHandle(hThread);
            }
            // return succeeded
            return;
        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            String strDLLName = textBox2.Text;
            String strProcessName = textBox1.Text;

            Int32 ProcID = GetProcessId(strProcessName);
            if (ProcID >= 0)
            {
                IntPtr hProcess = (IntPtr)OpenProcess(0x1F0FFF, 1, ProcID);
                if (hProcess == null)
                {
                    MessageBox.Show("OpenProcess() Failed!");
                    return;
                }
                else
                    InjectDLL(hProcess, strDLLName);
            }
        }
    }
}
Da das alles eher mit c&p als mit Verstand gemacht wurde, läuft das ganze natürlich nicht und ich hab einige Fragen dazu:

Zur InjectDLL:
Auf welches Signal wartet WaitForSingleObject? Sobald ich die DLL Injection starte stürzt das DirectX9 Programm (Ein Sample aus dem SDK) ab. Kurz darauf gibt es die Fehlermeldung "hTreahd[2] Error".

Zum D3DHook:
Da versteh ich recht wenig. Vor allem die Detours Funktion nicht.
So wie ich es verstanden hab, soll sie die Startadresse der EndScene()
Funktion zurückgeben. Aber was soll ich damit anstellen?

Ich hab beides auf einem 64Bit Rechner für 32Bit Systeme kompiliert.
Es läuft auf keinem von beiden, egal ob ich das Pattern von Gordon oder
eine statische Adresse benutze um die EndScene zu finden..
12/28/2012 17:03 xNopex#2
Lalalala:
[Only registered and activated users can see links. Click Here To Register...]

Remarks lesen. Und logisch denken.


Die Detour Funktion gibt dir die Adresse des Trampolins zurück.
12/28/2012 17:43 niko_d#3
Quote:
Originally Posted by xNopex View Post
Lalalala:
[Only registered and activated users can see links. Click Here To Register...]

Remarks lesen. Und logisch denken.


Die Detour Funktion gibt dir die Adresse des Trampolins zurück.
Danke für die schnelle Antwort.
Hab dummerweise nicht weit genug runtergescrollt XD
Die Antwort hab ich in den Remarks von [Only registered and activated users can see links. Click Here To Register...] gefunden (ohne logisch nachzudenken :P).
Code:
When a thread terminates, the thread object attains a signaled state, which satisfies the threads that are waiting for the object.
The thread object remains in the system until the thread has terminated and all handles to it are closed through a call to CloseHandle.
Zu der Detours-Funktion: Trampolin sagt mir nicht viel:(
Ich geh mal stark davon aus es ist die Rücksprungadresse zu der original EndScene() Funktion. Ich weiß jetzt noch immer nicht was ich damit machen soll. Die Detours-Funktion erledigt doch den Rücksprung oder nicht?

Bitte nehmt mir das nicht übel, aber das ist das 1. mal dass ich mit der
WinAPI und DirectX arbeite. Programmiere normalerweise in Java.
12/28/2012 18:00 MrSm!th#4
Ich rate zu Microsoft Detours anstatt dieser GD Funktion.
12/28/2012 18:21 Dr. Coxxy#5
kannst dir auch mal das tut hier ansehen:
[Only registered and activated users can see links. Click Here To Register...]
12/28/2012 23:17 niko_d#6
Thx das Tutorial hat geholfen.
Btw. der DLL-Injector den ich oben gepostet habe funktioniert nicht, aber
damit beschäftige ich mich später.
01/01/2013 03:56 SonyRazzer#7
Quote:
Originally Posted by niko_d View Post
Hallo elitepvpers,
ich hab mich an [Only registered and activated users can see links. Click Here To Register...] versucht.
Die DLL hab ich einigermaßen hinbekommen. Hier der Code:
Code:
#pragma once
#pragma comment(lib, "d3d9.lib")
#pragma comment(lib, "d3dx9.lib")

#include <windows.h>
#include <cstdio>
#include <d3d9.h>
#include <d3dx9.h>

//Variablen Deklaration
//HRESULT __stdcall EndScene(LPDIRECT3DDEVICE9 pDevice);
typedef HRESULT(__stdcall* EndScene_t)(LPDIRECT3DDEVICE9);
LPDIRECT3DDEVICE9 pDevice;
EndScene_t pEndScene;
DWORD dwDrawIndexedPrimitive;
DWORD dwEndScene;
//--------------------------------------------------------


const D3DCOLOR txtPink = D3DCOLOR_ARGB(255, 255, 0, 255); // Alpha, Rot, Grün, Blau
ID3DXFont *pFont;
LPDIRECT3DTEXTURE9 texPink;
char* charWallhack;

HRESULT GenerateTexture(IDirect3DDevice9 *pD3Ddev, IDirect3DTexture9 **ppD3Dtex, DWORD colour32)
{
	if( FAILED(pD3Ddev->CreateTexture(8, 8, 1, 0, D3DFMT_A4R4G4B4, D3DPOOL_MANAGED,ppD3Dtex, NULL)) )
		return E_FAIL;
	WORD colour16 = ((WORD)((colour32>>28)&0xF)<<12)
					|(WORD)(((colour32>>20)&0xF)<<8)
					|(WORD)(((colour32>>12)&0xF)<<4)
					|(WORD)(((colour32>>4)&0xF)<<0);
	D3DLOCKED_RECT d3dlr;    
	(*ppD3Dtex)->LockRect(0, &d3dlr, 0, 0);
	WORD *pDst16 = (WORD*)d3dlr.pBits;

	for(int xy=0; xy < 8*8; xy++)
		*pDst16++ = colour16;

	(*ppD3Dtex)->UnlockRect(0);
	return S_OK;
}
 

void DrawRect (LPDIRECT3DDEVICE9 Device_t, int X, int Y, int L, int H, D3DCOLOR color)
{
	D3DRECT rect = {X, Y, X+L, Y+H};
	Device_t->Clear(1, &rect, D3DCLEAR_TARGET, color, 0,  0);
}

void DrawFont (int X, int Y, D3DCOLOR Color, char *format, ...)
{
        char buffer[256];
        va_list args; // deswegen: #include <cstdio>
        va_start (args, format);
        vsprintf (buffer,format, args);
                RECT FontRect = { X, Y, X + 120, Y + 16 };
				pFont->DrawText( NULL, (LPCWSTR)buffer, -1, &FontRect, DT_NOCLIP , Color ); // Zeichnen
        va_end (args);
}

HRESULT __stdcall hkEndScene(LPDIRECT3DDEVICE9 pDevice_t)  
{
	if(pDevice == NULL){
		pDevice = pDevice_t;
		GenerateTexture(pDevice, &texPink,txtPink);
	}
	else{
		//DrawFont ( 300, 50, txtPink, "Wallhack %s", charWallhack );
		DrawRect ( pDevice, 10, 10, 200, 200, txtPink);
	}
	return pEndScene(pDevice);
}


//------------------------------------------------------------------------------------------------
//Detour function von Game Deception
void *DetourFunc(BYTE *src, const BYTE *dst, const int len) // credits to gamedeception
{
	BYTE *jmp = (BYTE*)malloc(len+5);
	DWORD dwback;
	VirtualProtect(src, len, PAGE_READWRITE, &dwback);
	memcpy(jmp, src, len); jmp += len;
	jmp[0] = 0xE9;
	*(DWORD*)(jmp+1) = (DWORD)(src+len - jmp) - 5;
	src[0] = 0xE9;
	*(DWORD*)(src+1) = (DWORD)(dst - src) - 5;
	VirtualProtect(src, len, dwback, &dwback);
	return (jmp-len);
}

bool bDataCompare(const BYTE* pData, const BYTE* bMask, const char* szMask)
{
    for(;*szMask;++szMask,++pData,++bMask)
        if(*szMask=='x' && *pData!=*bMask ) 
            return false;
    return (*szMask) == NULL;
} 
DWORD dwFindPattern(DWORD dwAddress,DWORD dwLen,BYTE *bMask,char * szMask)
{
    for(DWORD i=0; i < dwLen; i++)
        if( bDataCompare( (BYTE*)( dwAddress+i ),bMask,szMask) )
            return (DWORD)(dwAddress+i);
    
    return 0;
}

//Um sicher zu gehen, dass die dll geladen wurde
void InitHook()
{        HMODULE hModule = NULL;
        while( !hModule )
        {
                hModule = GetModuleHandleA( "d3d9.dll" ); // Handle zur DLL holen
                Sleep( 100 ); // 100ms warten
        }

		DWORD* VTableStart = 0;                  
		DWORD FoundByGordon = dwFindPattern((DWORD)hModule, 0x128000,
		(PBYTE)"\xC7\x06\x00\x00\x00\x00\x89\x86\x00\x00\x00\x00\x89\x86", "xx????xx????xx");
		if(FoundByGordon != 0){
			memcpy(&VTableStart, (void*)(FoundByGordon+2), 4);
			dwDrawIndexedPrimitive = (DWORD)VTableStart[82]; // für mehr: blick in die d3d9.h werfen!
			dwEndScene = (DWORD)VTableStart[42];

			pEndScene = ( EndScene_t )DetourFunc((PBYTE) 0x73E4412C,(PBYTE)hkEndScene, 5);
			if(pDevice != NULL && pFont != NULL){
				//D3DXCreateFont(pDevice, 14, 0, FW_NORMAL, 1, 0, DEFAULT_CHARSET,  OUT_DEFAULT_PRECIS, ANTIALIASED_QUALITY, DEFAULT_PITCH | FF_DONTCARE, (LPCWSTR)"Arial", &pFont ); 
				GenerateTexture(pDevice, &texPink,txtPink);
			}
		}
		else{
			MessageBox(NULL, TEXT("No Pattern found"), NULL, MB_OK);
		}
}


//Die Main
int WINAPI DllMain(HINSTANCE hInst,DWORD reason,LPVOID reserved)
{
        switch(reason)
        {
        case DLL_PROCESS_ATTACH:
                CreateThread(0, 0, (LPTHREAD_START_ROUTINE) InitHook, 0, 0, 0);
                break;
        }
        return true;
}
Der DLL Injector in C#:
Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;

namespace DLLInjector
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        [DllImport("kernel32")]
        public static extern IntPtr CreateRemoteThread(
          IntPtr hProcess,
          IntPtr lpThreadAttributes,
          uint dwStackSize,
          UIntPtr lpStartAddress, // raw Pointer into remote process
          IntPtr lpParameter,
          uint dwCreationFlags,
          out IntPtr lpThreadId
        );

        [DllImport("kernel32.dll")]
        public static extern IntPtr OpenProcess(
            UInt32 dwDesiredAccess,
            Int32 bInheritHandle,
            Int32 dwProcessId
            );

        [DllImport("kernel32.dll")]
        public static extern Int32 CloseHandle(
        IntPtr hObject
        );

        [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)]
        static extern bool VirtualFreeEx(
            IntPtr hProcess,
            IntPtr lpAddress,
            UIntPtr dwSize,
            uint dwFreeType
            );

        [DllImport("kernel32.dll", CharSet = CharSet.Ansi, ExactSpelling = true)]
        public static extern UIntPtr GetProcAddress(
            IntPtr hModule,
            string procName
            );

        [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)]
        static extern IntPtr VirtualAllocEx(
            IntPtr hProcess,
            IntPtr lpAddress,
            uint dwSize,
            uint flAllocationType,
            uint flProtect
            );

        [DllImport("kernel32.dll")]
        static extern bool WriteProcessMemory(
            IntPtr hProcess,
            IntPtr lpBaseAddress,
            string lpBuffer,
            UIntPtr nSize,
            out IntPtr lpNumberOfBytesWritten
        );

        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        public static extern IntPtr GetModuleHandle(
            string lpModuleName
            );

        [DllImport("kernel32", SetLastError = true, ExactSpelling = true)]
        internal static extern Int32 WaitForSingleObject(
            IntPtr handle,
            Int32 milliseconds
            );

        public Int32 GetProcessId(String proc)
        {
            Process[] ProcList;
            ProcList = Process.GetProcessesByName(proc);
            return ProcList[0].Id;
        }

        public void InjectDLL(IntPtr hProcess, String strDLLName)
        {
            IntPtr bytesout;

            // Length of string containing the DLL file name +1 byte padding
            Int32 LenWrite = strDLLName.Length + 1;
            // Allocate memory within the virtual address space of the target process
            IntPtr AllocMem = (IntPtr)VirtualAllocEx(hProcess, (IntPtr)null, (uint)LenWrite, 0x1000, 0x40); //allocation pour WriteProcessMemory

            // Write DLL file name to allocated memory in target process
            WriteProcessMemory(hProcess, AllocMem, strDLLName, (UIntPtr)LenWrite, out bytesout);
            // Function pointer "Injector"
            UIntPtr Injector = (UIntPtr)GetProcAddress(GetModuleHandle("kernel32.dll"), "LoadLibraryA");

            if (Injector == null)
            {
                MessageBox.Show(" Injector Error! \n ");
                // return failed
                return;
            }

            // Create thread in target process, and store handle in hThread
            IntPtr hThread = (IntPtr)CreateRemoteThread(hProcess, (IntPtr)null, 0, Injector, AllocMem, 0, out bytesout);
            // Make sure thread handle is valid
            if (hThread == null)
            {
                //incorrect thread handle ... return failed
                MessageBox.Show(" hThread [ 1 ] Error! \n ");
                return;
            }
            // Time-out is 10 seconds...
            int Result = WaitForSingleObject(hThread, 10 * 1000);
            // Check whether thread timed out...
            if (Result == 0x00000080L || Result == 0x00000102L || Result == 0xFFFFFFFF)
            {
                /* Thread timed out... */
                MessageBox.Show(" hThread [ 2 ] Error! \n ");
                // Make sure thread handle is valid before closing... prevents crashes.
                if (hThread != null)
                {
                    //Close thread in target process
                    CloseHandle(hThread);
                }
                return;
            }
            // Sleep thread for 1 second
            Thread.Sleep(1000);
            // Clear up allocated space ( Allocmem )
            VirtualFreeEx(hProcess, AllocMem, (UIntPtr)0, 0x8000);
            // Make sure thread handle is valid before closing... prevents crashes.
            if (hThread != null)
            {
                //Close thread in target process
                CloseHandle(hThread);
            }
            // return succeeded
            return;
        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            String strDLLName = textBox2.Text;
            String strProcessName = textBox1.Text;

            Int32 ProcID = GetProcessId(strProcessName);
            if (ProcID >= 0)
            {
                IntPtr hProcess = (IntPtr)OpenProcess(0x1F0FFF, 1, ProcID);
                if (hProcess == null)
                {
                    MessageBox.Show("OpenProcess() Failed!");
                    return;
                }
                else
                    InjectDLL(hProcess, strDLLName);
            }
        }
    }
}
Da das alles eher mit c&p als mit Verstand gemacht wurde, läuft das ganze natürlich nicht und ich hab einige Fragen dazu:

Zur InjectDLL:
Auf welches Signal wartet WaitForSingleObject? Sobald ich die DLL Injection starte stürzt das DirectX9 Programm (Ein Sample aus dem SDK) ab. Kurz darauf gibt es die Fehlermeldung "hTreahd[2] Error".

Zum D3DHook:
Da versteh ich recht wenig. Vor allem die Detours Funktion nicht.
So wie ich es verstanden hab, soll sie die Startadresse der EndScene()
Funktion zurückgeben. Aber was soll ich damit anstellen?

Ich hab beides auf einem 64Bit Rechner für 32Bit Systeme kompiliert.
Es läuft auf keinem von beiden, egal ob ich das Pattern von Gordon oder
eine statische Adresse benutze um die EndScene zu finden..
Du kannst mich Skype [Cribfex3] gerne mal hinzufügen, kann dir viel zum Hooking beibringen ( Detours, .. )