常见方案
网页唤起指定软件,其实就是利用URL来执行一个关键字Key,这个Key是注册表中的一个键,Value是指定路径的exe,亦可携带参数启动exe;
步骤1
检查关键字是否已存在
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| private static bool IsRegisteredKey(string key) { var executablePath = string.Empty; try { var registryRunKey = Registry.ClassesRoot.OpenSubKey(key); if (registryRunKey != null) { executablePath = registryRunKey.GetValue("URL Protocol") as string; registryRunKey.Close(); } } catch (Exception ex) { Logger.WriteLineError($"Get application {key} value failed, ex:{ex}"); }
Logger.WriteLineDebug($"AuoStartup executablePath - {executablePath}");
return !string.IsNullOrEmpty(executablePath) && executablePath == AppExecutePath; }
|
步骤2
注册关键字(步骤1、2通常在软件安装后或软件启动时执行)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| private static bool RegisterAppKey(string keyName, string value) { try { RegistryKey registryKey = Registry.ClassesRoot; var fKey = registryKey.OpenSubKey(keyName, true) ?? registryKey.CreateSubKey(keyName); fKey .SetValue("", value); fKey .SetValue("", keyName); if (flyinsonoKey != null) { var defaultIconKey = fKey .OpenSubKey("DefaultIcon", true) ?? flyinsonoKey.CreateSubKey("DefaultIcon"); if (defaultIconKey != null) { defaultIconKey.SetValue("", value + ",1"); } var shellKey = fKey .OpenSubKey("shell", true) ?? fKey .CreateSubKey("shell"); var openKey = shellKey.OpenSubKey("open", true) ?? shellKey.CreateSubKey("open"); var commandKey = openKey.OpenSubKey("command", true) ?? openKey.CreateSubKey("command"); if (commandKey != null) { commandKey.SetValue("", "\"" + value + "\"" + " \"%1\""); } fKey .SetValue("URL Protocol", value); fKey .Close(); }
return true; } catch (Exception ex) { Console.WriteLine($"Register ex:{ex}"); return false; } }
|
步骤3
网页中用Key写一个链接
1
| <a href="MyApp://?a=arg1&e=arg2">点击打开MyApp.exe</a>
|
步骤4
软件启动时解析参数
1 2
| var args = Environment.GetCommandLineArgs();
|
REG
保存为Notepad2.reg
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| Windows Registry Editor Version 5.00
[HKEY_CLASSES_ROOT\Notepad2] "URL Protocol"="D:\\Tools\\Notepad2\\Notepad2.exe" @="Notepad2Protocol"
[HKEY_CLASSES_ROOT\Notepad2\DefaultIcon] @="D:\\Tools\\Notepad2\\Notepad2.exe,1"
[HKEY_CLASSES_ROOT\Notepad2\shell]
[HKEY_CLASSES_ROOT\Notepad2\shell\open]
[HKEY_CLASSES_ROOT\Notepad2\shell\open\command] @="\"D:\\Tools\\Notepad2\\Notepad2.exe\" \"%1\""
|
注意事项:
路径使用双杠\\
如果字符串中有双引号(”),那么需要加转义字符””
保存后双击文件执行,将这些项写入到注册表
检验是否注册成功:
开始-运行 输入Notepad2:,可以运行该程序则表示注册成功了;
在浏览器的地址栏直接输入:Notepad2:,可以运行则表示注册成功;