简体   繁体   English

TSaveDialog文件扩展名和[ofOverwritePromt]问题

[英]TSaveDialog file extension and [ofOverwritePromt] issue

There is a simple question already about the idea of the TSaveDialog and [ofOverwritePromt] at Delphi overwrite existing file on save dialog . 关于TSaveDialog和Delphi的 [ofOverwritePromt]的概念已经存在一个简单的问题,它会在保存对话框中覆盖现有文件

So my issue/scenario is following: 所以我的问题/场景如下:

  • I have a TSaveDialog 我有一个TSaveDialog
  • I set the [ofOverwritePromt] in Options 我在Options设置了[ofOverwritePromt]
  • I set the filter to "PDF (*.pdf)|*.pdf" 我将过滤器设置为“PDF(* .pdf)| * .pdf”
  • Filter index is set to 1 过滤器索引设置为1

So now I execute the program and call the dialog. 所以现在我执行程序并调用对话框。 If the file I select WITH MOUSE or KEYBOARD (without typing) exists then save dialog asks me to overwrite with the message: 如果我选择WITH MOUSE或KEYBOARD(没有输入)的文件存在,则保存对话框要求我用消息覆盖:

保存对话框

But if I do the same actions but type the filename like 'Test' without specifying the extension the save dialog does not confirm overwrite. 但是,如果我执行相同的操作但输入文件名如'Test'而未指定扩展名,则保存对话框不会确认覆盖。 I know that actually it returns another filename "C:\\Users\\xxx\\Desktop\\Test" instead of "C:\\Users\\xxx\\Desktop\\Test.pdf". 我知道实际上它返回另一个文件名“C:\\ Users \\ xxx \\ Desktop \\ Test”而不是“C:\\ Users \\ xxx \\ Desktop \\ Test.pdf”。 It is kind of not nice if the dialog asks you to save the file, but you need to type the extension.. So usually I handle it like this: 如果对话框要求您保存文件,但是您需要键入扩展名,这有点不太好。所以通常我会像这样处理它:

repeat
  { Ask for the file if not silent }
  if not dlgSave.Execute then
    Exit;

  { Read the filename from the save dialog }
  LTempFile := dlgSave.FileName;
  if not SameText(ExtractFileExt(LTempFile), '.pdf') then
    begin
      { Add the extension }
      LTempFile := LTempFile + '.pdf';

      { As we bypassed the overwrite check in dialog do it now }
      if FileExists(LTempFile) then
        if MsgWarn(Format('%s already exists. Replace?', [ExtractFileName(LTempFile)]), mbOKCancel) <> mrOk then
          Continue;
    end;

  Break;
until False;

Is there a way to do that more elegant without customizing the standard dialog ? 有没有办法在没有自定义标准对话框的情况下更优雅?

My guess is that you do not set DefaultExt , which is why you get a blank extension returned. 我的猜测是你没有设置DefaultExt ,这就是你返回空白扩展名的原因。 Use this property and you won't get the problem. 使用此属性,您将不会遇到问题。 If you use multiple filters, use the OnFilterChange event. 如果使用多个过滤器,请使用OnFilterChange事件。 Here is one way to do it: 这是一种方法:

procedure TFormMain.SigSaveDialogMainTypeChange(Sender: TObject);
begin
  case (Sender as TSaveDialog).FilterIndex of
    0: (Sender as TSaveDialog).DefaultExt := 'pdf';
    1: (Sender as TSaveDialog).DefaultExt := 'txt';
  end;
end;

It also means you don't have to check for the extension and change it! 这也意味着您无需检查扩展并进行更改!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM