C# Register a Url Protocol

This tutorial will show you how to register a custom Url Protocol for your application. Basically, you can control your application by simply clicking an Url address like this one:
myApp:doSomething
Note: In this tutorial, I’ll name the custom protocol myApp – but you can use any name you want.

1.Editing the Registry

In order to create your custom url protocol, you must first add it to the computer’s Registry so it will know which application is associated with that protocol.
Here’s the structure of the subkey you should create:
Custom Protocol Registry
The method below creates all the subkeys needed:

2.Get the arguments in the Application

Now when you access a url like this: myApp:SomeValue Windows will automatically open your program and send to it the argument’s value (which is “SomeValue”).
Finally, simply get the arguments sent, by using Environment.GetCommandLineArgs().
Default
1
2
3
4
5
6
7
8
9
1
static void Main()
{
      string[] args = Environment.GetCommandLineArgs();
      
      //args[0] is always the path to the application
      RegisterMyProtocol(args[0]);
      //^the method posted before, that edits registry      
      try
      {
          //if there's an argument passed, write it
          Console.WriteLine("Argument: " + args[1].Replace("myapp:", string.Empty));  
      }
      catch
      {
          Console.WriteLine("No argument(s)");  //if there's an exception, there's no argument
      }
 
      Console.ReadLine(); //pauses the program - so you can see the result
}
 
Previous
Next Post »