C#實現Web鏈接啟動應用程序
最近需要配合Web端實現用戶點擊鏈接來啟動應用程序並且需要能夠傳參數給應用程序。
那么就可以使用注冊表來實現這個功能
編寫注冊表可以在軟件安裝程序中加入,也可以在軟件啟動后在軟件中編寫注冊表,在軟件安裝程序中編寫注冊表這里就不多說了,這里記錄一下C#實現注冊表的編寫。
if (Registry.ClassesRoot.OpenSubKey(RJCommon.ProtocolName) != null)
return;
RegistryKey registryKey = Registry.ClassesRoot.CreateSubKey(RJCommon.ProtocolName);
registryKey.SetValue(string.Empty, RJCommon.ProtocolName);//名稱為空的是設置默認值
registryKey.SetValue("URL Protocol", Application.ExecutablePath);
registryKey.CreateSubKey("DefaultIcon").SetValue(string.Empty, $"{Application.ExecutablePath},1");
RegistryKey shell = registryKey.CreateSubKey("shell");
shell.SetValue(string.Empty, "open");
RegistryKey open = shell.CreateSubKey("open");
open.SetValue(string.Empty, "open");
open.CreateSubKey("command").SetValue(string.Empty, $"\"{Application.ExecutablePath}\" %1");
registryKey.Close();
這樣就實現了軟件自注冊注冊表了。特別注意一下設置默認值時需要鍵值為空就可以設置默認值了,我在這個地方折騰過,在注冊表文件編寫中是填寫'@'符號,這里使用'@'是不能設置默認值的,切記。那么Web端如何調用呢?也很簡單
<a href="RDP:{'ip':'127.0.0.0','user':'user','pwd':'1536'}">打開遠程控制</a>
其中RDP就是C#中RJCommon.ProtocolName的值,且必須后面緊跟冒號':'符號,后面就是帶的參數了。
C#中接收這些參數就簡單了。可以使用static void Main(string[] args)中傳入的args參數獲取,或者使用Environment.CommandLine來獲取,Environment.CommandLine會多傳入一個程序路徑的值。
注冊表文件編寫
Windows Registry Editor Version 5.00
[HKEY_CLASSES_ROOT\RDP]
@="RDP"
"URL Protocol"="D:\\BaiduNetdiskDownload\\RdpClient\\RdpClient.exe"
[HKEY_CLASSES_ROOT\RDP\DefaultIcon]
@="D:\\BaiduNetdiskDownload\\RdpClient\\RdpClient.exe,1"
[HKEY_CLASSES_ROOT\RDP\shell]
@="open"
[HKEY_CLASSES_ROOT\RDP\shell\open]
@="open"
[HKEY_CLASSES_ROOT\RDP\shell\open\command]
@="\"D:\\BaiduNetdiskDownload\\RdpClient\\RdpClient.exe\" %1"
保存為.reg為后綴的文件,雙擊執行即可