Sunday, August 15, 2010

Generic method to invoke a save dialog

There are many times when you need to invoke a Save dialog(TSaveDialog) and more likely you do NOT wish to add another component on the form... here's what I came up with:
(add "Dialogs" to uses clause)
function SaveFileExecute(const Filter: string;
  var FileName: string): Boolean;
  SaveDialog: TSaveDialog;
  // variable used to let us know that the user is intending to save
  // it will cover the "Overwrite file" prompt
  bExecuted: Boolean;
  // label used to retry the save process
// label!!
  // initialize variable and result
  bExecuted := False;
  Result := False;
  // create a TSaveDialog instance
  SaveDialog := TSaveDialog.Create(NIL);
    // set the filter
    SaveDialog.Filter := Filter;
    // execute the dialog
    Result := SaveDialog.Execute;
    // store the result
    bExecuted := Result;
    if Result then begin
      // set the file name WARNING it's a OUT VARIABLE
      FileName := SaveDialog.FileName;
      // check if the user tries to overwrite file
      if FileExists(FileName) then
        // user is attempting to overwrite a file, prompt with
        // Yes, No and Cancel, some users feel more comfortable to click Cancel
        Result := (MessageDlg(
          Format('File "%s" already exists, overwrite?', [FileName]),
          mtConfirmation, mbYesNoCancel, 0) = mrYes);
    end; // if Result then begin
    // free allocated memory
  end; // tryf
  if (NOT Result) and bExecuted then
    // user selected No or Cancel in file overwrite, restart the process
    goto lRetry;

No comments:

Post a Comment

Blogroll(General programming and Delphi feeds)