码迷,mamicode.com
首页 > Windows程序 > 详细

如何确保C#的应用程序只被打开一次

时间:2015-01-08 13:00:50      阅读:191      评论:0      收藏:0      [点我收藏+]

标签:

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需要确保是唯一识别的,使用Process.GetCurrentProcess().MainModule.FileName提示说找不到文件

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:

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

 

 

坑爹的是又出现新问题

问题1:

bool createdNew;
string appName;
appName = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;
appName = @"Local\" + appName;    //Local\ZITaker
using (Mutex mutex = new Mutex(true, appName, out createdNew))

此段代码的问题在于,两个程序的Assembly.GetExecutingAssembly().GetName().Name会是一致的

 

问题2:

bool createdNew;
string appName;
appName = Process.GetCurrentProcess().MainModule.FileName;
appName = @"Local\" + appName;
using (Mutex mutex = new Mutex(true, appName, out createdNew))

这个会提示未能找到路径

 

正确的做法:

string appName;
appName = Process.GetCurrentProcess().MainModule.FileName;
appName = appName.Replace(Path.DirectorySeparatorChar, ‘_‘);
using (Mutex mutex = new Mutex(true, appName, out createdNew))

 

如何确保C#的应用程序只被打开一次

标签:

原文地址:http://www.cnblogs.com/chucklu/p/4210432.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!