Link to home
Start Free TrialLog in
Avatar of Paul_Halstead
Paul_Halstead

asked on

Extracting Terminal Server Session ID in Delphi

Greetings,

In our Delphi application we currently use a function GetComputerName to extract the name of the pc where the current instance of the app is running. This gets written to a table in the DB along with things like user-ids and times, so as to provide information as to who is logged in to the app and where.

This is fine in a LAN environment, but increasingly clients are using Terminal Services, where GetComputerName always returns the name of the 'Terminal Server' machine so there is no useful information about where users are logged in. Also if a session needs to be reset via TS manager it is not clear which session to target.

Does anyone know of a way for Delphi to find out whether the app is running under Terminal Services, and if so, to extract the TS 'Session ID' (and, if possible, the name of the pc concerned) in Delphi? Explicit, detailed code examples would be great!

Many thanks,

Paul Halstead
ASKER CERTIFIED SOLUTION
Avatar of jkr
jkr
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Hi,
Here are some of the same drawer, maybe you can use it.
function ProcessIdToSessionId(dwProcessId: DWORD; pSessionId: DWORD): BOOL; stdcall;
	external 'kernel32.dll';
 
	function GetSessionIdfromProccessId(const processId: DWORD; var sessionId: DWORD): boolean;
	begin
		result:=ProcessIdToSessionId(processId, DWORD(@sessionId));
	end;
 
	function GetCurrentSessionId: DWORD;
	begin
		if not GetSessionIdfromProccessId(GetCurrentProcessId,result) then
			result:=0;
	end;
 
	procedure terminateSameSessionId;
	var
		bContinue:		BOOL;
		Ret: 	 		BOOL;
		Ph: 			THandle;
		sh: 			THandle;
		pe: 			TProcessEntry32;
		n:				string;
		myProcessId:   	Dword;
		mySessionId:	DWORD;
		sessionId:		DWORD;
	begin
		mySessionId:=GetCurrentSessionId;
		sh:=CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
		pe.dwSize:=SizeOf(pe);
		bContinue:=Process32First(sh, pe);
		n:=WideLowerCase(ExtractFileName(Application.ExeName));
		GetWindowThreadProcessID(Application.Handle, @myProcessId);
		while Integer(bContinue) <> 0 do begin
			if WideLowerCase(pe.szExeFile) = copy(n,1,length(pe.szExeFile)) then
				if pe.th32ProcessID <> myProcessId then
					if GetSessionIdfromProccessId(pe.th32ProcessID,sessionId) then
						if sessionId=mySessionId then begin
							Ph:=OpenProcess(1, BOOL(0), pe.th32ProcessID);
							Ret:=TerminateProcess(Ph, 0);
						end;
			bContinue:=Process32Next(sh, pe);
		end;
		CloseHandle(sh);
	end; //terminate same session id

Open in new window