在 Inno Setup 中将项目添加到列表框的正确方法?

Correct way to add items to a list box in Inno Setup?

我从 获得了代码,我想将结果添加到列表框中。我在询问之前尝试过这样做,但我无法添加所有项目。这是我的代码:

var
  Query, AllPrinters: string;
  WbemLocator, WbemServices, WbemObjectSet: Variant;
  Printer: Variant;
  I: Integer;
begin
  WbemLocator := CreateOleObject('WbemScripting.SWbemLocator');
  WbemServices := WbemLocator.ConnectServer('.', 'root\CIMV2');
  Query := 'SELECT Name FROM Win32_Printer';
  WbemObjectSet := WbemServices.ExecQuery(Query);
  if not VarIsNull(WbemObjectSet) and (WbemObjectSet.Count > 0) then
  begin
    for I := 0 to WbemObjectSet.Count - 1 do
    begin
      Printer := WbemObjectSet.ItemIndex(I);
      if not VarIsNull(Printer) then
      begin
        Log(Printer.Name);
        AllPrinters := Printer.Name;
      end;
    end;
  end;
end;

然后在自定义页面上执行此操作:

ListBoxPrinters.Items.Add(AllPrinters);

您总是用下一个 AllPrinters := Printer.Name; 覆盖以前的值!

像那样简单构建 AllPrinters 字符串

....
AllPrinters := '';
....
for I := 0 to WbemObjectSet.Count - 1 do
    begin
      Printer := WbemObjectSet.ItemIndex(I);
      if not VarIsNull(Printer) then
      begin
        Log(Printer.Name);
        AllPrinters := AllPrinters + Printer.Name + #13#10;
      end;
    end;
end;

ListBoxPrinters.Items.Text := AllPrinters;

您将项目(打印机)添加到列表框中的方式相同,原始代码将它们添加到日志中:在循环中!

for I := 0 to WbemObjectSet.Count - 1 do
begin
  Printer := WbemObjectSet.ItemIndex(I);
  if not VarIsNull(Printer) then
  begin
    ListBoxPrinters.Items.Add(Printer.Name);
  end;
end;

当然,在迭代打印机之前,您必须使用 ListBoxPrinters 创建自定义页面。


如果您在创建页面后出于任何原因无法 运行 查询,您可以将打印机列表存储到 TStringList

var
  Printers: TStringList;
Printers := TStringList.Create;

for I := 0 to WbemObjectSet.Count - 1 do
begin
  Printer := WbemObjectSet.ItemIndex(I);
  if not VarIsNull(Printer) then
  begin
    Printers.Add(Printer.Name);
  end;
end;

准备好列表框后,只需将列表复制到框中即可:

ListBoxPrinters.Items.Assign(Printers);