东海一隅

是以圣人之治,实其腹,虚其心,弱其志,常使民无知无欲。

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

需求很简单:双击我的一个自定义扩展名的文件,打开相应的应用程序进行处理.查了一些资料,终于把它弄出来,在这里记录一下,以备查用.

①用到"Microsoft.Win32"命名空间.

using Microsoft.Win32;

 

② 检查一下文件类型是否已被注册.

public static bool FileTypeRegistered(string extension)
{
            RegistryKey sluKey 
= Registry.ClassesRoot.OpenSubKey(extension);
            
if (sluKey != null)
                
return true;
            
return false;
}

 ③ 删除已被注册的键值

public static void UnRegistFileType(string extension)
{
            
if (FileTypeRegistered(extension))
            {
                Registry.ClassesRoot.DeleteSubKey(extension); 
                
string relationName = extension.Substring(1, extension.Length - 1).ToUpper() + " FileType";
                Registry.ClassesRoot.DeleteSubKeyTree(relationName);
                Registry.ClassesRoot.Close();
            }
}

 ④ 注册自定义文件,并与自己的应用程序相关联

public static void RegistFileType(string extension)
{
            UnRegistFileType(extension);
            
string relationName = extension.Substring(1, extension.Length - 1).ToUpper() + " FileType";
            RegistryKey sluKey 
= Registry.ClassesRoot.CreateSubKey(extension);
            sluKey.SetValue(
"", relationName);
            sluKey.Close();

            RegistryKey relationKey 
= Registry.ClassesRoot.CreateSubKey(relationName);
            relationKey.SetValue(
"""Your Description");

            RegistryKey iconKey 
= relationKey.CreateSubKey("DefaultIcon");//图标
            iconKey.SetValue(
"", System.Windows.Forms.Application.StartupPath + @"\mainICO.ico");

            RegistryKey shellKey 
= relationKey.CreateSubKey("Shell");
            RegistryKey openKey 
= shellKey.CreateSubKey("Open");
            RegistryKey commandKey 
= openKey.CreateSubKey("Command");
            commandKey.SetValue(
"", System.Windows.Forms.Application.ExecutablePath + " %1");//是数字"1",双击文件之后就把文件的路径传递过来了.
            relationKey.Close();
}

 ⑤ 修改默认Main()函数,使之能接收参数

[STAThread]
static void Main(string[] args)
{
            
if (args != null && args.Length > 0)
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(
false);
                Application.Run(
new MainForm(args[0]));
            }
            
else
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(
false);
                Application.Run(
new MainForm());
            }
}

 ⑥在主窗体构造函数中实现自己的业务逻辑...

 

不知道大家有没有更好的解决方案,一起学习一下.

posted on 2008-08-11 18:52  东海一隅  阅读(1523)  评论(0编辑  收藏  举报