windows c++ (3) windows获取进程PID、进程路径、进程启停及文件相关操作

1、windows下获取PID

windows下获取PID比较简单,可以直接通过TlHelp32.h内的Process32First + Process32Next来遍历进程获取PROCESSENTRY32(存放快照进程信息的一个结构体)结构体信息,对比进程名称获取对应的PID。
调用以上方法记得先 #include #include
PROCESSENTRY32解析:

typedef struct tagPROCESSENTRY32
{
    DWORD   dwSize;
    DWORD   cntUsage;
    DWORD   th32ProcessID;          // this process
    ULONG_PTR th32DefaultHeapID;
    DWORD   th32ModuleID;           // associated exe
    DWORD   cntThreads;
    DWORD   th32ParentProcessID;    // this process's parent process
    LONG    pcPriClassBase;         // Base priority of process's threads
    DWORD   dwFlags;
    CHAR    szExeFile[MAX_PATH];    // Path
} PROCESSENTRY32;
成员 解析
dwSize 结构体的大小
cntUsage 此进程的引用计数(已经不再被使用,总是设置为零)
th32ProcessID 进程ID(我们需要的pid)
th32DefaultHeapID 进程默认堆ID(已经不再被使用,总是设置为零)
th32ModuleID 进程模块ID(已经不再被使用,总是设置为零)
cntThreads 此进程开启的线程计数
th32ParentProcessID 父进程的ID
pcPriClassBase 线程优先权
dwFlags 已经不再被使用
szExeFile 进程的可执行文件名称。要获得可执行文件的完整路径,应调用Module32First函数,再检查其返回的MODULEENTRY32结构的szExePath成员。但是,如果被调用进程是一个64位程序,您必须调用QueryFullProcessImageName函数去获取64位进程的可执行文件完整路径名

实现

/*
	brief:*获取进程PID
	parm1: 进程名称
	ret: 成功->进程PID
		 失败->-1
*/
int getPidByName(const char* processName )
{
	HANDLE hSnapshot;
	PROCESSENTRY32 lppe;
	BOOL Found;
	hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
	lppe.dwSize = sizeof(PROCESSENTRY32);
	Found = Process32First(hSnapshot, &lppe);
	char mProce[MAX_PATH] = "";
	int pid = -1;
	while (Found)
	{
		strcpy(mProce, processName);
		strcat(mProce, ".exe");
		if (strcmp(mProce, lppe.szExeFile) == 0)//进程名比较  
		{
			Found = TRUE;
			pid = lppe.th32ProcessID;
			break;
		}
		Found = Process32Next(hSnapshot, &lppe);//得到下一个进程  
	}
	CloseHandle(hSnapshot);
	return pid;
}

2、获取进程路径

实现

#define MAX_PATH          256
/*
	brief:*获取进程的完整路径,支持xp、win7、win10系统
	parm1: 进程PID
	parm2: 进程路径指针(返回值)
	parm3: 路径长度
	ret: null
*/
void GetProcessPath(DWORD nPID, char* szPathName, int pathlen)
{
	DWORD dwMajorVersion = 0;
	DWORD dwMinorVersion = 0;
	OSVERSIONINFOEX osver = { 0 };
	osver.dwOSVersionInfoSize = sizeof(osver);
	::GetVersionEx((OSVERSIONINFO*)&osver);
	dwMajorVersion = osver.dwMajorVersion;
	dwMinorVersion = osver.dwMinorVersion;

	//打开进程
	//dwPID,进程ID
	char  szFileName[MAX_PATH] = {0};//文件名
	HANDLE hProcess = NULL;
	HMODULE hModule = NULL;
	DWORD cbReturn = 0;
	hProcess=OpenProcess(PROCESS_QUERY_INFORMATION|PROCESS_VM_READ,//访问权限,win7以上系统需要提升权限EnablePrivilege
		false,//是否允许得到的进程句柄被后创建的子进程继承
		nPID);//进程ID
	DWORD dwError = 0;
	//BOOL bSuccessProcess = pEnumProcessModules(hProcess,&hModule,sizeof(hModule),&cbReturn);
	BOOL bSuccessProcess = EnumProcessModules(hProcess, &hModule, sizeof(hModule), &cbReturn);
	if (!bSuccessProcess)
	{
		dwError = GetLastError();
	}
	memset(szFileName, 0, sizeof(szFileName));
	memset(szPathName, 0, pathlen);
	if (hModule != NULL)
	{
		//获得进程模块文件名(包含路径)
		if (dwMajorVersion < 5)		//2000
		{
			//保存文件名
			DWORD dwGetModuleBaseName = GetModuleFileNameEx(hProcess, hModule, szPathName, pathlen);
		}
		if (dwMajorVersion == 5)  //x或Windows Server2003
		{
			GetProcessImageFileName(hProcess, szPathName, pathlen);
		}
		else if (osver.dwMajorVersion >= 6)		//win7或win7以上
		{
			DWORD dwPathNameSize = pathlen;
			bSuccessProcess = QueryFullProcessImageName(hProcess, 0, szPathName, &dwPathNameSize);
		}
		if (!bSuccessProcess)
		{
			dwError = GetLastError();
		}
	}
	if(hProcess)
		CloseHandle(hProcess);
}

3、进程启停

启动实现

/*
	brief:开始进程
	parm1: 进程名称
	parm2: 附带参数长度
	parm3: 附带参数
	ret: 成功->进程PID
		 失败->-1
*/
int startProc(const char* name,int argc = 0,char* param[] = NULL);
int startProc(const char* name,int argc,char* param[])
{
	std::string strPath = m_ProcessPath + name;

	PROCESS_INFORMATION		pi;
	STARTUPINFO				si = {sizeof(si)};
	DWORD					dwExitCode;
	HANDLE					h_MapGeneralArea;
	char cCommand[MAX_PATH] = {0};
	sprintf_s(cCommand,"%s.exe",strPath.c_str());
	for (int i = 0;i<argc;i++)
	{
		sprintf_s(cCommand,"%s %s",cCommand,param[i]);
	}
	//隐藏程序 DOS 窗口
	si.cb = sizeof(si); 
	si.dwFlags = STARTF_USESHOWWINDOW; 
	si.wShowWindow = SW_HIDE;
	BOOL ret = CreateProcess(NULL, cCommand, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);
	if (ret){
		return pi.dwProcessId;
	}
	else{
		return -1;
	}
}

停止实现

/*
	brief:停止进程
	parm1: 进程id
	ret: null
*/
void CProcessCtrl::stopProc( int pid )
{
	//killprocess
	HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS,FALSE,pid);  

	if (hProcess != NULL)
	{
		if(TerminateProcess(hProcess,0))
			CloseHandle(hProcess);
		else
		{
			LPVOID lpMsgBuf;
			FormatMessage(
				FORMAT_MESSAGE_ALLOCATE_BUFFER |
				FORMAT_MESSAGE_FROM_SYSTEM |
				FORMAT_MESSAGE_IGNORE_INSERTS,
				NULL,
				GetLastError(),
				MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
				(LPTSTR) &lpMsgBuf,
				0,
				NULL);
			LocalFree(lpMsgBuf);
		}
	}
}

4、文件操作

文件的操作网上很多,这里写下文件夹的拷贝删除

拷贝实现

//显示文件拷贝时的进度条
BOOL CopyFolder(LPCTSTR lpszFromPath,LPCTSTR lpszToPath)
{
	int nLengthFrm = strlen(lpszFromPath);
	char *NewPathFrm = new char[nLengthFrm+2];
	strcpy(NewPathFrm,lpszFromPath);
	NewPathFrm[nLengthFrm] = '\0';
	NewPathFrm[nLengthFrm+1] = '\0';
	SHFILEOPSTRUCT FileOp;
	ZeroMemory((void*)&FileOp,sizeof(SHFILEOPSTRUCT));
	FileOp.fFlags = FOF_NOCONFIRMATION ;
	FileOp.hNameMappings = NULL;
	FileOp.hwnd = NULL;
	FileOp.lpszProgressTitle = NULL;
	FileOp.pFrom = NewPathFrm;
	FileOp.pTo = lpszToPath;
	FileOp.wFunc = FO_COPY;

	int ret = SHFileOperation(&FileOp);
	char errdat[128];
	sprintf(errdat,"拷贝文件出错,错误码:%d",ret);
	if (ret!=0)
	{
		DPLOG_INFO("拷贝文件",errdat);
		Sleep(100);
		delete []NewPathFrm;
		return FALSE;
	}
	Sleep(100);
	delete []NewPathFrm;
	return TRUE;
}

删除实现

//删除文件或者文件夹
BOOL MyDeleteFile(char* lpszPath)
{
	SHFILEOPSTRUCT  shDelFile;
	memset(&shDelFile,0,sizeof(SHFILEOPSTRUCT));
	shDelFile.fFlags |= FOF_SILENT;      // don't report progress
	shDelFile.fFlags |= FOF_NOERRORUI;     // don't report errors
	shDelFile.fFlags |= FOF_NOCONFIRMATION;    // don't confirm delete


	// Copy pathname to double-NULL-terminated string.
	//
	TCHAR buf[_MAX_PATH + 1] = {0}; // allow one more character
	_tcscpy(buf, lpszPath);   // copy caller's pathname
	buf[_tcslen(buf)+1]=0;   // need two NULLs at end

	// Set SHFILEOPSTRUCT params for delete operation
	shDelFile.wFunc = FO_DELETE;       // REQUIRED: delete operation
	shDelFile.pFrom = buf;         // REQUIRED: which file(s)
	//shDelFile.pFrom = "C:\\work\\云卡口前端管理系统\\FMCloud(XListCtrl)\\Debug\\Controller3\0\0";
	shDelFile.pTo = NULL;          // MUST be NULL
	{           // otherwise..
		shDelFile.fFlags |= FOF_ALLOWUNDO;    // ..send to Recycle Bin
	}

	int retval = SHFileOperation(&shDelFile);
	return retval == 0;
}

你可能感兴趣的:(windows,c++,windows,c++,linux)