WTSLogoffSession

前言

今天帮同事写个小程序,需要在运行一个程序后,登出当前的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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值