现在的位置: 首页 > 综合 > 正文

C#、VB.NET将自己的程序注册到系统的右键菜单(所有文件和目录)

2012年04月18日 ⁄ 综合 ⁄ 共 972字 ⁄ 字号 评论关闭
文章目录

今天,有个网友问:

如何将自己的程序,注册到系统的右键菜单呢? 像 winrar, 杀毒软件那样

其实实现起来,很简单的,就是一个注册表操作而已,我写了一个实例,可以实现此功能,并获取调用自己的来源文件的路径。

核心代码:

private void button1_Click(object sender, EventArgs e)
{
    string menuName = string.IsNullOrEmpty(this.textBox1.Text.Trim()) ? "真有意思网" : this.textBox1.Text.Trim();
    
    //注册到所有文件
    if (chkFile.Checked)
    {
        RegistryKey shell = Registry.ClassesRoot.OpenSubKey(@"*\shell", true);
        RegistryKey custom = shell.CreateSubKey(menuName);
        RegistryKey cmd = custom.CreateSubKey("command");
        cmd.SetValue("", Application.ExecutablePath + " %1");
        //Application.ExecutablePath 是本程序自身的路径
        //%1 是传入打开的文件路径
        cmd.Close();
        custom.Close();
        shell.Close();
    }

    //注册到所有目录
    if (chkFile.Checked)
    {
        RegistryKey shell = Registry.ClassesRoot.OpenSubKey(@"directory\shell", true);
        RegistryKey custom = shell.CreateSubKey(menuName);
        RegistryKey cmd = custom.CreateSubKey("command");
        cmd.SetValue("", Application.ExecutablePath + " %1"); //%1 是传入打开的文件路径
        cmd.Close();
        custom.Close();
        shell.Close();
    }

    MessageBox.Show("注册成功!\r\n请通过文件或目录的右键菜单来测试结果!");
}

上面只是核心的部分,不能完整运行,请下载下面的完整源代码,有注释。

抱歉!评论已关闭.