在Windows 7 中有些我們經常使用的庫(Libraries),例如:音樂庫、文件庫、視頻庫、圖片庫等。還有幾十個系統已知檔案夾(Known Folders),System、Windows、My Music等。本篇將介紹如何通過Windows API Code Pack 在應用程式中調用這些公用檔案夾。
將Microsoft.WindowsAPICodePack.dll、Microsoft.WindowsAPICodePack.Shell.dll 加入項目中,編寫如下XAML 代碼,兩個<ComboBox> 用來顯示Known Folders 和Libraries 選項。
<Grid> <Label Content="Know Folders:" Height="30" Width="100" Margin="47,70,356,211" /> <Label Content="Libraries:" Height="30" Width="100" Margin="48,191,355,90" /> <ComboBox x:Name="knowFolders" Width="200" Height="25" Margin="186,70,117,211" /> <ComboBox x:Name="libraries" Width="200" Height="25" Margin="186,190,117,90" /> <Button x:Name="openKF" Click="openKF_Click" Content="Open Dialog" Height="30" Width="90" Margin="296,126,116,155" /> <Button x:Name="openLB" Click="openLB_Click" Content="Open Dialog" Height="30" Width="90" Margin="296,250,117,31" /></Grid>
在C# 中加入如下命名空間,Shell 用於支援載入公用檔案夾,Dialogs用於調用檔案夾對話方塊。
using Microsoft.WindowsAPICodePack.Shell;using Microsoft.WindowsAPICodePack.Dialogs;
接下了編寫一個ComboBox 載入方法填充上面提到的兩個<ComboBox> 內容,通過IKnownFolder 介面擷取所有KnownFolders 類中的系統已知檔案夾。
private void LoadCombox(){ knowFolders.Items.Clear(); foreach (IKnownFolder kf in KnownFolders.All) { if (kf != null && kf.CanonicalName != null) { knowFolders.Items.Add(kf.CanonicalName); } } if (knowFolders.Items.Count > 0) { SortDescription kfSort = new SortDescription(); knowFolders.Items.SortDescriptions.Add(kfSort); knowFolders.SelectedIndex = 0; } libraries.Items.Clear(); libraries.Items.Add("Documents"); libraries.Items.Add("Music"); libraries.Items.Add("Pictures"); libraries.Items.Add("Videos"); libraries.SelectedIndex = 0;}
Known Foloder “Open Dialog” 按鈕Click 事件,通過CommonOpenFileDialog 類建立對話方塊,將KnowFolder 初始化為ShellContainer。
private void openKF_Click(object sender, RoutedEventArgs e){ CommonOpenFileDialog cfd = new CommonOpenFileDialog(); string kfString = knowFolders.SelectedItem as string; IKnownFolder kf = KnownFolderHelper.FromCanonicalName(kfString); cfd.InitialDirectoryShellContainer = kf as ShellContainer; cfd.ShowDialog();}
Libraries “Open Dialog” 按鈕Click 事件:
private void openLB_Click(object sender, RoutedEventArgs e){ string selection = libraries.SelectedItem as string; ShellContainer selectedFolder = null; switch (selection) { case "Documents": selectedFolder = KnownFolders.DocumentsLibrary as ShellContainer; break; case "Music": selectedFolder = KnownFolders.MusicLibrary as ShellContainer; break; case "Pictures": selectedFolder = KnownFolders.PicturesLibrary as ShellContainer; break; case "Videos": selectedFolder = KnownFolders.VideosLibrary as ShellContainer; break; } CommonOpenFileDialog cfd = new CommonOpenFileDialog(); cfd.EnsureReadOnly = true; cfd.InitialDirectoryShellContainer = selectedFolder; cfd.ShowDialog();}
編譯測試:
原始碼
CommonFileDialog.zip