在我们使用
windows
系统时,我们常看到系统有很多类型,比如
word
的文档类型,它是以
doc
扩展名标识的,还有
pdf
,
html
,
aspx
等等,一但我们安装某些程序,相应类型程序的文档就可以打开进行编辑了。今天,我们也创建自己的一个类型,并结合
JumpList
的
Recent
来开发我们的应用。
<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />
如何让
windows
系统认识自己的类型,其实就是把我们的类型注册到注册表里的
HKEY_CLASSES_ROOT
下,具体注册信息,详看下面代码。
代码如下:
//
注册应用程序文件和图标
RegistryKey classesRoot = Registry.ClassesRoot;
private static void RegisterProgId(string progId, string appId,
string openWith, string IcoPath)
{
RegistryKey progIdKey = classesRoot.CreateSubKey(progId);
progIdKey.SetValue("FriendlyTypeName", "@shell32.dll,-8975");
progIdKey.SetValue("DefaultIcon", "@shell32.dll,-47");
progIdKey.SetValue("CurVer", progId);
progIdKey.SetValue("AppUserModelID", appId);
RegistryKey shell = progIdKey.CreateSubKey("shell");
shell.SetValue(String.Empty, "Open");
shell = shell.CreateSubKey("Open");
shell = shell.CreateSubKey("Command");
shell.SetValue(String.Empty, openWith);
RegistryKey iconKey = progIdKey.CreateSubKey("DefaultIcon");
iconKey.SetValue("", IcoPath);
shell.Close();
progIdKey.Close();
}
//
注册类型
private static void RegisterFileAssociation(string progId, string extension)
{
RegistryKey openWithKey = classesRoot.CreateSubKey(
Path.Combine(extension, "OpenWithProgIds"));
openWithKey.SetValue(progId, String.Empty);
openWithKey.Close();
}
在这个方法中,后两个参数是比较重要的,
openWith
参数应用程序所以在路径和附加参数,
IcoPath
是应用程对应的图标。通过这一步,我们就能把自己的类型注册到系统中,具体的类型依照
extension
参数来提供。
这样,如果在系统下建立一个
extension
实参为类型的文件时,我们看到的将是以对应图标替换的文件,双击,调用的是我们刚才注册的应用程序。
比如,我们现在注册的是
diar
,在系统下,所有以
diar
为扩展名的文件,都成为可执行文件了。
但怎么通过双击把文件的内容加载到应用程序中呢?
代码如下,在应用程序的加载时执行:
string[] parameters = Environment.GetCommandLineArgs();
if (parameters.Length > 1)
{
filePath = parameters[1];
//filePath
传过来的就是双击的文件的路径,这样我们就可以通过
IO
来操作这个文件了
}
其实上面这些知识不是
Windows7 JumpList
所特有的,怎么和
JumpList
中的知识关联呢?
在
JumpList
中,有一个
Recent
类别,就是最近打开的文件。其实系统有一个
RecentList
,会保存最近打开的文档,这个列表只有在两种情况下向其中添加子项,第一种就是上面我们在注册完类型后,双击文档时会添加到
RecentList
中。另一种情部下面说明。
看下面代码:
private void OpenDiaryFile()
{
CommonOpenFileDialog dialog = new CommonOpenFileDialog();
dialog.Title = "Select a diary document";
dialog.Filters.Add(new CommonFileDialogFilter("Text files (*.diar)", "*.diar"));
CommonFileDialogResult result = dialog.ShowDialog();
if (result == CommonFileDialogResult.OK)
{
filePath = dialog.FileName;
Content_TB.Text = File.ReadAllText(dialog.FileName, Encoding.Default);
jumplist.AddToRecent(dialog.FileName);
jumplist.KnownCategoryToDisplay = JumpListKnownCategoryType.Recent;//
最近
// jumplist.KnownCategoryToDisplay = JumpListKnownCategoryType.Frequent ;//
常用
jumplist.Refresh();
}
这段代码不难理解,就是用一个定义好的
CommonOpenFileDialog
对话框来打开一个文件。这里的
CommonOpenFileDialog
是
Windows 7 Training Kit For Developers
的一个类,必需调用这个类,我们才能用
jumplist.AddToRecent(dialog.FileName)
把最近文件添加到
RecentList
中。