您的位置:首页 > 编程语言 > C#

C#应用程序实现单例模式

2013-12-26 11:24 288 查看
该文档引自网址http://wenwen.soso.com/z/q85588071.htm

限制启动一个应用程序窗口,再启动,将把第一个启动的窗口从任务栏里还原出来。

代码如下:

using Microsoft.VisualBasic.ApplicationServices;

static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
SingleInstanceManager manager = new SingleInstanceManager();//单实例管理器
manager.Run(new string[]{});
//Application.Run(new frmMain()); //屏蔽掉了以前的加载头
}

// 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
{
frmMain 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();
app = new frmMain();//改为自己的程序运行窗体
Application.Run(app);

return false;
}

protected override void OnStartupNextInstance(StartupNextInstanceEventArgs eventArgs)
{
// Subsequent launches

base.OnStartupNextInstance(eventArgs);
app.Activate();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: