Launching a WinForms Application from a Browser via Custom URI Protocol
To enable a browser to launch a WinForms desktop application, you can register a custom URI scheme in the Windows Registry. This allows links like myapp:// to invoke your executable. The approach uses the application's ProductName (obtained from Form.ProductName) as the protocol name.
The following example shows how to check and register the protocol when the main form loads. Only the product name is needed (e.g., "VSDebug") rather than the full executable path.
private void MainForm_Load(object sender, EventArgs e)
{
ProtocolRegistrar.VerifyRegistration(this.ProductName);
}
public static class ProtocolRegistrar
{
public static void VerifyRegistration(string protocolName)
{
using (RegistryKey baseKey = Registry.ClassesRoot.OpenSubKey(protocolName, writable: false))
{
if (baseKey == null)
{
RegisterProtocol(protocolName);
}
}
}
private static void RegisterProtocol(string protocolName)
{
string executablePath = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
// Create root key for the protocol
using (RegistryKey protocolKey = Registry.ClassesRoot.CreateSubKey(protocolName))
{
protocolKey.SetValue(string.Empty, $"URL:{protocolName}");
protocolKey.SetValue("URL Protocol", string.Empty);
}
// Create shell\open\command key
string commandKeyPath = $@"{protocolName}\shell\open\command";
using (RegistryKey commandKey = Registry.ClassesRoot.CreateSubKey(commandKeyPath))
{
commandKey.SetValue(string.Empty, $"\"{executablePath}\" \"%1\"");
}
}
}
Because writing to HKEY_CLASSES_ROOT requires administrator privileges, you must elevate the application (e.g., via a manifest requesting requireAdministrator) before running the registration codee.
After registration, typing VSDebug:// (or whatever protocol name you used) in a browser address bar will prompt the browser to launch the application. The registry entries tell Windows which executable to run and how to pass the URI as an argument.