VS2015 C++编写简单进程管理器

it2026-01-01  1

VS2015 C++编写简单进程管理器

源代码运行结果

要求实现进程管理器

能列出操作系统当前运行的进程实现进程管理,如杀掉进程,输入进程名或进程ID,自动结束进程不要求有界面,命令行窗口即可

源代码

#include <Windows.h> #include <stdio.h> #include <TlHelp32.h> #include<map> #include<iostream> #include<string> #include"stdafx.h" using namespace std; int GetProcess(map<std::wstring, int> &_mapProcess) { PROCESSENTRY32 pe32; pe32.dwSize = sizeof(pe32); HANDLE hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (hProcessSnap == INVALID_HANDLE_VALUE) { cout << "Create Toolhelp32Snapshot Error!" << endl; return false; } BOOL bResult = Process32First(hProcessSnap, &pe32); int num(0); while (bResult) { std::wstring name = pe32.szExeFile; int id = pe32.th32ProcessID; cout << "进程ID:" << id << " " << endl; wcout << "进程名称:" << name << endl; _mapProcess.insert(pair<wstring, int>(name, id)); bResult = Process32Next(hProcessSnap, &pe32); } CloseHandle(hProcessSnap); return true; } void EnableDebugPriv() { HANDLE hToken; TOKEN_PRIVILEGES tkp; OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken); LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, &tkp.Privileges[0].Luid); tkp.PrivilegeCount = 1; tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; AdjustTokenPrivileges(hToken, FALSE, &tkp, 0, NULL, NULL); CloseHandle(hToken); } int KillProcess(int id) { HANDLE hProcess = NULL; hProcess = OpenProcess(PROCESS_TERMINATE, FALSE, id); if (hProcess == NULL) { wprintf(L"\nOpen Process fAiled:%d\n", GetLastError()); return -1; } DWORD ret = TerminateProcess(hProcess, 0); if (ret == 0) { wprintf(L"%d", GetLastError()); } return -1; } int main() { map<wstring, int> mapProcess; cout << "请输入指令:1.列出进程 2.终止进程" << endl; int pid; while (cin>>pid) { if(pid == 1) GetProcess(mapProcess); else if(pid == 2) { int i; cout << "请输入进程ID:"; cin >> i; int j=KillProcess(i); if(j==-1) cout << "成功终止进程!" << endl; } else cout << "输入有误!" << endl; cout << "请输入指令:1.列出进程 2.终止进程" << endl; } system("pause");

运行结果

列出进程 打开notepad,再列出进程,出现notepad 终止该3892进程 notepad被强制关闭

最新回复(0)