VB.net 如果需要單一實例運行,只要在其屬性中選中一個複選框就OK了,簡單得不能再簡單了。。。
在 C# 中,天生不支援單一實例運行,如果想要單一實例,處理起來很複製。
簡單點的有 尋找進程資訊、線程同步等。用起來很不爽。
在 VS2008 的 MSDN 中,搜尋 “單一實例”,找到了MS官方的實現方法。
頁面地址:單一實例檢測樣本
ms-help://MS.VSCC.v90/MS.MSDNQTR.v90.chs/wpf_samples/html/c283e8e9-6fb5-494f-9600-826148e77046.htm
來源程式下載。
ms-help://MS.VSCC.v90/MS.MSDNQTR.v90.chs/wpf_samples/sampleexecutables/AppModel/SingleInstanceDetectionSample.zip
開啟其中的 csharp 檔案夾下的工程,關鍵區段在 App.cs 檔案內,這個是程式入口所在。
看他 引用了
using Microsoft.VisualBasic.ApplicationServices;
標頭檔,呵呵,看來是調用 VB.net 的函數類庫實現的。PS:記得引用“Microsoft.VisualBasic”庫哦,不然會抱錯的。
他給的 App.cs 貌似不是 普通表單應用程式的。。需要改動一下。我的修改如下。
============================================================================
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();
MessageBox.Show(Application.ProductName + " 已經在運行了,不能重複運行。", "確定", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);//給個對話方塊提示
}
}
}