问题是为 macOS 寻找解决方案,而提供的答案不适用于该问题。但我会将答案保留在这里以供将来参考,以供那些在搜索引擎中找到该帖子并寻找 Windows 解决方案的人使用。
Windows - 从 URL 打开应用程序
有时您希望使用 mailto: 或 skype: 之类的自定义 URL 方案来处理一些自定义链接。为此,您可以在注册表中 register an application to a URI Scheme 并创建一个运行以处理对该 url 方案的请求的应用程序。
示例
I've created an example that demonstrate the feature. 创建此示例是为了处理 myapp: url 方案并显示一个消息框,其中包含通过 url 传递给应用程序的值。
示例包含 2 个项目:
- 当单击“myapp:”protocole 链接时将安装并运行的 Windows 窗体应用程序。
- 一个 Visual Studio 安装项目,它安装应用程序并设置注册设置以让 Windows 应用程序处理“myapp:”协议。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace UrlSchemeSample
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
var args = "";
if (Environment.GetCommandLineArgs().Length > 1)
args = Environment.GetCommandLineArgs()[1];
MessageBox.Show($"You can decide what to do with the arguments:\n{args}");
Application.Run(new Form1());
}
}
}
它是如何工作的?
我想你想创建myapp url 方案并在c:\myapp.exe 中有一个应用程序,你想用你的应用程序处理 url 方案。然后你应该在 registry/l 中创建这些键和值
HKEY_CLASSES_ROOT
myapp
(Default) = "URL:myapp"
URL Protocol = ""
DefaultIcon
(Default) = "c:\myapp.exe",0
shell
open
command
(Default) = "c:\myapp.exe" "%1"
然后您可以使用Environment.GetCommandLineArgs() 获取通过url 传递给应用程序的值并解析参数。
例如,有一个 url myapp:Hello world!,你的应用程序的命令行参数将是 myapp:Hello world!,你可以解析它并从参数中提取你需要的信息。
作为一个例子,你可以有一些这样的网址:myapp:show?form=form1&param1=something。然后你可以解析命令并做你需要的。
常见问题
1. Windows 窗体应用程序在此项目中的作用是什么?
当用户单击注册方案的 url 时,应用程序将打开,并且 url 将作为命令行参数传递给应用程序。然后你可以解析参数并做你需要的。
2。安装项目的作用是什么?
它会安装处理 url 方案的应用程序。它还使用合适的值在 Windows 注册表中注册 url 方案。
除了使用安装程序项目,您也可以使用 C# 代码创建这些注册表项和值,但使用安装程序项目更方便。如果没有 Visual Studio 2017 安装项目模板,可以here下载。