2009. szeptember 28., hétfő

Changing folder in Open/Save dialogs


Problem/Question/Abstract:

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.

Answer:

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);
var
  S, S1: string;
  EditHandle: THandle;
  startp,
    endp: DWORD;
begin
  s := '';
  if SaveDialog.FilterIndex = 2 then
  begin
    s := 'c:\program files';
  end
  else if SaveDialog.FilterIndex = 3 then
  begin
    s := 'd:\program files';
  end;
  if s <> '' then
  begin
    EditHandle := GetDlgItem(GetParent(SaveDialog.Handle), edt1);
    if EditHandle <> 0 then
    begin
      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);
    end;
  end;
end;

Nincsenek megjegyzések:

Megjegyzés küldése