From 3eec1310829f6ec7f3c40a35d5991b0ebbf273b5 Mon Sep 17 00:00:00 2001 From: Egor Tensin Date: Sun, 18 Oct 2020 00:11:25 +0300 Subject: Process: add methods to load resource strings --- src/process.cpp | 52 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) (limited to 'src') diff --git a/src/process.cpp b/src/process.cpp index f95bc56..d3ce3a4 100644 --- a/src/process.cpp +++ b/src/process.cpp @@ -6,14 +6,18 @@ #include #include #include +#include #include #include #include +#include #include +#include #include +#include #include #include @@ -110,4 +114,52 @@ int Process::get_exit_code() const { return static_cast(ec); } +HMODULE Process::get_exe_module() { + const auto module = ::GetModuleHandleW(NULL); + if (module == NULL) { + throw error::windows(GetLastError(), "GetModuleHandleW"); + } + return module; +} + +std::string Process::get_resource_string(unsigned int id) { + wchar_t* s = nullptr; + + const auto nch = ::LoadStringW(get_exe_module(), id, reinterpret_cast(&s), 0); + + if (nch <= 0) { + throw error::windows(GetLastError(), "LoadStringW"); + } + + return narrow(s, nch * sizeof(wchar_t)); +} + +Resource Process::get_resource(unsigned int id) { + const auto module = get_exe_module(); + + const auto src = ::FindResourceA(module, MAKEINTRESOURCEA(id), RT_RCDATA); + + if (src == NULL) { + throw error::windows(GetLastError(), "FindResourceA"); + } + + const auto resource = ::LoadResource(module, src); + + if (resource == NULL) { + throw error::windows(GetLastError(), "LoadResource"); + } + + const auto data = ::LockResource(resource); + + if (data == NULL) { + std::ostringstream oss; + oss << "Couldn't get data pointer for resource with ID " << id; + throw std::runtime_error{oss.str()}; + } + + const auto nb = ::SizeofResource(module, src); + + return {data, nb}; +} + } // namespace winapi -- cgit v1.2.3