当前位置:编程学习 > C/C++ >>

用c++结束程序进程问题

已知一个“已运行”的程序名(如:notepad.exe),如何利用C++代码强制结束该进程,请给个示例,谢谢。
追问:请问易做图,怎么没有psapi.h,psapi.lib,psapi.dll?可以把这三个文件发给我吗?邮箱:497251726@qq.com
答案:
能结束用户级的进程,如果进程为更高级别的话要先提升OpenProcess后进程句柄的令牌权限,对于notepad.exe这样的进程是可以轻松搞定的,vc6编译测试通过:

#include <windows.h>
#include <psapi.h>
#include <stdio.h>

#pragma comment(lib, "psapi.lib")

int main()
{
DWORD aps[1024], cbNeeded, cbNeeded2, i;
TCHAR buffer[256], target[] = "notepad.exe";
BOOL killed;
HANDLE hProcess;
HMODULE hModule;

killed = FALSE;

if(!EnumProcesses(aps, sizeof(aps), &cbNeeded)) {
printf("error while enumerating processes.\n");
return -1;
}

for(i = 0; i < cbNeeded/sizeof(DWORD); ++i) {
if(!(hProcess = OpenProcess(PROCESS_TERMINATE |
PROCESS_QUERY_INFORMATION |
PROCESS_VM_READ,FALSE, aps[i])))
continue;
if(!EnumProcessModules(hProcess, &hModule,
sizeof(hModule), &cbNeeded2))
continue;
GetModuleBaseName(hProcess, hModule, buffer, 256);
if(lstrcmpi(buffer, target) == 0) {
printf("Find process: <%s> pid:[%d]\n", target, aps[i]);
if(TerminateProcess(hProcess, 0))
killed = TRUE;
CloseHandle(hProcess);
break;
}
CloseHandle(hProcess);
}
if(killed)
printf("Target process: <%s> has being successfully terminated.\n", target);
else
printf("Target process does not exist or have no privilege to open or terminate.\n");
return 0;
}
如果你用的是windows xp以上版本,去掉include <psapi.h>和那句pragrma,就可以了
exit(0);
代码很多,不贴了,参考这里吧 http://topic.csdn.net/t/20050319/15/3864283.html
#include <windows.h>
#include <iostream>
using namespace std;

int main()
{
DWORD pid;
cout<<"正在监视进程..."<<endl;
HWND hWnd = FindWindow("Notepad", NULL);
if(!hWnd)
{
cout<<"Can't Find the Program.!"<<endl;
return -1;
}
if(hWnd)
{
cout<<"发现进程!即将关闭它··"<<endl;
GetWindowThreadProcessId(hWnd,&pid);
HANDLE hProcess = OpenProcess (PROCESS_ALL_ACCESS,FALSE,pid);
Sleep(1000);
TerminateProcess(hProcess,1);
//等待进程退出
if(WaitForSingleObject(hProcess,INFINITE)==STATUS_WAIT_0)
cout<<"已经完成!"<<endl;
else
cout<<"Unexpected error!"<<endl;
}
return 0;
}

上一个:在C++中用什么语句来替代goto
下一个:C++管理系统的问题

CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,