How to get ModuleBaseName using GetForegroundWindow function? - c++

I can get handle from GetForegroundWindow function. And I want to get BaseName
of handle. So i used GetModelBaseName function. But I guess this function was not work correctly.
TCHAR TitleName[MAX_PATH] = TEXT("");
HANDLE hFirst = GetForegroundWindow();
GetModuleBaseName(hFirst, NULL, TitleName, MAX_PATH);
_tprintf(TEXT("%s \n"), TitleName);
Tell me, what is the problem?

You are doing it wrong, that's why it's returning false and GetLastError will return ERROR_INVALID_HANDLE (6).
HWND WINAPI GetForegroundWindow(void);
Will return the current foreground window and will return it's window handle of type HWND.
You can do this to retrieve the filename of your application:
TCHAR szName[MAX_PATH];
GetModuleBaseName(GetCurrentProcess(), GetModuleHandle(NULL), szName, MAX_PATH);
Besides, you can also use GetModuleFileName or GetMappedFileName to retrieve the full path of your application
Edit: He wants to do something else too. To retrieve the path of another process, you will have to open that process with a process id. For instance, if 9912 is the process id of Chrome then you can execute the following code to retrieve it's path
HANDLE process = ::OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, 9912);
if (process)
{
char file_path[MAX_PATH];
if (::GetModuleFileNameEx(process, nullptr, file_path, MAX_PATH))
{
std::cout << file_path << std::endl;
}
else
{
std::cout << "Error retrieving path" << std::endl;
}
::CloseHandle(process);
}

Related

c++ my program cannot initialize a handle on a process

I'm trying to edit memory in a program. For the most part the code works, but when I try to initiate a handle on the process, it returns NULL.
#include <iostream>
#include <windows.h>
using namespace std;
int main() {
int playerTotalRam = 761;
HWND hwnd = FindWindowA(NULL, "generic game"); // specifies the window to act
upon
// error message if the window isn't found
if (hwnd == NULL) {
cout << "window not found!\n";
system("PAUSE");
} else {
DWORD processID;
// stores the process id of the window
GetWindowThreadProcessId(hwnd, &processID);
// gets the process id of the window
HANDLE handle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, processID);
// opens the process with full access
if (!handle) {
cout << "couldnt initiate a handle on the process!\n";
system("PAUSE");
}
// error message if the process ID isn't found
if (processID == NULL) {
cout << "cannot find process!\n";
system("PAUSE");
} else {
WriteProcessMemory(handle, (LPVOID)0x044A52C8, &playerTotalRam,
4, 0); // this writes the new value to the listed address
}
}
return 0;
}
The program outputs "couldnt initiate a handle on the process!"
I have this same error with other programs.
What i want to know is what am I doing wrong, and how can I fix this.
My system is windows 10 home.
Either FindWindowA is failing, resulting in an incorrect process id because you have the wrong window title text or you're not running your program as administrator. You need to run as administrator to get PROCESS_ALL_ACCESS permissions and make sure your title text is correct. This will solve your problem.

How can I get the name of any process having a visible window - WinAPI?

