Author: Peter Thörnqvist
How can I make the Save dialog automatically change the file extension of the
filename when the user selects a different Filter?
Answer:
The solution to this problem is to handle the OnTypeChange event of the TSaveDialog
and directly send a message to the dialog. Start by assigning an event handler for
the OnTypeChange event (this is called whenever the user selects a different filter
in the dialog). Delphi keeps track of which FilterIndex is currently selected even
when the dialog is open, so we can write the following code:
1
2 procedure TForm1.SaveDialogTypeChange(Sender: TObject);
3 var
4 buf: array[0..MAX_PATH] of char;
5 S: string;
6 od: TSaveDialog;
7 H: THandle;
8 begin
9 // get a pointer to the dialog
10 od := (Sender as TSaveDialog);
11 // Send the message to the dialogs parent so it can handle it the normal way
12 H := GetParent(od.Handle);
13 // get the currently entered filename
14 SendMessage(H, CDM_GETSPEC, MAX_PATH, integer(@buf));
15 S := buf;
16 // change the extension to the correct one
17 case od.FilterIndex of
18 1:
19 S := ChangeFileExt(S, '.rtf');
20 2:
21 S := ChangeFileExt(S, '.html');
22 3:
23 S := ChangeFileExt(S, '.txt');
24 end;
25 // finally, change the currently selected filename in the dialog
26 SendMessage(H, CDM_SETCONTROLTEXT, edt1, integer(PChar(S)));
27 end;
In the example, I have three filters for RTF, HTML and TXT and the code changes the
extension to the correct one simply by calling ChangeFileExt on the existing
filename. The CDM_* constants are defined in CommDlg.pas, so you must add this to
your uses clause (or redeclare them in your unit). The constant edt1 is taken from
the file Dlgs.pas where every constant used in the common dialogs are listed. edt1
is the first edit control on any common dialog, edt2 the second etc.
|