1、简介
本文主要介绍非IE浏览器的ActiveX控件替换方案.常用的做法是通过注册表来注册URL协议来完成这个功能,像腾讯的Tim等软件就是如此,如下图
所以,第一步就是通过C#写做注册表,接着通过网页访问来唤起winform程序.根据Tim的实例,通过C#写入了一个类似的注册表节点
接着通过网页访问,网页代码如下:
<a href="WinformsCustomInstall:hello world/">点击这里启动程序</a>
点击之后正常唤起了Winform程序.说明这个方法是可行的.
C#操作注册表的相关方法如下:
public class RegistryVisitor
{
public static void Register(string rootName,string appPath, string protocolName=null)
{
if (!string.IsNullOrEmpty(appPath) && File.Exists(appPath))
{
try
{
//判断root是否存在,存在的话先删除
if (Registry.ClassesRoot.OpenSubKey(rootName) != null)
Registry.ClassesRoot.DeleteSubKeyTree(rootName);
}
catch (Exception ex)
{
MessageBox.Show($"操作注册表异常,确保{rootName}创建前为空失败,信息:{ex.Message},堆栈:{ex.StackTrace}");
}
try
{
//创建root节点
using (var root = Registry.ClassesRoot.CreateSubKey(rootName))
{
//打开root节点,并写入相关信息
root.SetValue("", protocolName ?? "Custome Protocol");
root.SetValue("URL Protocol", appPath);
}
//创建root->shell子节点
using (Registry.ClassesRoot.CreateSubKey($@"{rootName}\shell")) { };
//创建root->shell->open子节点
using (Registry.ClassesRoot.CreateSubKey($@"{rootName}\shell\open")) { };
//打开open子节点
using (var open = Registry.ClassesRoot.OpenSubKey($@"{rootName}\shell\open", true))
{
//创建root->shell->open->command子节点
using (var command = open.CreateSubKey("command"))
{
//写入command子节点值相关的值 %1代表appPath对应的winform程序中的Main(string[] args)可以接收到%1传递的值
//%1的值是通过网页上给定 格式是 root节点的名称:网页需要传递的参数
//这样args就能接收到网页传递的参数
command.SetValue(@"", "\"" + appPath + "\" \" %1\"");
}
}
MessageBox.Show("注册表写入成功");
}
catch (Exception ex)
{
MessageBox.Show($"注册表写入失败,信息:{ex.Message},堆栈:{ex.StackTrace}");
}
}
}
}
代码注释中可以解析出注册表节点的具体结构和值.
2、实战
因为证明了注册表方案的可行性,接着就是将写入注册表的流程添加用户安装过程中即可.这样用户就可以通过网页正常唤起winform桌面.这里参考Winform Vs Installer之添加自定义安装流程