- Save File Dialog. Open File Метод
- Определение
- Возвращаемое значение
- Примеры
- Комментарии
- SaveFileDialog.Filter Property
- Syntax
- Property Value
- Exceptions
- Remarks
- Examples
- Common Item Dialog
- IFileDialog, IFileOpenDialog, and IFileSaveDialog
- Sample Usage
- Basic Usage
- Limiting Results to File System Items
- Specifying File Types for a Dialog
- Controlling the Default Folder
- Adding Items to the Places Bar
- State Persistence
- Multiselect Capabilities
- Listening to Events from the Dialog
- OnFileOk
- OnShareViolation and OnOverwrite
- Customizing the Dialog
- Adding Options to the OK Button
- Responding to Events in Added Controls
- Full Samples
Save File Dialog. Open File Метод
Определение
Открывает выбранный пользователем файл с разрешением на чтение и запись. Opens the file with read/write permission selected by the user.
Возвращаемое значение
Выбранный пользователем файл с разрешением на чтение и запись. The read/write file selected by the user.
Примеры
В следующем примере кода показано создание SaveFileDialog , установка элементов, вызов диалогового окна с помощью ShowDialog метода и открытие выбранного файла. The following code example illustrates creating a SaveFileDialog, setting members, calling the dialog box using the ShowDialog method, and opening the selected file. Для примера требуется форма с размещенной на ней кнопкой. The example requires a form with a button placed on it.
Комментарии
В целях безопасности этот метод создает новый файл с выбранным именем и открывает его с разрешениями на чтение и запись. For security purposes, this method creates a new file with the selected name and opens it with read/write permissions. Это может привести к непреднамеренной потере данных, если выбрать существующий файл для сохранения. This can cause unintentional loss of data if you select an existing file to save to. Чтобы сохранить данные в существующий файл с сохранением существующих данных, используйте класс, File чтобы открыть файл, используя имя файла, возвращенное в FileName свойстве. To save data to an existing file while retaining existing data, use the File class to open the file using the file name returned in the FileName property.
SaveFileDialog.Filter Property
Microsoft Silverlight will reach end of support after October 2021. Learn more.
Gets or sets a filter string that specifies the files types and descriptions to display in the SaveFileDialog.
Namespace: В System.Windows.Controls
Assembly: В System.Windows (in System.Windows.dll)
Syntax
Property Value
Type: System.String
A filter string that specifies the file types and descriptions to display in the SaveFileDialog. The default is Empty.
Exceptions
The filter string does not contain at least one vertical bar (|).
Remarks
If the Filter property is Empty, all files are displayed. Folders are always displayed.
Filter consists of a description of the filter followed by a vertical bar (|) and the filter pattern. The filter can specify one or more file types.
The description describes the type of files shown in the dialog box. Although the description can be any string, it usually consists of the type of files included in the filter followed by the parentheses that contain the extensions associated with the description. The filter description appears in the Save as type drop-down list of the dialog box. The following is an example of a filter description.
The filter pattern determines which files are shown by the dialog box. Filter patterns for the same description are separated by a semicolon (;). You can specify an exact match or use the wildcard character (*) in combination with the dot character (.) to specify file name or extension matches.
The following is an example of a filter description followed by multiple filter patterns. This example adds Image Files (*.bmp, *.jpg) to the Save as type drop-down list and shows .bmp and .jpg files when it is selected.
Image Files (*.bmp, *.jpg)|*.bmp;*.jpg
Multiple filter options are separated by the vertical bar.
The following is an example of multiple filter descriptions and patterns. This example adds Text Files (*.txt) and All Files (*.*) to the Save as type drop-down list. When Text Files (*.txt) is selected, .txt files are shown. When All Files (*.*) is selected, all file types are shown.
Text Files (*.txt)|*.txt|All Files (*.*)|*.*
Use the FilterIndex property to specify which filter appears first in the Save as type drop-down list. Otherwise, filter descriptions will appear in the order that they are listed in the Filter value.
If the specified filter does not contain at least one vertical bar, an exception will occur.
Examples
The following code example shows how to use the Filter property.
Common Item Dialog
Starting with WindowsВ Vista, the Common Item Dialog supersedes the older Common File Dialog when used to open or save a file. The Common Item Dialog is used in two variations: the Open dialog and the Save dialog. These two dialogs share most of their functionality, but each has its own unique methods.
While this newer version is named the Common Item Dialog, it continues to be called the Common File Dialog in most documentation. Unless you are dealing specifically with an older version of Windows, you should assume that any mention of the Common File Dialog refers to this Common Item Dialog.
The following topics are discussed here:
- IFileDialog, IFileOpenDialog, and IFileSaveDialog
- Sample Usage
- Listening to Events from the Dialog
- OnFileOk
- OnShareViolation and OnOverwrite
- Customizing the Dialog
- Adding Options to the OK Button
- Responding to Events in Added Controls
- Full Samples
- Related topics
IFileDialog, IFileOpenDialog, and IFileSaveDialog
WindowsВ Vista provides implementations of the Open and Save dialogs: CLSID_FileOpenDialog and CLSID_FileSaveDialog. Those dialog boxes are shown here.
IFileOpenDialog and IFileSaveDialog inherit from IFileDialog and share much of their functionality. In addition, the Open dialog supports IFileOpenDialog, and the Save dialog supports IFileSaveDialog.
The Common Item Dialog implementation found in WindowsВ Vista provides several advantages over the implementation provided in earlier versions:
- Supports direct use of the Shell namespace through IShellItem instead of using file system paths.
- Enables simple customization of the dialog, such as setting the label on the OK button, without requiring a hook procedure.
- Supports more extensive customization of the dialog by the addition of a set of data-driven controls that operate without a Win32 dialog template. This customization scheme frees the calling process from UI layout. Since any changes to the dialog design continue to use this data model, the dialog implementation is not tied to the specific current version of the dialog.
- Supports caller notification of events within the dialog, such as selection change or file type change. Also enables the calling process to hook certain events in the dialog, such as the parsing.
- Introduces new dialog features such as adding caller-specified places to the Places bar.
- In the Save dialog, developers can take advantage of new metadata features of the WindowsВ Vista Shell.
Additionally, developers can choose to implement the following interfaces:
- IFileDialogEvents to receive notifications of events within the dialog.
- IFileDialogCustomize to add controls to the dialog.
- IFileDialogControlEvents to be notified of events in those added controls.
The Open or Save dialog returns an IShellItem or IShellItemArray object to the calling process. The caller can then use an individual IShellItem object to get a file system path or to open a stream on the item to read or write information.
Flags and options available to the new dialog methods are very similar to the older OFN flags found in the OPENFILENAME structure and used in GetOpenFileName and GetSaveFileName. Many of them are exactly the same, except that they begin with an FOS prefix. The complete list can be found in the IFileDialog::GetOptions and IFileDialog::SetOptions topics. Open and Save dialogs are created by default with the most common flags. For the Open dialog, this is (FOS_PATHMUSTEXIST | FOS_FILEMUSTEXIST | FOS_NOCHANGEDIR) and for the Save dialog this is (FOS_OVERWRITEPROMPT | FOS_NOREADONLYRETURN | FOS_PATHMUSTEXIST | FOS_NOCHANGEDIR).
IFileDialog and its descendant interfaces inherit from and extend IModalWindow. Show takes as its only parameter the handle of the parent window. If Show returns successfully, there is a valid result. If it returns HRESULT_FROM_WIN32(ERROR_CANCELLED) , it means the user canceled the dialog. It might also legitimately return another error code such as E_OUTOFMEMORY.
Sample Usage
The following sections show example code for a variety of dialog tasks.
- Basic Usage
- Limiting Results to File System Items
- Specifying File Types for a Dialog
- Controlling the Default Folder
- Adding Items to the Places Bar
- State Persistence
- Multiselect Capabilities
Most of the sample code can be found in the Windows SDK Common File Dialog Sample.
Basic Usage
The following example illustrates how to launch an Open dialog. In this example, it is restricted to Microsoft Word documents.
NoteВ В Several examples in this topic use the CDialogEventHandler_CreateInstance helper function to create an instance of the IFileDialogEvents implementation. To use this function in your own code, copy the source code for the CDialogEventHandler_CreateInstance function from the Common File Dialog Sample, from which all of the examples in this topic are taken.
Limiting Results to File System Items
The following example, taken from above, demonstrates how to restrict results to file system items. Note that IFileDialog::SetOptions adds the new flag to a value obtained through IFileDialog::GetOptions. This is the recommended method.
Specifying File Types for a Dialog
To set specific file types that the dialog can handle, use the IFileDialog::SetFileTypes method. That method accepts an array of COMDLG_FILTERSPEC structures, each of which represents a file type.
The default extension mechanism in a dialog is unchanged from GetOpenFileName and GetSaveFileName. The file name extension that is appended to the text the user types in the file name edit box is initialized when the dialog opens. It should match the default file type (that selected as the dialog opens). If the default file type is «*.*» (all files), the file can be an extension of your choice. If the user chooses a different file type, the extension automatically updates to the first file name extension associated with that file type. If the user chooses «*.*» (all files), then the extension reverts to its original value.
The following example illustrates how this was done above.
Controlling the Default Folder
Almost any folder in the Shell namespace can be used as the default folder for the dialog (the folder presented when the user chooses to open or save a file). Call IFileDialog::SetDefaultFolder prior to calling Show to do so.
The default folder is the folder in which the dialog starts the first time a user opens it from your application. After that, the dialog will open in the last folder a user opened or the last folder they used to save an item. See State Persistence for more details.
You can force the dialog to always show the same folder when it opens, regardless of previous user action, by calling IFileDialog::SetFolder. However, we do not recommended doing this. If you call SetFolder before you display the dialog box, the most recent location that the user saved to or opened from is not shown. Unless there is a very specific reason for this behavior, it is not a good or expected user experience and should be avoided. In almost all instances, IFileDialog::SetDefaultFolder is the better method.
When saving a document for the first time in the Save dialog, you should follow the same guidelines in determining the initial folder as you did in the Open dialog. If the user is editing a previously existing document, open the dialog in the folder where that document is stored, and populate the edit box with that document’s name. Call IFileSaveDialog::SetSaveAsItem with the current item prior to calling Show.
Adding Items to the Places Bar
The following example demonstrates the addition of items to the Places bar:
State Persistence
Prior to WindowsВ Vista, a state, such as the last visited folder, was saved on a per-process basis. However, that information was used regardless of the particular action. For example, a video editing application would present the same folder in the Render As dialog as is would in the Import Media dialog. In WindowsВ Vista you can be more specific through the use of GUIDs. To assign a GUID to the dialog, call iFileDialog::SetClientGuid.
Multiselect Capabilities
Multiselect functionality is available in the Open dialog using the GetResults method as shown here.
Listening to Events from the Dialog
A calling process can register an IFileDialogEvents interface with the dialog by using the IFileDialog::Advise and IFileDialog::Unadvise methods as shown here.
This is taken from the Basic Usage sample.
The bulk of the dialog processing would be placed here.
The calling process can use events for notification when the user changes the folder, file type, or selection. These events are particularly useful when the calling process has added controls to the dialog (see Customizing the Dialog) and must change the state of those controls in reaction to these events. Useful in all cases is the ability of the calling process to provide custom code to deal with situations such as sharing violations, overwriting files, or determining if a file is valid before the dialog closes. Some of those cases are described in this section.
OnFileOk
This method is called after the user chooses an item, just before the dialog closes. The application can then call IFileDialog::GetResult or IFileOpenDialog::GetResults as would be done once the dialog had closed. If the item chosen is acceptable, they can return S_OK. Otherwise, they return S_FALSE and display UI that tells the user why the chosen item is not valid. If S_FALSE is returned, the dialog does not close.
The calling process can use the window handle of the dialog itself as the parent of the UI. That handle can be obtained by first calling IOleWindow::QueryInterface and then calling IOleWindow::GetWindow with the handle as shown in this example.
OnShareViolation and OnOverwrite
If the user chooses to overwrite a file in the Save dialog, or if a file being saved or replaced is in use and cannot be written to (a sharing violation), the application can provide custom functionality to override the default behavior of the dialog. By default, when overwriting a file, the dialog displays a prompt allowing the user to verify this action. For sharing violations, by default the dialog displays an error message, it does not close, and the user is required to make another choice. The calling process can override these defaults and display its own UI if desired. The dialog can be instructed to refuse the file and remain open or accept the file and close successfully.
Customizing the Dialog
A variety of controls can be added to the dialog without supplying a Win32 dialog template. These controls include PushButton, ComboBox, EditBox, CheckButton, RadioButton lists, Groups, Separators, and Static Text controls. Call QueryInterface on the dialog object (IFileDialog, IFileOpenDialog, or IFileSaveDialog) to obtain an IFileDialogCustomize pointer. Use that interface to add controls. Each control has an associated caller-supplied ID as well as a visible and enabled state that can be set by the calling process. Some controls, such as PushButton, also have text associated with them.
Multiple controls can be added into a «visual group» that moves as a single unit in the layout of the dialog. Groups can have a label associated with them.
Controls can be added only before the dialog is shown. However, once the dialog is displayed, controls can be hidden or shown as desired, perhaps in response to user action. The following examples show how to add a radio button list to the dialog.
Adding Options to the OK Button
Similarly, choices can be added to the Open or Save buttons, which are the OK button for their respective dialog types. The options are accessible through a drop-down list box attached to the button. The first item in the list becomes the text for the button. The following example shows how to provide an Open button with two possibilities: «Open» and «Open as read-only».
The user’s choice can be verified after the dialog returns from the Show method as you would for a ComboBox, or it can verified as part of the handling by IFileDialogEvents::OnFileOk.
Responding to Events in Added Controls
The events handler provided by the calling process can implement IFileDialogControlEvents in addition to IFileDialogEvents. IFileDialogControlEvents enables the calling process to react to these events:
- PushButton clicked
- CheckButton state changed
- Item selected from a menu, ComboBox, or RadioButton list
- Control activating. This is sent when a menu is about to display a drop-down list, in case the calling process wants to change the items in the list.
Full Samples
The following are complete, downloadable C++ samples from the Windows Software Development Kit (SDK) which demonstrate the use of and interaction with the Common Item Dialog.