I'm trying to get the name of processes which have a visible window. For example, if I have Chrome opened, I would like to get the string "chrome.exe", but I only get the init value "unknown" using the code below.
I read around it could be an access rights problem, can you suggest me how to change them in order to get the name of processes?
DWORD idProc = 0; //pointer to the process which created the window
DWORD idThread = GetWindowThreadProcessId(Wnd->get_handle(), &idProc);
Wnd->set_pid(idThread); //Wnd is an object of a class i created, to collect processes info
// Get a handle to the process.
TCHAR szProcessName[DEFAULT_BUFLEN] = TEXT("<unknown>");
HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION |
PROCESS_VM_READ,
FALSE, idProc);
if (hProcess!=NULL) {
HMODULE hMod;
DWORD cbNeeded;
if (EnumProcessModules(hProcess, &hMod, sizeof(hMod),
&cbNeeded))
{
GetModuleBaseName(hProcess, hMod, szProcessName,
sizeof(szProcessName) / sizeof(TCHAR));
}
}
Wnd->set_processname(szProcessName);
CloseHandle(hProcess);
It works fine for some processes, but it doesn't for many others like Chrome, as I said.
EDIT: I forgot to say, I've just filtered visible windows, so suppose handles are what I need yet.
this question how get process name/path by ID - is many time already answered here.
if you need name only (but not full path) - you can use CreateToolhelp32Snapshot / Process32First / Process32Next
compare PROCESSENTRY32.th32ProcessID with your idProc and use PROCESSENTRY32.szExeFile.
alternate and more effective way use ZwQuerySystemInformation with SystemProcessInformation info class.compare SYSTEM_PROCESS_INFORMATION.UniqueProcessId with your idProc and use SYSTEM_PROCESS_INFORMATION.ImageName. really first way is shell over this method.
if you need not only name, but full path :
if you have SE_DEBUG_PRIVILEGE - you need enable it, open process with PROCESS_QUERY_LIMITED_INFORMATION (vista+) or PROCESS_QUERY_INFORMATION (xp/2003) and use ZwQueryInformationProcess with ProcessImageFileName (return path in NT form) or GetProcessImageFileName (internally it call ZwQueryInformationProcess(,ProcessImageFileName,))
or begin from vista - you can use ProcessImageFileNameWin32 (return win32-path) or QueryFullProcessImageName (again only documented thin shell over this way)
also begin from vista - most effective way query process full path (in NT form) - use ZwQuerySystemInformation with SystemProcessIdInformation info class. this way not require any privileges and open process
use GetProcessImageNamr API instead:
#include <iostream>
using namespace std;
#include <windows.h>
#include <Psapi.h>
#pragma comment(lib, "Psapi.lib")
int main()
{
DWORD dwProcessId;
DWORD dwThreadId ;
while(1)
{
Sleep(2000);
HWND hForg = GetForegroundWindow(); // to get the foreground windows' handle window
dwThreadId = GetWindowThreadProcessId(hForg, &dwProcessId); // getting the window's process ID
DWORD dwDesiredAccess =
PROCESS_QUERY_INFORMATION | PROCESS_VM_READ;
bool bInheritHandle = false;
HANDLE hProcess = OpenProcess(dwDesiredAccess,
bInheritHandle, dwProcessId);
if(INVALID_HANDLE_VALUE == hProcess)
cout << "Failed to open process!" << endl;
HINSTANCE hMod = (HINSTANCE)GetWindowLongPtr(hForg, GWLP_HINSTANCE);
if(!hMod)
cout << "Null Module!" << endl;
char szModFileName[MAX_PATH] = "";
// never use this cause it won't get you what you want
// GetModuleFileNameEx(hProcess, hMod, szModFileName, MAX_PATH);
// use this
GetProcessImageFileName(hProcess, szModFileName, MAX_PATH);
CloseHandle(hProcess);
char szWindowName[MAX_PATH] = "";
GetWindowText(hForg, szWindowName, MAX_PATH);
cout << "Window Name: " << szWindowName << endl;
cout << "Created by: " << szModFileName << endl << endl;
}
cout << endl << endl << endl;
return 0;
}
don't use GetModuleFileNameEx but use GetProcessImageFileName

Get path to all users' start menu on Windows

I am looking for a way to retrieve the path to the all users start menu directory in C++. I am only able to get the one of the current user (using Qt):
QString startMenuPath = QStandardPaths::standardLocations(QStandardPaths::ApplicationsLocation).at(0);
However, Qt does not allow to retrieve the one for all users. As far as I know there also is no environment variable containing that path, that I could read.
To get a known folder, use SHGetFolderPath, and pass a KNOWNFOLDERID or CSIDL for the desired folder.
For example, the following code gets the All Users Start Menu and the Programs folder:
// Remember to #include <Shlobj.h>
WCHAR path[MAX_PATH];
HRESULT hr = SHGetFolderPathW(NULL, CSIDL_COMMON_PROGRAMS, NULL, 0, path);
if (SUCCEEDED(hr))
std::wcout << L"Start Menu\Programs: " << path << std::endl;
hr = SHGetFolderPathW(NULL, CSIDL_COMMON_STARTMENU, NULL, 0, path);
if (SUCCEEDED(hr))
std::wcout << L"Start Menu: " << path << std::endl;
Thanks goes to user theB for the solution. Here my final piece of code for creating a shortcut in the all-users start menu on Windows (uses Qt):
#include <shlobj.h>
bool createStartMenuEntry(QString targetPath) {
targetPath = QDir::toNativeSeparators(targetPath);
WCHAR startMenuPath[MAX_PATH];
HRESULT result = SHGetFolderPathW(NULL, CSIDL_COMMON_PROGRAMS, NULL, 0, startMenuPath);
if (SUCCEEDED(result)) {
QString linkPath = QDir(QString::fromWCharArray(startMenuPath)).absoluteFilePath("Some Link.lnk");
CoInitialize(NULL);
IShellLinkW* shellLink = NULL;
result = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_ALL, IID_IShellLinkW, (void**)&shellLink);
if (SUCCEEDED(result)) {
shellLink->SetPath(reinterpret_cast<LPCWSTR>(targetPath.utf16()));
shellLink->SetDescription(L"Description");
shellLink->SetIconLocation(reinterpret_cast<LPCWSTR>(targetPath.utf16()), 0);
IPersistFile* persistFile;
result = shellLink->QueryInterface(IID_IPersistFile, (void**)&persistFile);
if (SUCCEEDED(result)) {
result = persistFile->Save(reinterpret_cast<LPCOLESTR>(linkPath.utf16()), TRUE);
persistFile->Release();
} else {
return false;
}
shellLink->Release();
} else {
return false;
}
} else {
return false;
}
return true;
}
The path to any user's start menu is going to be (On Windows 7)
C:\Users\username\AppData\Roaming\Microsoft\Windows\Start Menu
For the All Users start menu (in Windows 7), it's
C:\ProgramData\Microsoft\Windows\Start Menu
However, only the admin and the user themselves will have unfettered access to each user's folders; everyone else will lack read/write permissions. You can circumvent this by running the program as admin, but you may wish to instead reconsider your program design, as a solution that depends on access to system-managed folders is, by design, going to be unstable.

Get active processname in vc++

Am working on a background appliation in vc++
How can i get the Process Name of the current Application for example "Iexplore" for Using Internet Explorer, "Skype" for window with tile "Skype - username", "Explorer" for using windows explorer ?
i referred this link but am getting Null error : http://www.codeproject.com/Articles/14843/Finding-module-name-from-the-window-handle
This can be done using the following code:
bool GetActiveProcessName(TCHAR *buffer, DWORD cchLen)
{
HWND fg = GetForegroundWindow();
if (fg)
{
DWORD pid;
GetWindowThreadProcessId(fg, &pid);
HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pid);
if (hProcess)
{
BOOL ret = QueryFullProcessImageName(hProcess, 0, buffer, &cchLen);
//here you can trim process name if necessary
CloseHandle(hProcess);
return (ret != FALSE);
}
}
return false;
}
and then
TCHAR buffer[MAX_PATH];
if(GetActiveProcessName(buffer, MAX_PATH))
{
_tprintf(_T("Active process: %s\n"), buffer);
}
else
{
_tprintf(_T("Cannot obtain active process name.\n"));
}
Note though that QueryFullProcessImageName function is only available since Windows Vista, on earlier systems you could use GetProcessImageFileName (it is similar, but requires linkage with psapi.dll and returns device path instead of usual win32 path)
I used this code in my QT5/C++ project to get the currently active process name and window title successfully, based on some research (thanks #dsi). Just wanted to share the code so that someone else would benefit from it.
# Put this two declarations in the top of the CPP file
#include <windows.h>
#pragma comment(lib, "user32.lib")
And put the following into a method:
// get handle of currently active window
HWND hwnd = GetForegroundWindow();
if (hwnd) {
// Get active app name
DWORD maxPath = MAX_PATH;
wchar_t app_path[MAX_PATH];
DWORD pid;
GetWindowThreadProcessId(hwnd, &pid);
HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pid);
if (hProcess) {
QueryFullProcessImageName(hProcess, 0, app_path, &maxPath);
// here you can trim process name if necessary
CloseHandle(hProcess);
QString appPath = QString::fromWCharArray(app_path).trimmed();
QFileInfo appFileInfo(appPath);
windowInfo.appName = appFileInfo.fileName();
}
// Get active window title
wchar_t wnd_title[256];
GetWindowText(hwnd, wnd_title, sizeof(wnd_title));
windowInfo.windowTitle = QString::fromWCharArray(wnd_title);
}
This code may not be compiled directly, because windowInfo is a parameter in my program. Please feel free to let me know in case you encountered any issues when trying this code.

