zoukankan      html  css  js  c++  java
  • 如何确保C#的应用程序只被打开一次

    http://stackoverflow.com/questions/184084/how-to-force-c-sharp-net-app-to-run-only-one-instance-in-windows

    using System.Threading;
    
    [DllImport("user32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    static extern bool SetForegroundWindow(IntPtr hWnd);
    
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
       bool createdNew = true;
       using (Mutex mutex = new Mutex(true, "MyApplicationName", out createdNew))
       {
          if (createdNew)
          {
             Application.EnableVisualStyles();
             Application.SetCompatibleTextRenderingDefault(false);
             Application.Run(new MainForm());
          }
          else
          {
             Process current = Process.GetCurrentProcess();
             foreach (Process process in Process.GetProcessesByName(current.ProcessName))
             {
                if (process.Id != current.Id)
                {
                   SetForegroundWindow(process.MainWindowHandle);
                   break;
                }
             }
          }
       }
    }

    上面代码的MyApplicationName需要确保是唯一识别的

    VS调试程序的时候

    string appName;
    appName = Process.GetCurrentProcess().ProcessName;//ZITaker.vshost

    appName = Process.GetCurrentProcess().MainModule.FileName;//D:SoftwareBMYunSourceCodeITakerITakerinDebugITaker.vshost.exe

    appName = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;//ZITaker

    appName = System.Reflection.Assembly.GetExecutingAssembly().Location;//D:SoftwareBMYunSourceCodeITakerITakerinDebugITaker.exe

    直接执行exe的时候

    string appName;
    appName = Process.GetCurrentProcess().ProcessName;//ZITaker

    appName = Process.GetCurrentProcess().MainModule.FileName;//D:SoftwareBMYunSourceCodeITakerITakerinDebugITaker.exe

    appName = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;//ZITaker

    appName = System.Reflection.Assembly.GetExecutingAssembly().Location;//D:SoftwareBMYunSourceCodeITakerITakerinDebugITaker.exe

    从上面可以看出System.Reflection.Assembly.GetExecutingAssembly().Location适合作为程序的唯一识别码

    http://stackoverflow.com/questions/4313756/creating-a-mutex-throws-a-directorynotfoundexception    //遇到找不到文件路径的错误

    My mutex name had  in it, which windows was interpreting as a path character. Running:

    将路径名中的反斜杠替换成_就可以了

    正确的做法:

    string appName;
    appName = System.Reflection.Assembly.GetExecutingAssembly().Location;
    appName = appName.Replace(Path.DirectorySeparatorChar, '_');
    using (Mutex mutex = new Mutex(true, appName, out createdNew))

    appName = Process.GetCurrentProcess().MainModule.FileName;//D:SoftwareBMYunSourceCodeITakerITakerinDebugITaker.vshost.exe
    ZBM.ZITaker.Log.OperationLog.Instance.WriteLog(appName, ZBM.ZITaker.Log.LogType.UI);
    appName = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;//ZITaker
    ZBM.ZITaker.Log.OperationLog.Instance.WriteLog(appName, ZBM.ZITaker.Log.LogType.UI);
    appName = System.Reflection.Assembly.GetExecutingAssembly().Location;//D:SoftwareBMYunSourceCodeITakerITakerinDebugITaker.exe
    ZBM.ZITaker.Log.OperationLog.Instance.WriteLog(appName, ZBM.ZITaker.Log.LogType.UI);

    最终版本

    using System;
    using System.Windows.Forms;//Application
    using System.Diagnostics;//Process
    using System.Threading;//Mutex
    using System.Runtime.InteropServices;//DllImport
    using System.IO;//Path
    
    static class Program
        {
            [DllImport("User32.dll")]
            //This function puts the thread that created the specified window into the foreground and activates the window.
            private static extern bool SetForegroundWindow(IntPtr hWnd);
    
            /// <summary>
            /// 应用程序的主入口点。
            /// </summary>
            [STAThread]
            static void Main()
            {
                try
                {
                    bool createdNew;
                    string appName;
                    appName = System.Reflection.Assembly.GetExecutingAssembly().Location;
    appName = appName.Replace(Path.DirectorySeparatorChar, '_');
    using (Mutex mutex = new Mutex(true, appName, out createdNew)) { if (createdNew) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Main()); } else { Process current = Process.GetCurrentProcess(); foreach (Process process in Process.GetProcessesByName(current.ProcessName)) { if (process.Id != current.Id) { SetForegroundWindow(process.MainWindowHandle); break; } } } } } catch (Exception ex) { } } }

    http://www.cnblogs.com/xiashengwang/archive/2012/08/29/2662366.html

    这篇文章中也提到了Mutex实现一次只打开一个应用程序

  • 相关阅读:
    Search a 2D Matrix leetcode java
    Sqrt(int x) leetcode java
    Search for a Range leetcode java
    php获取客户端公网ip代码
    ddns+ros(routeros)+centos7.6+nginx+php+dnspod
    limits.conf文件修改注意事项,限制文件描述符数和进程数
    阿里云本地存储网关的一些特点和注意事项
    ROS根据访问不同的网址,走不同的路由策略的脚本
    漫威所有电影的 按时间线的观影顺序
    sklearn—特征工程
  • 原文地址:https://www.cnblogs.com/chucklu/p/4210432.html
Copyright © 2011-2022 走看看