我如何 select Delphi 中的文件

How can i select a file in Delphi

我需要制作 'Graphic User Interface' 并且我需要一些 VCL 组件来 select 一些文件。

此组件必须select文件,但用户不必输入文件名。

我正在搜索信息,但没有任何帮助。

Vcl.Dialogs.TOpenDialog 可用于此目的。

另见 UsingDialogs

procedure TForm1.Button1Click(Sender: TObject);
var
  selectedFile: string;
  dlg: TOpenDialog;
begin
  selectedFile := '';
  dlg := TOpenDialog.Create(nil);
  try
    dlg.InitialDir := 'C:\';
    dlg.Filter := 'All files (*.*)|*.*';
    if dlg.Execute(Handle) then
      selectedFile := dlg.FileName;
  finally
    dlg.Free;
  end;

  if selectedFile <> '' then
    <your code here to handle the selected file>
end;

请注意,此处的示例假设将名为 Button1TButton 拖放到表单中,并将 TForm1.Button1Click(Sender: TObject) 过程分配给按钮 OnClick 事件。


可以在 TOpenDialog.Filter 属性 中使用多个文件扩展名,方法是使用 |(竖线)字符将它们连接在一起,如下所示:

'AutoCAD drawing|*.dwg|Drawing Exchange Format|*.dxf'

我找到了我的问题。 我的问题是我没有制作任何按钮来打开对话框。 我做了一个 TEdit。这个 Tedit 有这样的程序 (Onlclik):

procedure TForm1.SelectFile(Sender: TObject);
begin

  openDialog := TOpenDialog.Create(self);
  openDialog.InitialDir := 'C:\';
  openDialog.Options := [ofFileMustExist];

  // Allow only .dpr and .pas files to be selected
  openDialog.Filter :=
    'All files (*.*)|*.*';
  // Display the open file dialog
  if openDialog.Execute
  then ShowMessage('File : '+openDialog.FileName)
  else ShowMessage('Open file was cancelled');

  // Free up the dialog
  openDialog.Free;

end;