WPF程序只运行一个实例

1.WPF程序在 启动窗口的构造函数执行InitializeComponent之前判断是否已经存在实例

 

  • 不涉及服务器情况,可直接进行判断(不在mainwindow的构造函数中判断)
       // public MainWindow()
       // {
// private bool _createNew; //
string exeName = Properties.Resources.ThreadName; // Mutex mutex = new Mutex(true, exeName, out _createNew); //only one instance is allowed // if (!_createNew) // { // MessageBox.Show(Properties.Resources.ThereAlreadyApp); // App.Current.Shutdown(); // return; // } // InitializeComponent(); // }
  •  涉及服务器(好多复制粘贴的网址,不知道那个是原创,找了能找到时间最早的链接,侵删) 在 exeName字符串加 “Global\\”

如果已经有实例运行,关闭当前试图运行的程序。

 

更新  --  2016-12-23,在main函数中做判断不严谨,

 

托盘程序情况下,程序在桌面上显示以后,唯一ID就判断不了。改为在类App中重写OnStartup函数进行判断,强制程序退出用Environment.Exit(0);

    public partial class App : Application
    {
     public EventWaitHandle ProgramStarted { get; set; }

protected override void OnStartup(StartupEventArgs e) { bool createNew; ProgramStarted = new EventWaitHandle(false, EventResetMode.AutoReset, "MyTctiApp", out createNew); if (!createNew) { MessageBox.Show("already exit"); App.Current.Shutdown(); Environment.Exit(0); } base.OnStartup(e); } }

 

posted @ 2016-09-22 15:01  pkyou  阅读(4246)  评论(0编辑  收藏  举报