For my Terminal Server unit in the Jedi Security library I use 2 TObjectList descendants to hold a list of Terminal Server Sessions and Processes. Consider the sample below which connects to a server and enumerates all sessions:

var
  ATerminalServer: TJwTerminalServer;
  i: Integer;
begin
  ATerminalServer := TjwTerminalServer.Create;

  ATerminalServer.Server := ‘TS001′;

  try
    if ATerminalServer.EnumerateSessions then
    begin

      // Now loop through the list
      for i := 0 to ATerminalServer.Sessions.Count1 do
      begin
        Memo1.Lines.Add(ATerminalServer.Sessions[i].Username);
      end;

    end;
  except
    on E: EJwsclWinCallFailedException do
    begin
      // Handle Exception here
    end;
  end;

  // Free Memory
  ATerminalServer.Free;
end;

In the sample I loop through the sessions with a for loop. Even though Delphi supports the for in loop since Delphi 2005 it’s not possible to use this in TObjectList descendants, so we cannot use this:

// Now loop through the list
for Session in ATerminalServer.SessionList do
begin
  Memo1.Lines.Add(Session.Username);
end;
 

To make this possible we need to implement GetEnumerator and an Enumerator class:

TJwSessionsEnumerator = class
private
  FIndex: Integer;
  FSessions: TJwWTSSessionList;
public
  constructor Create(ASessionList: TJwWTSSessionList);
  function GetCurrent: TJwWTSSession;
  function MoveNext: Boolean;
  property Current: TJwWTSSession read GetCurrent;
end;

constructor TJwSessionsEnumerator.Create(ASessionList: TJwWTSSessionList);
begin
  inherited Create;
  FIndex := -1;
  FSessions := ASessionList;
end;

function TJwSessionsEnumerator.GetCurrent;
begin
  Result := FSessions[FIndex];
end;

function TJwSessionsEnumerator.MoveNext: Boolean;
begin
  Result := FIndex < FSessions.Count1;
  if Result then
    Inc(FIndex);
end;
 

Now we add a function with the name GetEnumerator in the SessionList class:

function TJwWTSSessionList.GetEnumerator: TJwSessionsEnumerator;
begin
  Result := TJwSessionsEnumerator.Create(Self);
end;
 

And that’s really all!

Related posts:

  1. Multiple Terminal Sessions in Windows Vista