前言
今天帮同事写个小程序,需要在运行一个程序后,登出当前的session。
用到了一个API :WTSLogoffSession。
以前没用过这个API,记录一下。
实验
// @file demo_WTSLogoffSession.cpp
// @brief 演示登出当前session的操作.
// 程序启动后,先运行notepad.exe, 当关闭记事本后,执行登出操作,到window登录界面
// @note 程序的编译没有请求管理员权限, 编译后,用管理员和标准用户登录,运行此demo都好使
// 编译环境:vs2015
// 试验环境:win7x64sp1
#include "stdafx.h"
#include <windows.h>
#include <Wtsapi32.h>
#pragma comment(lib, "Wtsapi32.lib")
#include <stdlib.h>
#include <stdio.h>
#include "demo_WTSLogoffSession.h"
#define PROG_TO_START "C:\\Windows\\System32\\notepad.exe"
DWORD get_session_id();
int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
_In_opt_ HINSTANCE hPrevInstance,
_In_ LPWSTR lpCmdLine,
_In_ int nCmdShow)
{
BOOL bRc = FALSE;
DWORD dwRc = 0;
HANDLE hServer = NULL;
char sz_cmd[MAXBYTE] = { '\0' };
STARTUPINFOA si;
PROCESS_INFORMATION pi;
memset(&si, 0, sizeof(si));
memset(&pi, 0, sizeof(pi));
si.cb = sizeof(STARTUPINFO);
GetStartupInfoA(&si);
si.wShowWindow = SW_NORMAL;
si.dwFlags = STARTF_USESHOWWINDOW;
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
do {
if (CreateProcessA(PROG_TO_START, sz_cmd, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) {
WaitForSingleObject(pi.hProcess, INFINITE);
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
}
hServer = WTSOpenServerA("");
if (NULL != hServer) {
bRc = WTSLogoffSession(hServer, get_session_id(), TRUE);
if (!bRc) {
dwRc = GetLastError();
// @todo log error sn
}
}
} while (0);
if (NULL != hServer) {
WTSCloseServer(hServer);
hServer = NULL;
}
return EXIT_SUCCESS;
}
DWORD get_session_id()
{
DWORD session_id = 0;
ProcessIdToSessionId(::GetCurrentProcessId(), &session_id);
return session_id;
}