如何在尝试运行应用程序的第二个实例时将主窗体置于顶部

时间:2013-01-14 18:51:38

标签: c#

我用一个表单编写了一个简单的Windows应用程序。它的目的是只在一个实例中运行。我使用互斥方法并在第二个实例尝试运行时抛出一条消息。现在我想更改此消息框,我只想在尝试触发第二个实例时将第一个实例置于顶部。我的代码目前是:

namespace WindowsFormsApplication2
{
    static class Program
    {

        [STAThread]                
        static void Main()
        {


            bool mutexCreated = false;
            System.Threading.Mutex mutex = new System.Threading.Mutex(true,@"Local\WindowsFormsApplication2.WindowsFormsApplication2.exe", out mutexCreated);

           if(!mutexCreated )  
           {
               if( MessageBox.Show("The application is already running.Hit the OK to exit",             "",MessageBoxButtons.OK, MessageBoxIcon.Information ) != DialogResult.Cancel )
               {
                  mutex.Close(); 
                  return;
               }
           }

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }
}

2 个答案:

答案 0 :(得分:2)

.NET已经对此提供了很好的支持,支持单实例应用程序并让第一个应用程序了解另一个实例的入门。强烈支持这一点而不是自己动手。使用WindowsFormsApplicationBase类,改变Program.cs文件,如下所示:

using System;
using System.Windows.Forms;
using Microsoft.VisualBasic.ApplicationServices;    // Add reference to Microsoft.VisualBasic

namespace WindowsFormsApplication1 {
    class Program : WindowsFormsApplicationBase {
        public Program() {
            this.EnableVisualStyles = true;
            this.IsSingleInstance = true;
            this.MainForm = new Form1();
        }
        protected override void OnStartupNextInstance(StartupNextInstanceEventArgs e) {
            e.BringToForeground = true;
        }
        [STAThread]
        public static void Main(string[] args) {
            new Program().Run(args);
        }
    }
}

注意OnStartupNextInstance()方法如何确保将主窗口带回前台。您还可以使用其e.CommandLine属性来获取从第二个实例传递到主实例的命令行参数。如果您使用文件关联,这往往会很有用。

答案 1 :(得分:0)

这是我发现的最新版本的帖子。从本质上讲,您可以获取其他流程信息,然后将其转发。

http://social.msdn.microsoft.com/Forums/en/csharpgeneral/thread/42b3db75-e61e-4f59-bf2b-c96a40cfb4e4