如何使我的应用成为单例应用? [重复]

问题描述 投票:2回答:3

我有一个应用程序,但目前不是单例应用程序。我希望使其成为单例应用程序,以便其另一个实例在运行时不会退出。

如果可以完成,请提供一些示例代码。

c# .net windows-applications
3个回答
3
投票

这里有一些很好的示例应用程序。下面是一种可能的方法。

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.
}

[许多其他可能的方式。请参阅示例以了解替代方法。

First one.

Second One.

Third One.


2
投票

我认为以下代码将对您有所帮助。这是相关的链接: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());
    }
}

1
投票

我知道的方法如下。该程序必须尝试打开一个命名的互斥锁。如果存在该互斥锁,则退出,否则,创建互斥锁。但这似乎与您的条件“其另一个实例在运行时不退出”相矛盾。无论如何,也许这也很有帮助

© www.soinside.com 2019 - 2024. All rights reserved.