我有一个应用程序,但目前它不是单例应用程序。我喜欢使它成为单例应用程序,这样它的另一个实例就不会在运行时退出。
如果可以做到,请回复一些示例代码。
我有一个应用程序,但目前它不是单例应用程序。我喜欢使它成为单例应用程序,这样它的另一个实例就不会在运行时退出。
如果可以做到,请回复一些示例代码。
这里有一些很好的示例应用程序。下面是一种可能的方法。
public static Process RunningInstance()
{
Process current = Process.GetCurrentProcess();
Process[] processes = Process.GetProcessesByName (current.ProcessName);
//Loop through the running processes in with the same name
foreach (Process process in processes)
{
//Ignore the current process
if (process.Id != current.Id)
{
//Make sure that the process is running from the exe file.
if (Assembly.GetExecutingAssembly().Location.
Replace("/", "\\") == current.MainModule.FileName)
{
//Return the other process instance.
return process;
}
}
}
//No other instance was found, return null.
return null;
}
if (MainForm.RunningInstance() != null)
{
MessageBox.Show("Duplicate Instance");
//TODO:
//Your application logic for duplicate
//instances would go here.
}
许多其他可能的方式。有关替代方案,请参见示例。
我认为以下代码将对您有所帮助。这是相关链接: http: //geekswithblogs.net/chrisfalter/archive/2008/06/06/how-to-create-a-windows-form-singleton.aspx
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
/*====================================================
*
* Add codes here to set the Winform as Singleton
*
* ==================================================*/
bool mutexIsAvailable = false;
Mutex mutex = null;
try
{
mutex = new Mutex(true, "SampleOfSingletonWinForm.Singleton");
mutexIsAvailable = mutex.WaitOne(1, false); // Wait only 1 ms
}
catch (AbandonedMutexException)
{
// don't worry about the abandonment;
// the mutex only guards app instantiation
mutexIsAvailable = true;
}
if (mutexIsAvailable)
{
try
{
Application.Run(new SampleOfSingletonWinForm());
}
finally
{
mutex.ReleaseMutex();
}
}
//Application.Run(new SampleOfSingletonWinForm());
}
}
我知道的方法如下。程序必须尝试打开一个命名的互斥体。如果该互斥体存在,则退出,否则,创建互斥体。但这似乎与您的条件相矛盾,即“它的另一个实例不会在运行时退出”。无论如何,也许这也有帮助