`

TerminateMySelf

 
阅读更多
<div class="iteye-blog-content-contain" style="font-size: 14px"></div>
bool Application::TerminateMySelf()
{
	//获取自身线程id
	DWORD _PID;
	_PID=::GetCurrentProcessId();
	printf("ProcessId:%d\n",_PID);

	//获取当前程序的完全路径,返回路径长度
	TCHAR tcCurAppPath[MAX_PATH] = {0};
	DWORD dPathLength = GetModuleFileName(NULL, tcCurAppPath, MAX_PATH);

	//检索系统每个进程的进程标识,返回0失败
	DWORD adwProcessIds[1024] = {0};
	DWORD dwProcessIdCount = 0;
	EnumProcesses(adwProcessIds, sizeof(adwProcessIds), &dwProcessIdCount);

	//轮询每个进程
	for (DWORD i = 0; i < dwProcessIdCount; i++)
	{
		//打开进程
		HANDLE hProcess = OpenProcess(
			PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
			FALSE,
			adwProcessIds[i]);

		if (hProcess != NULL)
		{
			//获取handle完整路径
			HMODULE hModule = NULL;
			DWORD dwNeeded = 0;
			TCHAR tcFileName[MAX_PATH] = {0};
			GetModuleFileNameEx(hProcess, hModule, tcFileName, MAX_PATH);

			//openProcess产生的handle必须关闭
			CloseHandle (hProcess);

			if (0 == _tcsicmp(tcCurAppPath, tcFileName) && adwProcessIds[i] != _PID)
			{
				//根据线程id重新打开handle,注意权限
				HANDLE hClose = OpenProcess(PROCESS_ALL_ACCESS,TRUE,adwProcessIds[i]);

				printf("程序已经启动,开始结束前一进程。\n");

				//强制结束线程
				BOOL bTerminate = TerminateProcess(hClose,-1);
				CloseHandle (hClose);

				if(!bTerminate)
				{
					printf("结束进程失败,错误代码:%d\n",GetLastError());
					return false;
				}
				else
				{
					printf("前一进程已结束,重新进入程序!\n");
					return true;
				}		
			}
		}
	}
	return true;
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics