VC++根据explorer.exe进程检测用户是否已登录 | 马犇-技术博客

VC++根据explorer.exe进程检测用户是否已登录

来源:本站原创 C/C++, 原创 超过5,578 views围观 1条评论

这个地方写成了定时器的回调,定时检测!

void CALLBACK timeCall(UINT timeid, UINT umsg, DWORD_PTR dwUser, DWORD dw1, DWORD_PTR dw2)
{
	DWORD dwSessionId = WTSGetActiveConsoleSessionId();        //获取控制台的session
	HANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);    //为创建环境快照
	if (hSnap == INVALID_HANDLE_VALUE)
		return;

	//遍历快照,通过快照的 procEntry.szExeFile 获取应用程序名字,从而取得相应的PID
	PROCESSENTRY32 procEntry;
	procEntry.dwSize = sizeof(PROCESSENTRY32);
	Process32First(hSnap, &procEntry);

	DWORD dwExplorerPid = -1;
	do
	{
		if (strcmp(procEntry.szExeFile, "explorer.exe") == 0)
		{
			DWORD dwExplorerSessId = 0;
			if (ProcessIdToSessionId(procEntry.th32ProcessID, &dwExplorerSessId) && dwExplorerSessId == dwSessionId)
			{
				dwExplorerPid = procEntry.th32ProcessID;
				break;
			}
		}
	} while (Process32Next(hSnap, &procEntry));

	LOG_INFO("检测用户是否已经登录 : %s", (dwExplorerPid == -1) ? "未登录" : "已经登录");
	if (dwExplorerPid != -1)
	{
		//已登录
		DoSomething();
	}
}