3. Writing the Explorer Browser Example Code
The Explorer Browser example doesn't contain a lot of code, yet you can do quite a bit with it because the ExplorerBrowser control provides a lot of functionality by itself. When you start this example, you can choose any of the KnownFolder entries and see where this takes you in the right Browser pane. Listing 1 shows the code needed for this example.
Example 1. Using the Explorer Browser control to create an interesting interface
public frmMain() { // Perform the standard initialization. InitializeComponent();
// Initialize the folder list. foreach (IKnownFolder Folder in KnownFolders.All) lstFolders.Items.Add(Folder.CanonicalName);
// Choose an initial folder. lstFolders.SelectedItem = KnownFolders.Documents.CanonicalName; Browser.Navigate(ShellFileSystemFolder.FromFolderPath( KnownFolders.Documents.Path)); }
private void lstFolders_SelectedIndexChanged(object sender, EventArgs e) { try {
// Locate the selection. foreach (IKnownFolder Folder in KnownFolders.All)
// Compare the folder name to the selected name. if (Folder.CanonicalName == lstFolders.Text) {
// Change the selected folder. Browser.Navigate( ShellFileSystemFolder.FromFolderPath( Folder.Path));
// Exit the loop. break; } } catch { // Display an error message. MessageBox.Show("Can't select the specified item."); } }
|
The code begins with the frmMain() constructor. The example performs the standard initialization. It then fills lstFolders with the names of all the KnownFolder entries using a foreach loop. The CanonicalName property provides the most readable entries. The ComboBox control automatically sorts the names for you.
It's also important to provide an initial selection. The example uses the KnownFolders.Documents entry for this purpose. Setting lstFolders means changing the SelectedItem property to the appropriate CanonicalName value. To set the Browser display, the code relies on the Navigate() method. You must provide a ShellFileSystemFolder or a ShellFile object in most cases (any appropriate ShellObject should work). The example uses the ShellFileSystemFolder.FromFolderPath() method to obtain the appropriate value. In this case, the value is from KnownFolders.Documents.Path. At this point, the application presents an initial display similar to the one shown in Figure 3.
After the user makes a selection, the example calls lstFolders_SelectedIndexChanged(). The lstFolders.Items
collection contains a list of canonical names, not paths. The first
task the code performs is to match the canonical name in an IKnownFolder object, Folder, with the canonical name the user has selected. When the two CanonicalName property values match, the code extracts a path from Folder. It then calls Browser.Navigate() to set the Browser display.