Thursday, May 14, 2009

Register Application as a Url Protocol

There are times when it is appropriate for a desktop application to be called via a URL and be passed data, such as "myprotocol://open?id=100”. The following code shows how an application can self register itself to handle a URL protocol.

public void RegisterUrlProtocol(string myUrlProtocolName, bool force,) 
RegistryKey rKey = Registry.ClassesRoot.OpenSubKey(myUrlProtocolName, true); 
if (force || rKey == null) 
rKey = Registry.ClassesRoot.CreateSubKey(myUrlProtocolName); 
rKey.SetValue("", "URL:"+ myUrlProtocolName+" Protocol"); 
rKey.SetValue("URL Protocol", ""); 
rKey = rKey.CreateSubKey(@"shell\open\command"); 
rKey.SetValue("", "\"" + Application.ExecutablePath + "\" %1"); 
if (rKey != null) { rKey.Close(); 
}