C#编写功能让你的系统导入注册表文件时不提示

最近项目需要将授权文件导入系统,注册成服务,本来很简单的事情,只要写个服务就可以,而公司上级又不想给我源码。这就让我有点为难,很简单的工作,就变得复杂了。

如是我就用命令行的方式来实现,关键代码如下:

        /// <summary>
        /// 注册授权文件
        /// </summary>
        /// <param name="path">文件路径</param>
        private static void RegLic( string path)
        {
            Process process = new Process();
            process.StartInfo.FileName = "cmd.exe";
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.RedirectStandardInput = true;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.RedirectStandardError = true;
            process.StartInfo.CreateNoWindow = true;

            process.Start();
            process.StandardInput.WriteLine(path + @"\DssLicSev.reg");

            process.StandardInput.WriteLine("exit");
            process.Close();
        }

此方法运行良好,可是弹出提示框确认。这肯定不是我们所期望的。

百度一下,找到解决办法,可以不提示。就是打开注册表

[HKEY_CLASSES_ROOT\regfile\shell\open\command]

将其默认值改为regedit.exe /s"%1"  而不是regedit.exe "%1"

再重新运行就不弹出提示框,然后在安装程序里面执行导入reg文件时,即可。添加一个类库项目命名为InstallHelp,添加Install安装类,重写install方法附上关键代码

public override void Install(IDictionary stateSaver)

{

  string installPath = this.Context.Parameters["targetdir"];//这软件的安装路径

    ImporRegNoDialog(true);

   RegLic( string path);

  ImporRegNoDialog(false);

    base.Install(stateSaver);

}

/// <summary>
/// 注册授权文件
/// </summary>
/// <param name="path"></param>
private static void RegLic( string path)
{
    Process process = new Process();
    process.StartInfo.FileName = "cmd.exe";
    process.StartInfo.UseShellExecute = false;
    process.StartInfo.RedirectStandardInput = true;
    process.StartInfo.RedirectStandardOutput = true;
    process.StartInfo.RedirectStandardError = true;
    process.StartInfo.CreateNoWindow = true;

    process.Start();
    process.StandardInput.WriteLine(path + @"\DssLicSev.reg");

    process.StandardInput.WriteLine("exit");
    process.Close();
}

/// <summary>
/// 导入注册表无提示框
/// </summary>
/// <param name="isTrue">true不提示,false提示</param>
public static void ImporRegNoDialog(bool isTrue)
{
    RegistryKey regClassesRoot = Registry.ClassesRoot;
    RegistryKey regFile = regClassesRoot.OpenSubKey("regfile", true);
    RegistryKey regShell = regFile.OpenSubKey("shell", true);
    RegistryKey regOpen = regShell.OpenSubKey("open", true);
    RegistryKey regCommand = regOpen.OpenSubKey("command", true);
    string ss = string.Empty;
    if (isTrue)
        ss = "regedit.exe /s" + '"' + "%1" + '"';
    else
        ss = "regedit.exe " + '"' + "%1" + '"';
    //默认值的名称为空,
    regCommand.SetValue("", ss);

}

好了,现在只要在安装程序里打包即可,右键你的安装程序

image

选择自定义操作

image

编译程序。就可以实现了,先写到这里。吃饭去了。

posted @ 2012-03-29 12:27  itbread  阅读(2094)  评论(1编辑  收藏  举报

如果觉得对你有帮助,不妨微信扫描打赏鼓励下