Autor Beitrag
tommie-lie
ontopic starontopic starontopic starontopic starontopic starofftopic starofftopic starofftopic star
Beiträge: 4373

Ubuntu 7.10 "Gutsy Gibbon"

BeitragVerfasst: Do 18.12.03 23:59 
Mit GetEnvironmentVariable und SetEnvironmentVariable kann man Umgebungsvariablen auslesen und ändern. Die Aufgabe, alle (prozesslokalen) Umgebungsvariablen auszulesen übernimmt die Funktion GetEnvironmentStrings. Sie liefert eine für Windows-API-Funktionen typische Struktur zurück, nämlich eine nullterminierte Liste von nullterminierten Strings.

Zum einfacheren Zugriff kann man auch folgende Funktion benutzen, die ein array of String zurückliefert und über einen By-Reference-Parameter auch die Anzahl an Variablen ausspuckt.

Vorraussetzungen:
  • windows.pas muss eingebunden sein
  • Windows ab Windows95

Der Datentyp TStringArray ist folgendermaßen deklariert:
ausblenden Delphi-Quelltext
1:
2:
type
  TStringArray = array of String

Und hier die Funktion:
ausblenden volle Höhe Delphi-Quelltext
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
function GetEnvironmentVarList(var count: LongWord): TStringArray;
var
  env, env2: PChar;
  i: Integer;
begin
  // get the bunch of memory that contains the variables
  env := GetEnvironmentStrings();
  if env = nil then
    exit;
  env2 := env;

  i := 0;
  count := 0;


  // get the number of variables to allocate the dynamic array in one go
  while env2^ <> #0 do
  begin
    env2 := StrEnd(env2) + 1;
    inc(count);
  end;
  // restore the beginning of the block
  env2 := env;

  // and assign the values for every variable
  SetLength(Result, count);
  while (env2^ <> #0and (i < High(Result)) do
  begin
    Result[i] := env2;
    inc(env2, length(Result[i]) + 1);
    inc(i);
  end;

  // Free the block of memory!!!
  FreeEnvironmentStrings(env);
end;


Ein Beispielaufruf könnte folgendermaßen aussehen:
ausblenden Delphi-Quelltext
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
procedure TForm1.Button1Click(Sender: TObject);
var
  cnt: longword;
  list: TStringArray;
  i: Integer;
begin
  list := GetEnvironmentVarList(cnt);
  Label1.Caption := IntToStr(cnt);
  for i := 0 to cnt - 1 do
    Listbox1.Items.Add(list[i]);
end;

In Label1 steht nun die Anzahl der Umgebungsvariablen und in der Listbox die Variablen selbst, zusammen mit dem aktuell zugewiesenen Wert.

_________________
Your computer is designed to become slower and more unreliable over time, so you have to upgrade. But if you'd like some false hope, I can tell you how to defragment your disk. - Dilbert