WPF使用URL协议实现网页中打开应用
2023-06-13 09:14:11 时间
常见方案
网页唤起指定软件,其实就是利用URL来执行一个关键字Key,这个Key是注册表中的一个键,Value是指定路径的exe,亦可携带参数启动exe;
步骤1
检查关键字是否已存在
//检查注册表是否已包含 key
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通常在软件安装后或软件启动时执行)
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写一个链接
<a href="MyApp://?a=arg1&e=arg2">点击打开MyApp.exe</a>
步骤4
软件启动时解析参数
//此处会获取到步骤2中设置的Value;和步骤3中的href;参数自行解析
var args = Environment.GetCommandLineArgs();
REG
保存为Notepad2.reg
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:
,可以运行则表示注册成功;
相关文章
- WPF TextBox使用密码样式
- wpf wrapPanel居中并从左到右排列
- WPF混合Blazor做个简易聊天小程序
- 解决XP上WPF显示gif卡的问题
- C#-WPF ProgressBar进度条
- 【翻译】WPF 中附加行为的介绍 Introduction to Attached Behaviors in WPF
- 【翻译】WPF中的数据绑定表达式
- 分享一个 WPF 气泡弹框
- 开源WPF控件库推荐:ModernWpf
- 几十款 WPF 控件 - UI 库,总有一款适合你
- WPF中用户控件和自定义控件
- WPF常用UI库和图表库(MahApps、HandyControl、LiveCharts)
- WPF 属性变动后的业务处理及恢复原始值的方法
- 有小伙伴问:上位机用QT还是winform/wpf好?
- WPF 已知问题 Separator 无法应用 ContextMenu 定义的默认样式
- WPF 性能测试
- WPF 编写一个测试 WM_TOUCH 触摸消息延迟的应用
- WPF实现MySQL数据库的连接和操作(wpf 连接mysql)
- WPF连接MySQL:实现跨平台的数据交互(wpf 连接mysql)
- 深入分析WPF客户端读取高清图片卡以及缩略图的解决方法详解
- WPF绑定实例详解