C#实现应用不重复开启

private void FormMain_Load(object sender, EventArgs e) {

if (CheckRunning("程序名")) // 设定程序禁止重复运行,并返回检查当前进程是否重复开启的实例的结果。"identifier"不能与其它程序一样,这是区分互斥所的标识符。

{

Process.GetCurrentProcess().Kill();//关掉当前进程

}

}

 

public static bool CheckRunning(string identifier) {

System.Security.Cryptography.MD5CryptoServiceProvider md = new System.Security.Cryptography.MD5CryptoServiceProvider();

string md5c = BitConverter.ToString(md.ComputeHash(System.Text.Encoding.Default.GetBytes(identifier))).ToLower().Replace("-", "");

bool isRunning = false; new System.Threading.Mutex(true, md5c, out isRunning); // IsRunning true:表示该互斥体创建成功,之前没有同名互斥体(程序未运行);false:表示创建失败,之前以有同名互斥体(程序已运行) md.Dispose();

return (!isRunning);

}

第二种简单的方法:

System.Diagnostics.Process[] myprocess = System.Diagnostics.Process.GetProcessesByName("程序名");

if (myprocess.Length > 1) { MessageBox.Show("程序已经启动,请勿重复打开"); Application.Exit(); this.Dispose(); this.Close(); }

posted @ 2023-04-24 19:54  十里晚风  阅读(175)  评论(0)    收藏  举报