WPF安装部署小结

开机启动

右击"MySetup">>"视图">>"注册表",在"HKEY_LOCAL-MACHINE"文件夹下新建键"Software">>"Microsoft">>"Windows">>"CurrentVersion">>"Run",在"Run"文件夹新建字符串值,命名为"DataServiceHost.exe",可根据需求命名,右击"DataServiceHost">>"属性窗口",其中"Value"属性设为"[TARGETDIR] DataServiceHost.exe"。如此,便实现了开机启动。

实现安装后自动运行及删除注册表

点击菜单上的"文件">>"添加">>"新项目",选择"安装程序类",命名为"Installer",在"Installer.cs"代码中重写如下方法。自定义操作完成后,一定要将应用程序生成,这样就可以得到".dll"文件。生成成功后,就可以将该".dll"程序集添加到安装项目中。右击"MySetup">>"视图">>"自定义操作",主窗口如下图。

右击"安装">>"添加自定义操作",弹出如下对话框。

在"应用程序文件夹"中添加程序集,在之前"InstallService应用程序"中debug文件夹中找到".dll"文件,添加进去。这样便实现了安装后自动运行和卸载后删除注册表的功能。

安装完成后自动运行某个程序

将这句代码写在AfterInstall里面:

System.Diagnostics.ProcessStartInfo psiConfig = new System.Diagnostics.ProcessStartInfo(path + "\run.exe");//path即是安装的目录

System.Diagnostics.Process pConfig = System.Diagnostics.Process.Start(psiConfig);

如何得到用户所选安装路径?在实现代码的时候,用户所选安装路径大多数情况下都要用到,怎么得到他的值呢?在自定义操作->安装->"主输出来自Library(活动)"上面右键属性,在CustomActionData中填入/targetdir="[TARGETDIR]", 然后在类InstallerTest中用这句话this.Context.Parameters["targetdir"] 就可以取得安装的目录了

C#避免重复打开应用程序

 在程序启动时判断进程是否在运行,如果运行则关闭。

 
  public MainWindow()
        {
            InitializeComponent();
            //默认设置
            //关掉已运行的进程实例
            Process ps = GetRunningInstance();
            if (ps != null) ps.Kill();
        }
//获取已运行的进程实例
        public static Process GetRunningInstance()
        {
            Process currentProcess = Process.GetCurrentProcess(); //获取当前进程 
            //获取当前运行程序完全限定名 
            string currentFileName = currentProcess.MainModule.FileName;
            //获取进程名为ProcessName的Process数组。 
            Process[] processes = Process.GetProcessesByName(currentProcess.ProcessName);
            //遍历有相同进程名称正在运行的进程 
            foreach (Process process in processes)
            {
                if (process.MainModule.FileName == currentFileName)
                {
                    if (process.Id != currentProcess.Id) //根据进程ID排除当前进程 
                        return process;//返回已运行的进程实例 
                }
            }
            return null;
        }    

WPF 接收进程参数方法

首先重写app.xml方法OnStartup,在方法中接收参数,并保存到属性中。在主窗体就可以应用了。

 /// <summary>
    /// App.xaml 的交互逻辑
    /// </summary>
    public partial class App : Application
    {
        //重写app方法
        protected override void OnStartup(StartupEventArgs e)
        {
            if (e.Args != null && e.Args.Count() > 0)
            {
                this.Properties["ArbitraryArgName"] = e.Args[0];
            }
            base.OnStartup(e);
        }
    }

在应用的时候

 if (Application.Current.Properties["ArbitraryArgName"] != null)
            {
                _UserName = Application.Current.Properties["ArbitraryArgName"].ToString();//ArbitraryArgName要与APP里面设置的名字相同
                _UserName = _UserName.Split('/')[2];
                lbUserName.Text = "当前用户:" + _UserName;           
          }    
原文地址:https://www.cnblogs.com/lipanpan/p/3948979.html