您的位置:首页 > 编程语言 > C#

C#程序多用户只启动一个进程的方法[转载]

2009-12-30 16:06 603 查看
版权声明:转载时请以超链接形式标明文章原始出处和作者信息及本声明
http://greenlandy.blogbus.com/logs/14388828.html

Code Snippet [STAThread]
     private static void Main()
     {
         Application.EnableVisualStyles();
         Application.SetCompatibleTextRenderingDefault(false);
         var wb = new Form1();
         Process current = Process.GetCurrentProcess();
         bool newinstance = true;
         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)
                 {
                     //?回另一个例程实例  
                     current = process;
                     newinstance = false;
                     break;
                 }
             }
         }
         if (newinstance)
         {
             Application.Run(wb);
         }
         else
         {
             ShowWindowAsync(current.MainWindowHandle, 1);

             //?置真实例程为foreground   window  
             SetForegroundWindow(current.MainWindowHandle);
         }
     }
引入这两个API函数

Code Snippet [DllImport("User32.dll")]
private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);

[DllImport("User32.dll")]
private static extern bool SetForegroundWindow(IntPtr hWnd);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: