windows API 第22篇 WTSGetActiveConsoleSessionId

函数原型:
DWORD WTSGetActiveConsoleSessionId (VOID)
先看一下原文介绍:

The WTSGetActiveConsoleSessionId function retrieves the Terminal Services session currently attached to the physical console. The physical console is the monitor, keyboard, and mouse. Note that it is not necessary that Terminal Services be running for this function to succeed.

该函数可以用来获取当前活动的会话ID,有时候我们通过枚举explorer 的相关信息,来获取相关进程的信息,但windows是个多用户操作系统,当多个用户登录时会使通过枚举explorer而得到的用户信息不准确。所以应当先用WTSGetActiveConsoleSessionId获得当前会话ID,再通过枚举进程,通过比较sessionID进而得到的消息比较可靠。
例如:

 DWORD dwSessionId = WTSGetActiveConsoleSessionId();

	PWTS_PROCESS_INFO ppi = NULL;
	DWORD dwProcessCount = 0;

	if (WTSEnumerateProcesses(WTS_CURRENT_SERVER_HANDLE, 0, 1, &ppi, &dwProcessCount))
	{
		for (int i = 0; i <dwProcessCount; i ++)
		{      //任务管理器里可能出现多个explorer
			if (_wcsicmp(ppi[i].pProcessName, L"explorer.exe") == 0)
			{
				if (ppi[i].SessionId == dwSessionId)
				{
					break;
				}
			}
		}

		WTSFreeMemory(ppi);
	}

      ..........

      ..........

      ..........
原文地址:https://www.cnblogs.com/priarieNew/p/9755655.html