Changing folder in Open/Save dialogs (Views: 101)


It is possible to specify initial folder in Open/Save dialogs. However sometimes it is necessary to change current folder, for example, in responce to change of filter.


Windows doesn't offer a way to change current dialog. However there is a very handy approach to this problem - imitate user actions. Below is the sample code of how the folder is changed when filter is changed.

procedure SaveDialogTypeChange is a handler for OnTypeChange event.
Depending on the type different folders are selected. This piece of code saves the value of file name edit box, puts a new folder name there, then imitates click of OK button and then restores contents of the edit box.
Add Dlgs to "uses" clause of your unit.

procedure TMainForm.SaveDialogTypeChange(Sender: TObject);
  S, S1: string;
  EditHandle: THandle;
    endp: DWORD;
  s := '';
  if SaveDialog.FilterIndex = 2 then
    s := 'c:\program files';
  else if SaveDialog.FilterIndex = 3 then
    s := 'd:\program files';
  if s <> '' then
    EditHandle := GetDlgItem(GetParent(SaveDialog.Handle), edt1);
    if EditHandle <> 0 then
      SetLength(S1, GetWindowTextLength(EditHandle) + 1);
      GetWindowText(EditHandle, PChar(S1), Length(S1));
      SetLength(S1, StrLen(PChar(S1)));
      SendMessage(EditHandle, EM_GETSEL, Integer(@StartP), Integer(@EndP));
      SetWindowText(EditHandle, PChar(S));
      SendMessage(GetParent(SaveDialog.Handle), WM_COMMAND, 1,
        GetDlgItem(GetParent(SaveDialog.Handle), IDOK));
      if Length(S1) > 0 then
        if S1[Length(S1)] = #10 then
          Delete(S1, Length(S1), 1);
      SetWindowText(EditHandle, PChar(S1));
      SendMessage(EditHandle, EM_SETSEL, StartP, EndP);

<< Back to main page