Get path of current module after using RemoteThread

I need to get the current path of the module where my code executed (dll). I've made a dll injection from .NET into a native process and used RemoteThread.
I have tried getcwd, GetCurrentDirectory, GetModuleHandle.
Also tried this solution. But it doesn't work either. I get an empty string with the length of MAX_PATH.
https://stackoverflow.com/questions/6719140/get-path-of-current-module-after-using-remotethread/6719210#6719210
I already opened a thread but I can not login to my email to get the id.
Sorry but anyway thanks for your answer. I will rate this time!
C# Injection
public static IntPtr InjectLibrary(
Process targetProcess,
string libraryPath)
{
var libaryPathBytes = Encoding.GetBytes();
var hProc = NativeMethods.OpenProcess()
var hMemory = NativeMethods.VirtualAllocEx()
NativeMethods.WriteProcessMemory()
var hLoadLib = NativeMethods.GetProcAddress()
var hThread = NativeMethods.CreateRemoteThread()
return hThread;
}
Native Library
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
{
DWORD threadId;
CreateThread( NULL, 0, Bootstrap, NULL, 0, &threadId);
break;
}
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
DWORD WINAPI Bootstrap(LPVOID arg) {
DWORD currentProcessID = GetCurrentProcessId();
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, currentProcessID);
MODULEENTRY32 entry;
Module32First(snapshot, &entry);
MessageBox(NULL, entry.szLibPath, L"", MB_OK);//entry.szLibPath is empty string with the length if MAX_PATH like □□□□□□□□□□□□□□□□□□□□□□□....
HMODULE module = entry.hModule;
wchar_t currentPath[MAX_PATH];
GetModuleFileName(module, currentPath, MAX_PATH);
MessageBox(NULL, currentPath, L"", MB_OK);//currentPath isempty string with the length if MAX_PATH like □□□□□□□□□□□□□□□□□□□□□□□....
//all other options give me the same string or the executable path
return 0;
}
There's a "hidden" tool helper library mentionned by Raymond Chen that gets around several quirks in the Win32 APi. It seems you can use that to fetch the handle to the first module associated to a process (presumably the original executable). You can use that handle to get the path to the executable.
Looks something like:
// Get a listing of modules loaded in the process.
DWORD process = ...;
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, process);
// Get the handle to the first module loaded by that process.
MODULEENTRY32 entry;
Module32First(snapshot, &entry);
HANDLE module = entry.hModule;
// Get the path to the executable/DLL file containing the module.
GetModuleFileName(module, ...);
Edit: I've tried a complete example. You get an empty string using GetModuleFileName() because the module handle was not loaded using the LoadLibrary() function call.
However, it seems the MODULEENTRY32 structure already provides the full path to the module in its szExePath member. The following example works for me:
#include <Windows.h>
#include <TlHelp32.h>
#include <iostream>
int main ( int, char ** )
{
// Substitute `process` with appropriate process ID.
const ::DWORD process = ::GetCurrentProcessId();
const ::HANDLE snapshot =
::CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, process);
if ( snapshot == INVALID_HANDLE_VALUE ) {
std::cerr << "Couldn't get snapshot!" << std::endl;
return (EXIT_FAILURE);
}
// Get 1st module info.
::MODULEENTRY32W module;
::ZeroMemory(&module, sizeof(module));
module.dwSize = sizeof(module);
const ::BOOL result = Module32FirstW(snapshot, &module);
if ( result == FALSE )
{
// Handle errors.
const ::DWORD error = ::GetLastError();
std::cerr
<< "Couldn't get 1st module (" << error << ")."
<< std::endl;
return (EXIT_FAILURE);
}
std::wcout
<< module.szExePath << std::endl;
// Cleanup.
::CloseHandle(snapshot);
return (EXIT_SUCCESS);
}