CustomUriSchemeRegistration.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. using Microsoft.Win32;
  2. using System;
  3. namespace CustomUrlSchemeRegistrationPoC
  4. {
  5. internal class CustomUriSchemeRegistration
  6. {
  7. private readonly string _urlScheme;
  8. private readonly string _displayName;
  9. private readonly string _exeFilePath;
  10. public CustomUriSchemeRegistration(string urlScheme, string displayName, string exeFilePath)
  11. {
  12. _urlScheme = urlScheme;
  13. _displayName = displayName;
  14. _exeFilePath = exeFilePath;
  15. }
  16. private static RegistryKey Target => Registry.ClassesRoot;
  17. public bool Install(out Exception exception)
  18. {
  19. try
  20. {
  21. using (var keyClass = Target.CreateSubKey(_urlScheme))
  22. {
  23. keyClass.SetValue(null, _displayName);
  24. keyClass.SetValue("URL Protocol", "");
  25. }
  26. using (var keyCommand = Target.CreateSubKey(_urlScheme + @"\shell\open\command"))
  27. {
  28. keyCommand.SetValue(null, "\"" + _exeFilePath + "\" %1");
  29. }
  30. exception = null;
  31. return true;
  32. }
  33. catch (Exception ex)
  34. {
  35. exception = ex;
  36. return false;
  37. }
  38. }
  39. public bool Uninstall(out Exception exception)
  40. {
  41. try
  42. {
  43. using (Target)
  44. {
  45. if (Target.OpenSubKey(_urlScheme) != null)
  46. {
  47. Target.DeleteSubKeyTree(_urlScheme);
  48. }
  49. }
  50. exception = null;
  51. return true;
  52. }
  53. catch (Exception ex)
  54. {
  55. exception = ex;
  56. return false;
  57. }
  58. }
  59. }
  60. }