C#中如何让Windows窗体只运行一次

.Net技术 码拜 10年前 (2014-12-14) 1397次浏览 0个评论

方法一:

[STAThread]
static void Main() { bool isAppRunning = false;
   System.Threading.Mutex mutex = new System.Threading.Mutex(
       true,
       System.Diagnostics.Process.GetCurrentProcess().ProcessName,
       out isAppRunning);
   if (!isAppRunning)
   {
       MessageBox.Show(“本程序已经在运行了,请不要重复运行!”);
       Environment.Exit(1);
   }
   else
   {
       Application.EnableVisualStyles();
       Application.SetCompatibleTextRenderingDefault(false);
       Application.Run(new Form1());
   }
}

注:也可以这样设置Mutex , Mutex MyMutex = new Mutex(true, “OnlyRunOncetime”, out bExist);

   确保唯一。

方法二(API):

  1.  [STAThread]   
  2.         static void Main()   
  3.         {   
  4.             //Get   the   running   instance.      
  5.             Process instance RunningInstance();   
  6.             if (instance == null)   
  7.             {   
  8.                 System.Windows.Forms.Application.EnableVisualStyles();   
  9.                 System.Windows.Forms.Application.DoEvents();   
  10.   
  11.                 //There  isn’t another instance, show our form.      
  12.                 Application.Run(new Form1());   
  13.             }   
  14.             else  
  15.             {   
  16.                 //There is another instance of this process.     
  17.                 HandleRunningInstance(instance);   
  18.             }   
  19.         }   
  20.   
  21.         public static Process RunningInstance()   
  22.         {   
  23.             Process current Process.GetCurrentProcess();   
  24.             Process[] processes Process.GetProcessesByName(current.ProcessName);   
  25.   
  26.             //Loop through  the running processes in with the same name      
  27.             foreach (Process process in processes)   
  28.             {   
  29.                 //Ignore   the   current   process     
  30.                 if (process.Id != current.Id)   
  31.                 {   
  32.                     //Make sure that the process is running from the exe file.      
  33.                     if (Assembly.GetExecutingAssembly().Location.Replace(“/”, “\”) == current.MainModule.FileName)   
  34.                     {   
  35.                         //Return   the   other   process   instance.     
  36.                         return process;   
  37.                     }   
  38.                 }   
  39.             }   
  40.             //No other instance was found, return null.    
  41.             return null;   
  42.         }   
  43.   
  44.         public static void HandleRunningInstance(Process instance)   
  45.         {   
  46.             //Make sure the window is not minimized or maximized    
  47.             ShowWindowAsync(instance.MainWindowHandle, WS_SHOWNORMAL);   
  48.             //Set the real intance to foreground window   
  49.             SetForegroundWindow(instance.MainWindowHandle);   
  50.         }   
  51.   
  52.         [DllImport(“User32.dll”)]   
  53.         private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);   
  54.         [DllImport(“User32.dll”)]   
  55.         private static extern bool SetForegroundWindow(IntPtr hWnd);   
  56.   
  57.         //1:normal   
  58.         //2:minimized   
  59.         //3:maximized   
  60.         private const int WS_SHOWNORMAL 3;

一般都用方法一方法二

方法三
把AssemblyInfo.cs里的[assembly: AssemblyFileVersion(“1.0.0.0”)]改为[assembly:AssemblyFileVersion(“2.0.0.8”)],然后利用该信息进行判断。
代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Reflection;
using System.Collections;
using System.Threading;

namespace MyWork_01
{
class Program
{
static void Main(string[] args)
{
Process[] processes = Process.GetProcesses(); //获得当前所有进程
Process currentProcess = Process.GetCurrentProcess(); //获取当前正在运行进程
ProcessModule currentPM = currentProcess.Modules[0];
int same = 0; //相同运行实例个数
ArrayList proList = new ArrayList(); //将相同实例加入此集合中

foreach (Process p in processes)
{
try//由于进程不同,有的进程不包含Modules信息,所以要用try保护
{
if (p.Modules != null)
if (p.Modules.Count > 0)
{
System.Diagnostics.ProcessModule pm = p.Modules[0];
if (pm.FileVersionInfo.FileVersion.Equals(currentPM.FileVersionInfo.FileVersion))
{
same++;
proList.Add(p);
}
if (same > 1)
{
same++;
proList.Add(p);
if (same > 1)
{
for (int i = 0; i < proList.Count; i++)
{
if (((Process)(proList[i])).Id == currentProcess.Id)
{
Console.WriteLine(“该进程已经启动了一个实例”);
Thread.Sleep(1000);
((Process)(proList[i])).Kill();
}
}
}
}
}
}
catch
{ }
}
Console.Read();
}
}
}

方法四:直接定义一个属性类,利用此属性信息进行判断。
代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Diagnostics;
using System.Collections;
using System.Threading;

[assembly: Help(“This Assembly demonstrates custom attributes creation and their run-time query.”)]

public class HelpAttribute : Attribute
{
public HelpAttribute(String Description_in)
{
this.description = Description_in;
}

protected String description;

public String Description
{
get
{
return this.description;
}
}
}
class Program
{
static void Main(string[] args)
{
HelpAttribute HelpAttr1 = null;
HelpAttribute HelpAttr2 = null;
Process currentProcess = Process.GetCurrentProcess(); //获取当前正在运行进程
Assembly a = Assembly.LoadFrom(currentProcess.MainModule.FileName);
foreach (Attribute attr in a.GetCustomAttributes(true))
{
HelpAttr1 = attr as HelpAttribute;
if (null != HelpAttr1)
{
//Console.WriteLine(“Description of {0}:\n{1}”, currentProcess.MainModule.FileName, HelpAttr1.Description);
break;
}
}
Process[] processes = Process.GetProcesses(); //获得当前所有进程
int same = 0; //相同运行实例个数
ArrayList proList = new ArrayList(); //将相同实例加入此集合中
foreach (Process pro in processes)
{
try//由于进程不同,有的进程不包含Modules信息,所以要用try保护
{
if (pro.Modules != null)
if (pro.Modules.Count > 0)
{
Assembly b = Assembly.LoadFrom(pro.MainModule.FileName);
foreach (Attribute attr in b.GetCustomAttributes(true))
{
HelpAttr2 = attr as HelpAttribute;
if (null != HelpAttr2)
{
if (HelpAttr1.Description.Equals(HelpAttr2.Description))
{
same++;
proList.Add(pro);
if (same > 1)
{
for (int i = 0; i < proList.Count; i++)
{
if (((Process)(proList[i])).Id == currentProcess.Id )
{
Console.WriteLine(“该进程已经启动了一个实例”);

Thread.Sleep(1000);
((Process)(proList[i])).Kill();

}
}
}
}
}
}
}
}
catch
{
}
}
Console.ReadLine();
}

}


CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明C#中如何让Windows窗体只运行一次
喜欢 (0)
[1034331897@qq.com]
分享 (0)

文章评论已关闭!