您的位置:首页 > 其它

WPF之创建单实例应用程序

2013-05-11 13:43 204 查看
单实例应用程序即该应用程序只允许运行一个实例,说白了就是不能同时运行两个相同的程序。

主体框架为3个自定义类: Startup、 SimpleInstanceAppWrapper、 App

// Startup.cs
using System;
using System.Windows;

namespace WpfApplication1
{
class Startup
{
[STAThread()]
static void Main(string[] args)
{

SimpleInstanceAppWrapper instance = new SimpleInstanceAppWrapper();
instance.Run(args);
}
}
}
// SimpleInstanceAppWrapper.cs
// 添加引用: Microsoft.VisualBasic
using System;
using System.Windows;

namespace WpfApplication1
{
class SimpleInstanceAppWrapper : Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase
{
public SimpleInstanceAppWrapper()
{
this.IsSingleInstance = true;
}

private App app;

protected override bool OnStartup(Microsoft.VisualBasic.ApplicationServices.StartupEventArgs eventArgs)
{
app = new App();
app.Run(new MainFrame()); // MainFrame类是自定义的主窗口类

return false;
}

protected override void OnStartupNextInstance(Microsoft.VisualBasic.ApplicationServices.StartupNextInstanceEventArgs eventArgs)
{
//base.OnStartupNextInstance(eventArgs);

MessageBox.Show("Cannot startup the second instance!");
}
}
}
// App.cs
using System;
using System.Windows;

namespace WpfApplication1
{
class App : Application
{
///
/// 该事件在Application.Run()方法调用之后,在主窗口显示之前发生。
///
/// 该参数包含字符串数组类型的命令行参数
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
}

///
/// 该事件在应用程序关闭时,app.Run()方法返回之前发生。
///
/// 该参数包含整数类型的退出代码
protected override void OnExit(ExitEventArgs e)
{
base.OnExit(e);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