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之添加自定義安裝流程