欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

用进程打开记事本(notepad),停留5秒后结束记事本进程

程序员文章站 2022-07-12 15:50:47
...
卓工课上老师的作业,写了一下午加一个晚上,终于完成了,很开心。
#include "stdafx.h"
#include <windows.h>  
#include <tlhelp32.h>  
#include <tchar.h>
#include <iostream>
using namespace std;//注意这几个文件的次序,在VS2017中不可以乱序

bool killProcess(PROCESS_INFORMATION& processInfo)
{
	DWORD processId = processInfo.dwProcessId;
	PROCESSENTRY32 processEntry = { 0 };
	processEntry.dwSize = sizeof(PROCESSENTRY32);

	//给系统内的所有进程拍一个快照  
	HANDLE handleSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);

	//遍历每个正在运行的进程  
	if (Process32First(handleSnap, &processEntry))
	{
		BOOL isContinue = TRUE;

		//终止子进程  
		do {
			if (processEntry.th32ParentProcessID == processId)
			{
				HANDLE hChildProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, processEntry.th32ProcessID);
				if (hChildProcess)
				{
					TerminateProcess(hChildProcess, 0);
					CloseHandle(hChildProcess);
				}
			}
			isContinue = Process32Next(handleSnap, &processEntry);
		} while (isContinue);

		HANDLE hBaseProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, processId);

		if (hBaseProcess)
		{
			TerminateProcess(hBaseProcess, 0);
			CloseHandle(hBaseProcess);
		}
	}

	DWORD exitCode = 0;

	GetExitCodeProcess(processInfo.hProcess, &exitCode);
	cout << "exitCode=" << exitCode << endl;

	if (exitCode == STILL_ACTIVE)
	{
		return false;
	}

	return true;
}

int main() {

	TCHAR szCommandLine[] = TEXT("notepad");//或者WCHAR  
	STARTUPINFO si;
	PROCESS_INFORMATION pi;
	ZeroMemory(&pi, sizeof(pi));
	ZeroMemory(&si, sizeof(si));
	si.cb = sizeof(si);

	if (CreateProcess(NULL, szCommandLine, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi))  //createprocess()返回值为bool型,成功为非零.
	{
		Sleep(5000);
		cout << killProcess(pi) << endl;
	}
	else {
		cout << "创建失败!" << endl;
		HANDLE hProcess = GetCurrentProcess();
		TerminateProcess(hProcess, 0);
	}

	system("pause");//这句话注意可以使程序避免闪退
	return 0;
} 

这一段程序构思比较巧妙,1.使用定义killprocess(),后调用。2.把createProcess()返回值作为if语句的判断条件,简单粗暴。

知识点:windows编程的进程的创建与结束。参见百度百科:https://baike.baidu.com/item/CreateProcess/11050419?fr=aladdin#3

相关标签: c vs2017

上一篇: 遍历json

下一篇: 理解JSON