winform中已运行的程序则显示到桌面

来源:互联网 发布:网上真实赌博软件 编辑:程序博客网 时间:2024/06/05 16:25
static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            Process instance = RunningInstance();
            if (instance == null)
            {
                //没有实例在运行
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new Form1());
            }
            else
            {
                //已经有一个实例在运行
                HandleRunningInstance(instance);
            }
        }
 
         private static Process RunningInstance()
         {
             Process current = Process.GetCurrentProcess();
             Process[] processes = Process.GetProcessesByName(current.ProcessName);
             //遍历与当前进程名称相同的进程列表  
             foreach (Process process in processes)
             {
                 //如果实例已经存在则忽略当前进程  
                 if (process.Id != current.Id)
                 {
                     //保证要打开的进程同已经存在的进程来自同一文件路径
                     if (Assembly.GetExecutingAssembly().Location.Replace("/""\\") == current.MainModule.FileName)
                     {
                         //返回已经存在的进程
                         return process;
                          
                     }
                 }
             }
             return null;
         }
 
         public static void HandleRunningInstance(Process instance)
         {
             ShowWindowAsync(instance.MainWindowHandle, WS_SHOWNORMAL);
             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;
    }
0 0