打印

[asp.net教程] 如何让应用程序只有一个实例在运行?

如何让应用程序只有一个实例在运行?

myform.cs
   
  using system;
  using system.runtime.interopservices;
  using system.windows.forms;
  using system.diagnostics;
  using system.reflection;
   
  public class oneinstnace
  {
   [stathread]
   public static void main()
   {
   //得到正在运行的例程
   process instance = runninginstance();
   if (instance == null)
   {
   //如果没有其它例程,就新建一个窗体
   application.run (new form());
   }
   else
   {
   //处理发现的例程
   handlerunninginstance(instance);
   }
   }
   public static process runninginstance()

   {
   process current = process.getcurrentprocess();
   process[] processes = process.getprocessesbyname (current.processname);
   
   //遍历正在有相同名字运行的例程
   foreach (process process in processes)
   {
   //忽略现有的例程
   if (process.id != current.id)
   {
   //确保例程从exe文件运行
   if (assembly.getexecutingassembly().location.replace("/", "\\") ==
   current.mainmodule.filename)
   {
   //返回另一个例程实例
   return process;
   }
   }
   }
   
   //没有其它的例程,返回null
   return null;
   }
   
   public static void handlerunninginstance(process instance)
   {
   //确保窗口没有被最小化或最大化
   showwindowasync (instance.mainwindowhandle , ws_shownormal);
   
   //设置真实例程为foreground window
   setforegroundwindow (instance.mainwindowhandle);
   }
   
   [dllimport("user32.dll")]
   
   private static extern bool showwindowasync(
   intptr hwnd, int cmdshow);
   [dllimport("user32.dll")] private static extern bool
   setforegroundwindow(intptr hwnd);
   private const int ws_shownormal = 1;
  }

TOP

返回顶部
AYBlue

Processed in 0.057437 second(s), 7 queries.

当前时区 GMT+8, 现在时间是 2009-1-10 12:02 京ICP备06054220号

清除 Cookies - 联系我们 - 163K.com - Archiver - WAP