zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    input文本框输入限制(正则表达式)
    SQL Server通用型分页存储过程
    简单易学的数据图表
    HTML中input文本框只读不可编辑的方法
    SQL添加外键约束的方式
    +1 也要睁着眼
    博客园的自定义皮肤
    网站收集整理
    jQuery extend方法介绍
    HTML5本地存储
  • 原文地址:https://www.cnblogs.com/wyynts/p/3414531.html
Copyright © 2011-2022 走看看