只启动一个窗体,如果再次启动则激活该窗体


只启动一个窗体,如果再次启动则激活该窗体
     以前就很想实现这个功能,不过不知从何处下手,初步做了一下只实现了只启动一个窗体,却无法实现激活该窗体,这是一个很大的遗憾呀!也是唯一美中不足之处.在网上找了好久,终于实现了这个功能,在这和大家一起分享一下.
 1using System;
 2using System.Collections.Generic;
 3using System.Windows.Forms;
 4using System.Diagnostics;
 5using System.Runtime.InteropServices;
 6
 7namespace WindowsApplication2
 8{
 9    static class Program
10    {
11        /// <summary>
12        /// 应用程序的主入口点。
13        /// </summary>

14        
15        [DllImport("User32.dll")]
16        private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);
17        [DllImport("User32.dll")]
18        private static extern bool SetForegroundWindow(IntPtr hWnd);
19        private const int WS_SHOWNORMAL = 1;
20
21        [STAThread]
22        static void Main()
23        {
24            //得到正在运行的例程
25            Process instance = RunningInstance();
26            if (instance == null)
27            {
28                //如果没有其它例程,就新建一个窗体
29                Application.EnableVisualStyles();
30                Application.SetCompatibleTextRenderingDefault(false);
31                Application.Run(new Form1());
32            }

33            else
34            {
35                //处理发现的例程
36                HandleRunningInstance(instance);
37            }

38        }

39        /// <summary>
40        /// 得到正在运行的进程
41        /// </summary>
42        /// <returns></returns>

43        public static Process RunningInstance()
44        {
45            Process current = Process.GetCurrentProcess();
46            Process[] processes = Process.GetProcessesByName(current.ProcessName);
47
48            //遍历正在有相同名字运行的进程
49            foreach (Process process in processes)
50            {
51                //忽略现有的进程
52                if (process.Id != current.Id)
53                {
54                    //确保进程从EXE文件运行
55                    if (process.MainModule.FileName == current.MainModule.FileName)
56                    {
57                        // 返回另一个进程实例
58                        return process;
59                    }

60                }

61            }

62            //没有其它的进程,返回Null
63            return null;
64        }

65        /// <summary>
66        /// 处理正在运行的进程,也就是将其激活
67        /// </summary>
68        /// <param name="instance">要处理的进程</param>

69        public static void HandleRunningInstance(Process instance)
70        {
71            //确保窗口没有被最小化或最大化
72            ShowWindowAsync(instance.MainWindowHandle, WS_SHOWNORMAL);
73            //设置真实进程为foreground window
74            SetForegroundWindow(instance.MainWindowHandle);
75        }

76    }

77}
posted @ 2008-04-15 11:57  侯垒  阅读(2602)  评论(13编辑  收藏  举报
Powered by: holly