日期:2014-05-18  浏览次数:20829 次

老问题:如何避免两个相同的.exe运行?
怎么避免同一个.exe文件两次运行?
急!

------解决方案--------------------
using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace WindowsApplication1
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static int Main(string[] args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
if (runone())
Application.Run(new Form1
());
return 1;
}
private static System.Threading.Mutex mutex;
private static bool runone()
{
bool one;
mutex = new System.Threading.Mutex(true, "WindowsApplication2", out one);
return one;
} }
}



2

using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace WindowsApplication1
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static int Main(string[] args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Process[] ps=Process.GetProcessesByName("application.exe");
if (ps.Length==0)
{
Application.Run(new Form1
());
}

return 1;
}

}
}
------解决方案--------------------
public static Process RunningInstance()
{
Process current = Process.GetCurrentProcess();
Process[] processes = Process.GetProcessesByName (current.ProcessName);
//查找相同名称的进程
foreach (Process process in processes)
{
//忽略当前进程
if (process.Id != current.Id)
{
//确认相同进程的程序运行位置是否一样.
if (Assembly.GetExecutingAssembly().Location.Replace("/", "\\") == current.MainModule.FileName)
{
//Return the other process instance.
return process;
}
}
}
//No other instance was found, return null.
return null;
}