Delphi实现:
uses
WtsApi32;
//通过会话ID得到会话名称
procedure GetSessionUserName(dwSessionId: dword; var UserName: string);
var
bRes: boolean;
dwBufferLen: dword;
Ptr: Pointer;
begin
bRes := WTSQuerySessionInformation(WTS_CURRENT_SERVER_HANDLE, dwSessionId, WTSUserName, Ptr, dwBufferLen);
if bRes = false then
begin
UserName := '';
exit;
end;
UserName := PWideChar(Ptr);
end;
//通过会话名称结束目标会话
procedure ExitByUserName(str: string);
var
i: integer;
sessionInfo: PWTS_SESSION_INFOW;
sessionInfoCount: dword;
dwSessionId: dword;
UserName: string;
CommandLine: string;
begin
if WTSEnumerateSessions(WTS_CURRENT_SERVER_HANDLE, 0, 1, sessionInfo, sessionInfoCount) then
begin
for i := 0 to sessionInfoCount - 1 do
begin
//遍历注销状态为“活动”或者“断开”的所有目标会话
if (sessionInfo.state = WTSActive) or (sessionInfo.state = WTSDisconnected) then
begin
dwSessionId := sessionInfo.SessionId;
GetSessionUserName(dwSessionId, UserName);
if UserName = str then
begin
CommandLine := Format('LOGOFF %d', [dwSessionId]);
winexec(PAnsiChar(ansistring(CommandLine)), SW_HIDE);
Sleep(2500);
end;
end;
inc(sessionInfo);
end;
end;
end;
C++实现:
//在其它session中(如远程桌面的session)运行指定的程序,需要具有system权限,可以在任意的桌面里运行指定程序
#include <windows.h>
#include <stdio.h>
#include <process.h>
#include <Tlhelp32.h>
#include <tchar.h>
#include <psapi.h>
#include <stdio.h>
#include <STDLIB.H>
#include <tlhelp32.h>
#include <WtsApi32.h>
#pragma comment(lib, "WtsApi32.lib")
#pragma comment (lib,"psapi")
// Get us