Welcome to the new DelphiDabbler Code Library Documentation.

This is a new site that's currently running on alpha code. There are going to be bugs. If you discover any, please report them on the site's issues page (GitHub account required). Thanks.

Warning: Many URLs are going to change. Refer to the README file to discover which library project's documentation has been completed.

EnumNames class method

Project: Environment Variables Unit

Unit: PJEnvVars

Class: TPJEnvironmentVars

Applies to: ~>3.0

class procedure EnumNames(Callback: TPJEnvVarsEnum; Data: Pointer);


Enumerates the names of all the environment variables in the current process.


The Callback method or (anonymous procedure) must be implemented by the caller.

Important: Environment variables should not be modified while EnumNames is executing. This is because the method takes a snap-shot of the environment variable names before it starts calling Callback. Any environment variables added or deleted while EnumNames is running will not be reflected in the enumeration and could cause obscure bugs.


Here are two implementation of methods that add the names of all environment variables to a user-provided string list.

The first implementation works with all compilers and uses a callback method. The methods we create could be part of any class, but here we assume they are part of a form class named TForm1. Implement the following methods:

procedure TForm1.EnvNameCallback(const VarName: string; Data: Pointer):

procedure TForm1.EnvNamesToStrings(const Strings: TStrings);
  TPJEnvironmentVars.EnumNames(EnvNameCallback, Pointer(Strings));

Here our method that adds the environment variable names to a given string list is called EnvNamesToStrings and the callback method is EnvNameCallback.

In EnvNamesToStrings we call EnumNames and pass a reference to the callback to it. The interesting bit is that we pass a pointer to the string list via the Data parameter.

Now EnumNames calls EnvNamesToStrings once for each environment variable, passing the environment variable’s name in the VarName parameter and the string list pointer in the Data parameter. EnvNamesToStrings casts the Data pointer back to a TStrings object and adds the environment variable name to it.

The second example requires Delphi 2009 or later. We again implement an EnvNamesToStrings method of TForm1, but this time we dispense with the callback method and use use an anonymous procedure instead. Here’s the method:

procedure TForm1.EnvNamesToStrings(const Strings: TStrings);
    procedure (const AName: string; Data: Pointer)

Because we are using an anonymous procedure that is in the same scope as EnvNamesToStrings’s string list parameter we can access the string list object directly. This means there is no need to pass a reference to the string list to the callback via EnumName’s Data parameter, so we just pass nil.