Skip to content

Instantly share code, notes, and snippets.

@SteelPh0enix
Last active April 13, 2022 07:58
Show Gist options
  • Save SteelPh0enix/8af7c1dcb58c578708a6e23113db1f3e to your computer and use it in GitHub Desktop.
Save SteelPh0enix/8af7c1dcb58c578708a6e23113db1f3e to your computer and use it in GitHub Desktop.
List Windows processes alphabetically
#include <Windows.h>
#include <Psapi.h>
#include <vector>
#include <string>
#include <iostream>
#include <algorithm>
#ifdef UNICODE
using String = std::wstring;
#else
using String = std::string;
#endif
String getProcessName(DWORD processID) {
TCHAR processNameChars[MAX_PATH]{};
HANDLE const processHandle = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, processID);
if (processHandle != nullptr) {
HMODULE moduleHandle{};
DWORD bytesNeeded{};
if (EnumProcessModules(processHandle, &moduleHandle, sizeof(moduleHandle), &bytesNeeded)) {
if (GetModuleBaseName(processHandle, moduleHandle, processNameChars, sizeof(processNameChars) / sizeof(TCHAR))) {
return String(processNameChars);
}
}
CloseHandle(processHandle);
}
return String();
}
std::vector<String> getRunningProcessesNames() {
std::vector<String> processNames;
DWORD processIDs[1024]{};
DWORD bytesReturned{};
if (!EnumProcesses(processIDs, sizeof(processIDs), &bytesReturned)) {
return processNames;
}
unsigned const processesListed = bytesReturned / sizeof(DWORD);
processNames.reserve(processesListed);
for (unsigned i = 0; i < processesListed; i++) {
processNames.push_back(getProcessName(processIDs[i]));
}
return processNames;
}
int main() {
auto processNames = getRunningProcessesNames();
std::sort(processNames.begin(), processNames.end());
for (auto const& process : processNames) {
if (process.length() != 0) {
#ifdef UNICODE
std::wcout << process << std::endl;
#else
std::cout << process << std::endl;
#endif
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment