让程序只启动一次,有如下几种方法,本人比较推荐第一种
第一:
static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
//Application.Run(new LEDShow());
System.Threading.Mutex mutex = new System.Threading.Mutex(false, "ThisShouldOnlyRunOnce");
bool Running = !mutex.WaitOne(0, false);
if (!Running)
Application.Run(new Form1());
else
MessageBox.Show("程序已启动!");
}
}
第二:
using System.Diagnostics;
namespace Assistant.Common
...{
/**//// <summary>
/// 进程工具类
/// </summary>
public class ProcessUtil
...{
/**//// <summary>
/// 判断该程序是否已有实例运行
/// </summary>
/// <param name="fileName">实例文件名</param>
/// <returns>是否有运行实例</returns>
public static bool HasRunningInstance(string fileName)
...{
Process current = Process.GetCurrentProcess();
Process[] processes = Process.GetProcessesByName(current.ProcessName);
foreach (Process process in processes)
...{
if (process.Id != current.Id)
...{
if (fileName.Replace("/", "\") == current.MainModule.FileName)
...{
return true;
}
}
}
return false;
}
}
}
或者:
string name = textBox1.Text.Trim();
Process[] ravProcesses = Process.GetProcessesByName(""+name+"");
foreach(Process procName in ravProcesses)
{
procName.Kill();
}
或者:
[System.Runtime.InteropServices.DllImport("user32.dll")]
private static extern IntPtr FindWindow(string strclassName, string strWindowName);
private void timer1_Tick(object sender, System.EventArgs e)
{
string FormTitle = "无标题 - 记事本";
IntPtr hWnd = FindWindow(null, FormTitle);
if (hWnd != IntPtr.Zero)
{
Console.WriteLine("程序已启动!");
}
}