wpf制作自己的安裝程序(可定制)


用wpf開發自己的安裝程序,包括安裝界面、卸載界面、創建快捷方式等

安裝程序原理:

1、將編譯好的文件打包成zip的壓縮文件,

2、然后將zip以資源的方式內嵌到安裝程序中

3、在安裝的時候使用ICSharpCode.SharpZipLib.dll將zip文件解壓到相應的目錄中

4、建立相應的快捷方式,啟動主程序程序

核心代碼:

解壓:

/// <summary>
    /// ZIP助手類
    /// </summary>
    public static class ZIPHelper
    {
        public static Action<double, double, string> ActionProgress;
        /// <summary>
        /// 解壓縮zip文件
        /// </summary>
        /// <param name="zipFile">解壓的zip文件流</param>
        /// <param name="extractPath">解壓到的文件夾路徑</param>
        /// <param name="bufferSize">讀取文件的緩沖區大小</param>
        public static void Extract(byte[] zipFile, string extractPath, int bufferSize)
        {
            extractPath = extractPath.TrimEnd('/') + "//";
            byte[] data = new byte[bufferSize];
            int size;//緩沖區的大小(字節)
            double max = 0;//帶待壓文件的大小(字節)
            double osize = 0;//每次解壓讀取數據的大小(字節)
            using (ZipInputStream s = new ZipInputStream(new System.IO.MemoryStream(zipFile)))
            {
                ZipEntry entry;
                while ((entry = s.GetNextEntry()) != null)
                {
                    max += entry.Size;//獲得待解壓文件的大小
                }
            }
            using (ZipInputStream s = new ZipInputStream(new System.IO.MemoryStream(zipFile)))
            {
                ZipEntry entry;

                while ((entry = s.GetNextEntry()) != null)
                {
                    string directoryName = Path.GetDirectoryName(entry.Name);
                    string fileName = Path.GetFileName(entry.Name);

                    //先創建目錄
                    if (directoryName.Length > 0)
                    {
                        Directory.CreateDirectory(extractPath + directoryName);
                    }
                    if (fileName != String.Empty)
                    {
                        using (FileStream streamWriter = File.Create(extractPath + entry.Name.Replace("/", "//")))
                        {
                            while (true)
                            {
                                size = s.Read(data, 0, data.Length);
                                if (size > 0)
                                {
                                    osize += size;
                                    System.Windows.Forms.Application.DoEvents();
                                    streamWriter.Write(data, 0, size);
                                    string text = Math.Round((osize / max * 100), 0).ToString() + "%";
                                    ActionProgress?.Invoke(max + 5, osize, text);

                                    System.Windows.Forms.Application.DoEvents();
                                }
                                else
                                {
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }
    }

創建快捷方式

/// <summary>
        /// 執行軟件安裝
        /// </summary>
        private void Setup()
        {
            try
            {
                IsFinished = false;
                //獲取用戶選擇路徑中的最底層文件夾名稱
                string fileName = this.txtInstallationPath.Text.Split('\\')[this.txtInstallationPath.Text.Split('\\').Count() - 1];

                //當用戶選擇的安裝路徑中最底層的文件夾名稱不是“XthkDecryptionTool”時,自動在創建一個“XthkDecryptionTool”文件夾,防止在刪除的時候誤刪別的文件
                if (!fileName.Equals(InstallEntity.InstallFolderName))
                {
                    this.txtInstallationPath.Text = this.txtInstallationPath.Text + @"\" + InstallEntity.InstallFolderName;
                }
                //安裝路徑
                InstallPath = this.txtInstallationPath.Text;

                //顯示安裝進度界面
                //this.tcMain.SelectedIndex = 1;
                this.grid_one.Visibility = Visibility.Collapsed;
                this.grid_two.Visibility = Visibility.Visible;
                this.grid_three.Visibility = Visibility.Collapsed;

                //檢測是否已經打開
                Process[] procCoursewareDecryptionTool = Process.GetProcessesByName(InstallEntity.AppProcessName);
                if (procCoursewareDecryptionTool.Any())
                {
                    if (MessageBox.Show("" + InstallEntity.DisplayName + "”正在運行中,是否強制覆蓋程序?", "提示", MessageBoxButton.YesNo, MessageBoxImage.Information) == MessageBoxResult.Yes)
                    {
                        Common.IsAppKill(InstallEntity.AppProcessName);
                    }
                    else
                    {
                        Application.Current.Shutdown();

                    }
                }

                //創建用戶指定的安裝目錄文件夾
                Directory.CreateDirectory(InstallPath);
                ZIPHelper.ActionProgress -= ActionProgressResult;
                ZIPHelper.ActionProgress += ActionProgressResult;

                this.pbSchedule.Value = 0;
                this.txtSchedule.Text = "0%";

                //將軟件解壓到用戶指定目錄
                ZIPHelper.Extract(Install.SetupFiles.Setup, InstallPath, 1024 * 1204);
                //將嵌入的資源釋放到用戶選擇的安裝目錄下面(卸載程序)
                string uninstallPath = this.txtInstallationPath.Text + @"\" + InstallEntity.UninstallName;
                FileStream fsUninstall = System.IO.File.Open(uninstallPath, FileMode.Create);
                fsUninstall.Write(Install.SetupFiles.Uninstall, 0, Install.SetupFiles.Uninstall.Length);
                fsUninstall.Close();

                //將嵌入的資源釋放到用戶選擇的安裝目錄下面(快捷圖標)
                string InstallIcoPath = this.txtInstallationPath.Text + InstallEntity.IconDirectoryPath;
                FileStream fsInstallIcoPath = System.IO.File.Open(InstallIcoPath, FileMode.Create);
                var InstallIco = Install.SetupFiles.IcoInstall;
                byte[] byInstall = Common.ImageToByteArray(InstallIco);
                fsInstallIcoPath.Write(byInstall, 0, byInstall.Length);
                fsInstallIcoPath.Close();

                //將嵌入的資源釋放到用戶選擇的安裝目錄下面(快捷卸載圖標)
                string UninstallIcoPath = this.txtInstallationPath.Text + InstallEntity.UninstallIconDirectoryPath;
                FileStream fsUninStallIco = System.IO.File.Open(UninstallIcoPath, FileMode.Create);
                var UnInstallIco = Install.SetupFiles.IcoUninstall;
                byte[] byUnInstall = Common.ImageToByteArray(UnInstallIco);
                fsUninStallIco.Write(byUnInstall, 0, byUnInstall.Length);
                fsUninStallIco.Close();

                //釋放卸載程序完成,更新進度條
                this.pbSchedule.Value = this.pbSchedule.Value + 1;
                this.txtSchedule.Text = Math.Round((this.pbSchedule.Value / this.pbSchedule.Maximum * 100), 0).ToString() + "%";


                //添加開始菜單快捷方式
                RegistryKey HKEY_CURRENT_USER = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders");
                string programsPath = HKEY_CURRENT_USER.GetValue("Programs").ToString();//獲取開始菜單程序文件夾路徑
                Directory.CreateDirectory(programsPath + InstallEntity.MenuFolder);//在程序文件夾中創建快捷方式的文件夾

                //更新進度條
                this.pbSchedule.Value = this.pbSchedule.Value + 1;
                this.txtSchedule.Text = Math.Round((this.pbSchedule.Value / this.pbSchedule.Maximum * 100), 0).ToString() + "%";

                //快捷方式名稱";
                string IconPath = InstallPath + InstallEntity.IconDirectoryPath;
                string UninstallIconPath = InstallPath + InstallEntity.UninstallIconDirectoryPath;
                string InstallExePath = InstallPath + @"\" + InstallEntity.AppExeName;
                string ExeUnInstallPath = InstallPath + @"\" + InstallEntity.UninstallName;

                //開始菜單打開快捷方式
                shortName = programsPath + InstallEntity.MenuFolder + InstallEntity.ShortcutName;
                Common.CreateShortcut(shortName, InstallExePath, IconPath);//創建快捷方式


                //更新進度條
                this.pbSchedule.Value = this.pbSchedule.Value + 1;
                this.txtSchedule.Text = Math.Round((this.pbSchedule.Value / this.pbSchedule.Maximum * 100), 0).ToString() + "%";
                //開始菜單卸載快捷方式
                Common.CreateShortcut(programsPath + InstallEntity.MenuFolder + InstallEntity.UninstallShortcutName, ExeUnInstallPath, UninstallIconPath);//創建卸載快捷方式

                //更新進度條
                this.pbSchedule.Value = this.pbSchedule.Value + 1;
                this.txtSchedule.Text = Math.Round((this.pbSchedule.Value / this.pbSchedule.Maximum * 100), 0).ToString() + "%";

                //添加桌面快捷方式
                string desktopPath = HKEY_CURRENT_USER.GetValue("Desktop").ToString();//獲取桌面文件夾路徑
                shortName = desktopPath + @"\" + InstallEntity.ShortcutName;
                Common.CreateShortcut(shortName, InstallExePath, IconPath);//創建快捷方式

                //常見控制面板“程序與功能”
                //可以往root里面寫,root需要管理員權限,如果使用了管理員權限,主程序也會以管理員打開,如需常規打開,需要在打開進程的時候做降權處理
                RegistryKey CUKey = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, Environment.Is64BitOperatingSystem ? RegistryView.Registry64 : RegistryView.Registry32);
                var currentVersion = CUKey.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Uninstall");
                Dictionary<string, string> dic = new Dictionary<string, string>();
                dic.Add("DisplayIcon", InstallExePath);//顯示的圖標的exe
                dic.Add("DisplayName", InstallEntity.DisplayName);//名稱
                dic.Add("Publisher", InstallEntity.Publisher);//發布者
                dic.Add("UninstallString", ExeUnInstallPath);//卸載的exe路徑
                dic.Add("DisplayVersion", InstallEntity.VersionNumber);
                RegistryKey CurrentKey = CUKey.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Uninstall\" + InstallEntity.DisplayName, true);
                if (CurrentKey == null)
                {
                    //說明這個路徑不存在,需要創建
                    CUKey.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Uninstall\" + InstallEntity.DisplayName);
                    CurrentKey = CUKey.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Uninstall\" + InstallEntity.DisplayName, true);
                }
                foreach (var item in dic)
                {
                    CurrentKey.SetValue(item.Key, item.Value);
                }
                CurrentKey.Close();


                //更新進度條
                this.pbSchedule.Value = this.pbSchedule.Value + 1;
                this.txtSchedule.Text = Math.Round((this.pbSchedule.Value / this.pbSchedule.Maximum * 100), 0).ToString() + "%";

                //安裝完畢,顯示結束界面
                this.grid_one.Visibility = Visibility.Collapsed;
                this.grid_two.Visibility = Visibility.Collapsed;
                this.grid_three.Visibility = Visibility.Visible;

                IsFinished = true;
            }
            catch (Exception)
            {
                //安裝完畢,顯示結束界面
                this.grid_one.Visibility = Visibility.Visible;
                this.grid_two.Visibility = Visibility.Collapsed;
                this.grid_three.Visibility = Visibility.Collapsed;
                throw;
            }
        }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM