1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
|
#include <iostream>
#include <string>
#include <vector>
#include <windows.h>
#include <psapi.h>
#include <cctype>
#pragma comment ( lib, "psapi.lib" ) // link with psapi.lib (psapi.dll)
HANDLE open_process( std::string window_title )
{
const auto window = ::FindWindowA( nullptr, window_title.c_str() ) ;
if(window)
{
DWORD pid = 0 ;
::GetWindowThreadProcessId( window, std::addressof( pid ) ) ;
static constexpr auto required_access = PROCESS_ALL_ACCESS ; // adjust as required
return ::OpenProcess( required_access, false, pid ) ;
}
return nullptr ;
}
std::vector<HMODULE> module_list( HANDLE process )
{
std::vector<HMODULE> modules(2048) ; // a sufficiently large size
DWORD nbytes = 0 ;
::EnumProcessModules( process, std::addressof( modules.front() ),
DWORD( modules.size() * sizeof( HMODULE ) ), std::addressof(nbytes) ) ;
modules.resize( nbytes / sizeof( HMODULE ) ) ;
return modules ;
}
std::string& to_lower( std::string& str )
{
for( char& c : str ) c = char( std::tolower(c) ) ;
return str ;
}
const void* base_address( HANDLE process, std::string module_name )
{
char fname[MAX_PATH] {};
for( auto module : module_list(process) )
{
::GetModuleFileNameExA( process, module, fname, sizeof(fname) ) ;
const std::string full_name = fname ;
std::string file_name = full_name.substr( full_name.find_last_of( "/\\" ) + 1 ) ;
if( to_lower(file_name) == to_lower(module_name) ) return module ;
}
return nullptr ; // not found
}
int main()
{
const std::string window_title = "Garry's Mod" ;
const auto process = open_process(window_title) ;
const std::string module_name = "Client.dll" ;
const void* address = base_address( process, module_name ) ;
if(address)
{
std::cout << "module '" << module_name << "' is loaded at base address " << address
<< "\n\t in process " << process << " which owns a window with title '" << window_title << "'\n" ;
}
// ...
// CloseHandle(process) ; // once we are done
}
|