Monday, January 14, 2019

Cách tạo link custom Uri scheme để chạy app như skype

Tạo Uri custom bằng cách đăng ký registry

private static void WriteRegistry()
        {
            try
            {
                using (var key = Registry.CurrentUser.CreateSubKey("SOFTWARE\\Classes\\" + UriScheme))
                {
                    string applicationLocation = Path.Combine(System.Windows.Forms.Application.StartupPath, "TestApp.exe");

                    key.SetValue("", "URL:" + FriendlyName);
                    key.SetValue("URL Protocol", "");

                    using (var defaultIcon = key.CreateSubKey("DefaultIcon"))
                    {
                        defaultIcon.SetValue("", applicationLocation + ",1");
                    }

                    using (var commandKey = key.CreateSubKey(@"shell\open\command"))
                    {
                        commandKey.SetValue("", "\"" + applicationLocation + "\" \"%1\"");
                    }
                }
            }
            catch (Exception objEx)
            {
                ExceptionManger.WriteLog(objEx, "Exception happended in WriteRegistry.");
            }
        }

Như vậy khi mở trình duyệt gõ testapp: thì TestApp.exe sẽ chạy.

Muốn truyền thêm tham số cho TestApp thì hàm main cần nhận tham số string[] args. Sau đó xử lý tham số truyền vào trong mảng args.