Exemple #1
0
        bool SetAssociation(string Extension, string KeyName, string OpenWith, string FileDescription)
        {
            RegistryKey BaseKey;
            RegistryKey OpenMethod;
            RegistryKey Shell;
            RegistryKey CurrentUser;

            try
            {
                BaseKey = Registry.ClassesRoot.CreateSubKey(Extension);
                BaseKey.SetValue("", KeyName);
                BaseKey.Flush();
                BaseKey.Close();

                OpenMethod = Registry.ClassesRoot.CreateSubKey(KeyName);
                OpenMethod.SetValue("", FileDescription);
                OpenMethod.CreateSubKey("DefaultIcon").SetValue("", "\"" + OpenWith + "\",0");
                OpenMethod.Flush();

                Shell = OpenMethod.CreateSubKey("Shell");
                Shell.CreateSubKey("open").CreateSubKey("command").SetValue("", "\"" + OpenWith + "\"" + " \"%1\"");
                Shell.CreateSubKey("edit").CreateSubKey("command").SetValue("", "\"" + OpenWith + "\"" + " \"%1\"");
                Shell.Flush();
                Shell.Close();
                OpenMethod.Close();

                // Delete the key instead of trying to change it
                CurrentUser = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\FileExts\\" + Extension, true);
                if (CurrentUser != null)
                {
                    CurrentUser.DeleteSubKey("UserChoice", false);
                    CurrentUser.Flush();
                    CurrentUser.Close();
                }
            }
            catch (Exception ex)
            {
                if (ex is System.Security.SecurityException || ex is UnauthorizedAccessException)
                {
                    MessageBox.Show("Please restart this program with administrative privileges to set file associations!");
                    return(false);
                }
#if DEBUG
                MessageBox.Show(ex.ToString());
#else
                MessageBox.Show(ex.Message);
#endif
                return(false);
            }


            // Tell explorer the file association has been changed
            SHChangeNotify(0x08000000, 0x0000, IntPtr.Zero, IntPtr.Zero);

            return(true);
        }