WPF-应用程序单例模式
WPF程序如何只允许打开一个窗口,当窗口存在时,激活窗口。
单例模式微软社区有发表这个文章,http://blogs.microsoft.co.il/arik/2010/05/28/wpf-single-instance-application/
步骤:
1、项目中新增SingleInstance.cs文件
2、添加引用 System.Runtime.Remoting
3、app.xaml.cs文件中继承ISingleInstanceApp(源自步骤1新增的cs文件中)
如下:
public partial class App : Application, ISingleInstanceApp
4、修改项目属性-应用程序-启动对象,选择为<projectname>.App的选项
5、实现app.xaml.cs的main方法,Unique 字段弄个唯一编码即可。如下
/// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application, ISingleInstanceApp { private const string Unique = “My_Unique_Application_String”; [STAThread] public static void Main() { if (SingleInstance<App>.InitializeAsFirstInstance(Unique)) { var application = new App(); application.InitializeComponent(); application.Run(); // Allow single instance code to perform cleanup operations SingleInstance<App>.Cleanup(); } } #region ISingleInstanceApp Members public bool SignalExternalCommandLineArgs(IList<string> args) { // handle command line arguments of second instance // … return true; } #endregion }
6、修改App.xaml文件的生成操作,App.xaml-属性-生成操作,选择Page
到6这一步就可以实现单例了。没有demo,自己敲一敲,复制粘贴试一下吧。~~~~
------由于自己要做窗口传参的需求,下面是自己遇到的问题记录一下--------
7、如果打开窗口时需要传参,那么打开窗口的操作就需要在代码中实现,如下:
// TODO: Make this unique!"Change this to something that uniquely identifies your program."; private const string AppId = "{22222222222222}"; [STAThread] static void Main(string[] args) { //if (SingleInstance<App>.InitializeAsFirstInstance(Unique)) //{ // var application = new App(); // application.InitializeComponent(); // application.Run(); // // Allow single instance code to perform cleanup operations // SingleInstance<App>.Cleanup(); //} //if (args.Length != 6) return; if (SingleInstance<App>.InitializeAsFirstInstance(AppId)) { var win = new MainWindow(); var vm = new MainWindowViewModel(args, win.Close); win.DataContext = vm; var application = new App(); application.InitializeComponent(); application.Run(); // Allow single instance code to perform cleanup operations SingleInstance<App>.Cleanup(); } } #region ISingleInstanceApp Members public bool SignalExternalCommandLineArgs(IList<string> args) { // handle command line arguments of second instance if (this.MainWindow.WindowState == WindowState.Minimized) { this.MainWindow.WindowState = WindowState.Normal; } this.MainWindow.Activate(); return true; } #endregion
与此同时还有一个地方需要删除,由于已经在类中定义一个Main方法来实现对WPF应用程序的启动。那么App.xaml里面的StartupUri删除掉,否则会出现2个窗口或者异常
8、由于不走App.xaml,所以如果引用第三方资源的话,需要在打开的窗口里面加资源,否则资源不会加载出来。
参考原文链接:https://codereview.stackexchange.com/questions/20871/single-instance-wpf-application