Option Explicit
On Error goto error ' just to cover our ass if there is an unexpected error.
Public Type SECURITY_ATTRIBUTES
nLength As Long
lpSecurityDescriptor As Long
bInheritHandle As Long
End Type
Public SA as SECURITY_ATTRIBUTES
Public Const PAGE_READWRITE as long = &h4
Public Const MEM_COMMIT as long = &h1000
Public Const MEM_RELEASE as long = &h8000
Public Const PROCESS_ALL_ACCESS As Long = (STANDARD_RIGHTS_REQUIRED Or SYNCHRONIZE Or &HFFF)
Public Function InjectDll(Dll as String, target as String) As Boolean
Dim hWnd as long ' Stores handle of target window
Dim hLoadLibraryA as long ' Stores handle to loadlibrary
Dim hThread as long ' Stores handle to remote thread
Dim hRemoteMem as long ' Stores handle to remote memory
Dim hProcess as long ' Stores handle to target process
Dim procID as long ' Stores Process ID
Dim dwBytesWritten as long ' Stores number of bytes written
Dim dwThreadID as long ' Stores remote thread id
' Initialize security attributes
SA.nLength = Len(SE)
SA.lpSecurityDescriptor = False
' Find the target window
hWnd = FindWindow(target, vbNullString)
GetWindowThreadProcessId hWnd, procID ' This will get the process id and store in procID
' Open the existing process object
hProcess = OpenProcess(PROCESS_ALL_ACCESS, False, procID)
if hProcess = 0 then goto error
' Get the proc address of LoadLibrary
hLoadLibraryA = GetProcAddress(GetModuleHandle("kernel32.dll"), "LoadLibraryA")
' Commit a region of memory within the virtual address space of the target process
hRemoteMem = VirtualAllocEx(hProcess, 0, LenB(Dll), MEM_COMMIT, PAGE_READWRITE)
if hRemoteMem = 0 then goto error
' Write our dll into the memory we committed.
WriteProcessMemory hProcess, ByVal hRemoteMem, ByVal Dll, LenB(Dll), dwBytesWritten
' Create a thread that runs in the virtual address space of the target process
hThread = CreateRemoteThread(hProcess, SA, 0, ByVal hLoadLibraryA, ByVal hRemoteMem, 0, dwThreadID)
if hThread = 0 then goto error
' Wait until the thread is in the signaled state or the time out interval elapses
WaitForSingleObject hThread, 1000
VirtualFreeEx hProcess, hRemoteMem, 0&, MEM_RELEASE
Exit Function
error:
MsgBox "An error has occured!", "VB Injection ERROR!", MB_ERROR
End Function