zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    解决Oracle XE报错ORA-12516(oracle回话数超出限制)
    端口被占用如何处理
    ORACLE initialization or shutdown in progress 错误解决办法
    oracle的闪回功能
    Linux入门
    oracle字段like多个条件
    navicat常用快捷键与SQL基本使用
    Oracle四舍五入,向上取整,向下取整
    无限循环小数化分数
    筛选素数
  • 原文地址:https://www.cnblogs.com/softidea/p/3324283.html
Copyright © 2011-2022 走看看