作者:
桂素偉 來源:
博客園 發布時間: 2009-10-30 11:37 閱讀: 1440 次 推薦: 0
原文鏈接 [收藏]
在我們使用windows系統時,我們常看到系統有很多類型,比如word的文檔類型,它是以doc擴展名標識的,還有pdf,html,aspx等等,一但我們安裝某些程序,相應類型程序的文檔就可以打開進行編輯了。今天,我們也創建自己的一個類型,并結合JumpList的Recent來開發我們的應用。
如何讓windows系統認識自己的類型,其實就是把我們的類型注冊到注冊表里的HKEY_CLASSES_ROOT下,具體注冊信息,詳看下面代碼。
代碼如下:
1
//注冊應用程序文件和圖標
2
RegistryKey classesRoot = Registry.ClassesRoot;
3
private static void RegisterProgId(string progId, string appId,
4
string openWith, string IcoPath)
5
{
6
7
RegistryKey progIdKey = classesRoot.CreateSubKey(progId);
8
progIdKey.SetValue("FriendlyTypeName", "@shell32.dll,-8975");
9
progIdKey.SetValue("DefaultIcon", "@shell32.dll,-47");
10
progIdKey.SetValue("CurVer", progId);
11
progIdKey.SetValue("AppUserModelID", appId);
12
13
RegistryKey shell = progIdKey.CreateSubKey("shell");
14
shell.SetValue(String.Empty, "Open");
15
shell = shell.CreateSubKey("Open");
16
shell = shell.CreateSubKey("Command");
17
shell.SetValue(String.Empty, openWith);
18
19
RegistryKey iconKey = progIdKey.CreateSubKey("DefaultIcon");
20
iconKey.SetValue("", IcoPath);
21
22
shell.Close();
23
progIdKey.Close();
24
}
25
//注冊類型
26
private static void RegisterFileAssociation(string progId, string extension)
27
{
28
RegistryKey openWithKey = classesRoot.CreateSubKey(
29
Path.Combine(extension, "OpenWithProgIds"));
30
openWithKey.SetValue(progId, String.Empty);
31
openWithKey.Close();
32
}
33
在這個方法中,后兩個參數是比較重要的,openWith參數應用程序所以在路徑和附加參數,IcoPath是應用程對應的圖標。通過這一步,我們就能把自己的類型注冊到系統中,具體的類型依照extension參數來提供。
這樣,如果在系統下建立一個extension實參為類型的文件時,我們看到的將是以對應圖標替換的文件,雙擊,調用的是我們剛才注冊的應用程序。
比如,我們現在注冊的是diar,在系統下,所有以diar為擴展名的文件,都成為可執行文件了。
但怎么通過雙擊把文件的內容加載到應用程序中呢?
代碼如下,在應用程序的加載時執行:
1
string[] parameters = Environment.GetCommandLineArgs();
2
if (parameters.Length > 1)
3

{
4
filePath = parameters[1];
5
//filePath傳過來的就是雙擊的文件的路徑,這樣我們就可以通過IO來操作這個文件了
6
}
7
其實上面這些知識不是Windows7 JumpList所特有的,怎么和JumpList中的知識關聯呢?
在JumpList中,有一個Recent類別,就是最近打開的文件。其實系統有一個RecentList,會保存最近打開的文檔,這個列表只有在兩種情況下向其中添加子項,第一種就是上面我們在注冊完類型后,雙擊文檔時會添加到RecentList中。另一種情部下面說明。
看下面代碼:
1
private void OpenDiaryFile()
2
{
3
CommonOpenFileDialog dialog = new CommonOpenFileDialog();
4
dialog.Title = "Select a diary document";
5
dialog.Filters.Add(new CommonFileDialogFilter("Text files (*.diar)", "*.diar"));
6
CommonFileDialogResult result = dialog.ShowDialog();
7
if (result == CommonFileDialogResult.OK)
8
{
9
filePath = dialog.FileName;
10
Content_TB.Text = File.ReadAllText(dialog.FileName, Encoding.Default);
11
jumplist.AddToRecent(dialog.FileName);
12
jumplist.KnownCategoryToDisplay = JumpListKnownCategoryType.Recent;//最近 // jumplist.KnownCategoryToDisplay = JumpListKnownCategoryType.Frequent ;//常用
13
jumplist.Refresh();
14
}
15
這段代碼不難理解,就是用一個定義好的CommonOpenFileDialog對話框來打開一個文件。這里的CommonOpenFileDialog是Windows 7 Training Kit For Developers的一個類,必需調用這個類,我們才能用jumplist.AddToRecent(dialog.FileName)把最近文件添加到RecentList中。
文章列表