原文:WPF:如何实现单实例的应用程序(Single Instance)

好吧,这是我将WPF与Windows Forms进行比较的系列文章的第四篇,讨论一下如何实现单实例(single instance)

先来看第一种最简单粗暴的做法:

检测进程名,如果名称一样,则表示程序已经启动了,就不再启动.

    protected override void OnStartup(StartupEventArgs e)
{
// Get Reference to the current Process
Process thisProc = Process.GetCurrentProcess();
// Check how many total processes have the same name as the current one
if (Process.GetProcessesByName(thisProc.ProcessName).Length > 1)
{
// If ther is more than one, than it is already running.
MessageBox.Show("Application is already running.");
Application.Current.Shutdown();
return;
} base.OnStartup(e);
}
很简单,不是吗?但简单有什么错呢? 它很实用.
[注意]这个代码如果在visual studio中调试则无效,因为visual studio调试用的进程是加了一个vshost的后缀的。
 
第二种方案我觉得应该还是可以用mutex来实现嘛,看看下面的代码
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Windows;
using System.Diagnostics;
using System.Threading; namespace WpfApplication1
{
///
/// App.xaml 的交互逻辑
///
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
bool createNew;
Mutex mutex = new Mutex(true, "MyApplication", out createNew);
if (createNew)
base.OnStartup(e);
else
{
MessageBox.Show("程序已经启动了");
Application.Current.Shutdown();
}
} }
}

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

这一种做法的结果与第一种很类似,或者说没有任何区别。

 

看起来解决问题了,但仍然不是很理想的。最好的情况是,当用户开启第二个实例的时候,如果第一个实例没有处于活动状态,则应该激活它。

我们很自然还是联想到了原先在Windows Forms时代的WindowsFormsApplicationBase,那里面做这个事情太简单了。

首先,添加Microsoft.VisualBasic的引用

namespace WpfApplication1
{
public class EntryPoint
{
[STAThread]
public static void Main(string[] args)
{
SingleInstanceManager manager = new SingleInstanceManager();
manager.Run(args);
}
} // Using VB bits to detect single instances and process accordingly:
// * OnStartup is fired when the first instance loads
// * OnStartupNextInstance is fired when the application is re-run again
// NOTE: it is redirected to this instance thanks to IsSingleInstance
public class SingleInstanceManager : WindowsFormsApplicationBase
{
SingleInstanceApplication app; public SingleInstanceManager()
{
this.IsSingleInstance = true;
} protected override bool OnStartup(Microsoft.VisualBasic.ApplicationServices.StartupEventArgs e)
{
// First time app is launched
app = new SingleInstanceApplication();
app.Run();
return false;
} protected override void OnStartupNextInstance(StartupNextInstanceEventArgs eventArgs)
{
// Subsequent launches
base.OnStartupNextInstance(eventArgs);
app.Activate();
}
} public class SingleInstanceApplication : Application
{
protected override void OnStartup(System.Windows.StartupEventArgs e)
{
base.OnStartup(e); // Create and show the application's main window
//MainWindow window = new MainWindow();
Window1 window = new Window1();
window.Show();
} public void Activate()
{
// Reactivate application's main window
this.MainWindow.Show();
this.MainWindow.Activate();
}
}
}

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

WPF:如何实现单实例的应用程序(Single Instance)的更多相关文章

  1. 使用 WPF 创建单实例应用程序

    一个简单的例子就是大家在使用很多应用程序,例如在使用Microsoft Word 时会遇到一种情况,不管你打开多少个文档,系统一次只能加载一个winword.exe 实例.当打开新文档时,文档在新窗口 ...

  2. WPF点滴(2) 创建单实例应用程序

    最近有同事问道在应用程序启动之后,再次双击应用程序,如何保证不再启动新的应用程序,而是弹出之前已经启动的进程,本质上这就是创建一个单实例的WPF应用程序.在VS的工程树中有一个App.xaml和App ...

  3. Python静态方法实现单实例模式

    单实例模式 当程序中需要同一个实例就可以解决问题的场景,可以使用单实例模式

  4. WPF 单实例应用程序

    例如:Microsoft Word,不管打开多少个文档(也不管它们是如何打开的),一次只能加载 winword.exe 一个实例. 这便是单实例应用程序. 对于这种单实例应用程序,WPF 本身并未提供 ...

  5. WPF使用Mutex创建单实例程序失效

    vs2019 1.引入名称空间 using System.Threading; using System.Runtime.InteropServices; 2.导入dll并声明方法 [DllImpor ...

  6. C# 实现单实例程序

    在我们经常使用的软件中,当我们已经打开后,再次打开时,有的软件不会出现两个.例如有道词典,会将上次的界面显示出来,或者提示我们“该程序已经运行...”.我通过一个简单的C# WPF例子来说明. 首先我 ...

  7. windows应用程序单实例

    前言 这才第几天博客就跟不上了,看来一天一篇博客的目标还是有点大,写博客还是挺费时间的,写了不满意删,删完再写...直到自己没了耐心.今天先写个前言,实质性的内容明天再补吧.今天一天的收获还是挺多的, ...

  8. [WPF]WPF设置单实例启动

    WPF设置单实例启动 使用Mutex设置单实例启动 using System; using System.Threading; using System.Windows; namespace Test ...

  9. Qt实现应用程序单实例运行--LocalServer方式

    使Qt应用程序能够单实例运行的典型实现方法是使用共享内存实现.该方法实现简单,代码简洁. 但有一个致命缺陷:共享内存(QSharedMemory)实现的单程序运行,当运行环境是UNIX时,并且程序不幸 ...

随机推荐

  1. HDOJ 1266 Reverse Number(数字反向输出题)

    Problem Description Welcome to 2006'4 computer college programming contest! Specially, I give my bes ...

  2. 命名实参和可选实参(C# 编程指南)

    https://msdn.microsoft.com/zh-cn/library/dd264739.aspx CalculateBMI(weight: 123, height: 64); Calcul ...

  3. FZU 11月月赛D题:双向搜索+二分

    /* 双向搜索感觉是个不错的技巧啊 */ 题目大意: 有n的物品(n<=30),平均(两个人得到的物品差不能大于1)分给两个人,每个物品在每个人心目中的价值分别为(vi,wi) 问两人心目中的价 ...

  4. PCanywhere/teamviewer/RDP/ultraVNC/tigerVNC/realVNC/Xmanager

    PCanywhere/teamviewer/RDP/ultraVNC/tigerVNC/realVNC/Xmanager 1, 通常应用场景一般CentOS/RHEL等linux系统不配置安装Desk ...

  5. Java向上转型注意事项

    继承.接口:Java子类中如果含有父类中不包含的变量与方法,子类对象向上转型时就是丢失这些变量和方法. interface SuperClass{ int i = 2; void f() ; } cl ...

  6. MySQL添加外键的方法

    为book表添加外键: <1>明确指定外键的名称: 语法:alter table 表名 add constraint 外键的名称 foreign key(你的外键字段名) REFERENC ...

  7. iOS 捕获系统外异常

    iOS 捕获系统外异常 太阳火神的漂亮人生 (http://blog.csdn.net/opengl_es) 本文遵循"署名-非商业用途-保持一致"创作公用协议 转载请保留此句:太 ...

  8. boost::pool与内存池技术

      建议看这个链接的内容:http://cpp.winxgui.com/cn:mempool-example-boost-pool Pool分配是一种分配内存方法,用于快速分配同样大小的内存块,    ...

  9. VLV INDEX

    Normally, when the Directory Server conducts a search, the server looks through the entire entry for ...

  10. 网页JavaScript1

    DOM的操作 windows对象操作 属性: opener,打开当前窗口的源窗口,首次启动 是null. dialogArgument,对话框的返回值 子对象: history , location ...