C#实现单实例运行

C#实现单实例运行的方法,也有多种,比如利用 Process 查找进程的方式,利用 API findwindow 查找窗体的方式,还有就是 利用 Mutex 原子操作,上面几种方法中, 综合考虑利用 Mutex 的方式是较好的选择。

[STAThread]
static void Main()
{
    bool isAppRunning = false;
    System.Threading.Mutex mutex = new System.Threading.Mutex(
        true,
        System.Diagnostics.Process.GetCurrentProcess().ProcessName,
        out isAppRunning);
    if (!isAppRunning)
    {
        MessageBox.Show("本程序已经在运行了,请不要重复运行!");
        Environment.Exit(1);
    }
    else
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    }
}
 
使用Process 查找进程的方式会报错:System.ComponentModel.Win32Exception 中第一次偶然出现的“System.dll”类型的异常
原因可能是因为:
有些进程,如:system 系统空闲进程,当前程序没有权限获取相关信息或有些程序没有process.MainModule.FileName这些属性
示例代码:

           bool result = false;
            try
            {
                Process me = Process.GetCurrentProcess();
                Process[] us = Process.GetProcesses();
                Process another = null;
                foreach (var p in us)
                {
                    try
                    {
                        if (p.Id != me.Id && p.MainModule.FileName == me.MainModule.FileName)
                        {
                            another = p;
                            break;
                        }
                    }
                    catch (Exception ex)
                    {
                        logger.Error(ex);
                    }
                }
                if (another != null)
                {
                    MessageBox.Show("程序已运行", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Question);
                    result = true;
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.StackTrace+“
”+ e.Message);
                result = true;
            }
            return result;
 
 
 
 
http://xxinside.blogbus.com/logs/47162540.html
原文地址:https://www.cnblogs.com/softidea/p/3324283.html