C# winform应用程序仅能打开一个进程运行

判断程序是否已经运行,使程序只能运行一个实例:

方法1:

//这种检测进程的名的方法,并不绝对有效。因为打开第一个实例后,将运行文件改名后,还是可以运行第二个实例.

 private static bool isAlreadyRunning()
        {
            bool b = false;
            Process[] mProcs = Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName);
            if (mProcs.Length > 1) {
                b = true;
            }
            return b;
        }

方法2:

//线程互斥

static void Main()
        {
            bool canCreateNew;
            Mutex m = new Mutex(true, "Mutex名,任意字符串", out canCreateNew);
            if (canCreateNew)
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new Login());
                m.ReleaseMutex();
            }
            else {
                MessageBox.Show("程序已经运行!");
            }

        }

方法三:全局原子法,创建程序前,先检查全局原子表中看是否存在特定原子A(创建时添加的),存在时停止创建,说明该程序已运行了一个实例;不存在则运行程序并想全局原子表中添加特定原子A;退出程序时要记得释放特定的原子A哦,不然要到关机才会释放。C#实现如下:

1、申明WinAPI函数接口:

[System.Runtime.InteropServices.DllImport("kernel32.dll")]

        public static extern UInt32 GlobalAddAtom(String lpString);  //添加原子

        [System.Runtime.InteropServices.DllImport("kernel32.dll")]

        public static extern UInt32 GlobalFindAtom(String lpString);  //查找原子

        [System.Runtime.InteropServices.DllImport("kernel32.dll")]

        public static extern UInt32 GlobalDeleteAtom(UInt32 nAtom);  //删除原子

2、修改Main()函数如下:

 

 static void Main()
        {
            if (GlobalFindAtom("xinbiao_test") == 77856768) //没找到原子"xinbiao_test"
            {
                GlobalAddAtom("xinbiao_test");  //添加原子"xinbiao_test"
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new Form1());
            }
            else
            {
                MessageBox.Show("已经运行了一个实例了。");
            }                        
        }

 

3、在FormClosed事件中添加如下代码:

       GlobalDeleteAtom(GlobalFindAtom("xinbiao_test"));//删除原子"xinbiao_test"

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/jin20000/archive/2008/10/24/3136791.aspx

 

 

posted @ 2013-11-08 16:29  你好,再见  阅读(2107)  评论(0编辑  收藏  举报