简体   繁体   中英

When use .net Mutex to ensure single instance, is that possible update first instance when launch second instance

I have a winform application. the Mutex class used to block create more than one instance.

static class Program
{

    public static string IDFromAnotherApp = "default";
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main(string[] args)
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        if (args.Length > 0)
            IDFromAnotherApp = args[0];

        bool successAquisition;
        Mutex programMutex = new Mutex(true,
            AppDomain.CurrentDomain.SetupInformation.ApplicationName,
            out successAquisition);

        if (successAquisition)
        {
            Application.Run(new Form1());
            programMutex.ReleaseMutex();
            GC.KeepAlive(programMutex);

        }
        else
        {
            IDFromAnotherApp = "another";
            MessageBox.Show("already open");

        } 

    }
}

Form1 code

    public partial class Form1 : Form
{

    public Form1()
    {
        InitializeComponent();
        DisplayId();   
    }

    public void DisplayId()
    {
        label1.Text = Program.IDFromAnotherApp;
    }
}

Now when a user clicks the APP with a parameter, the Form1 label1 control will present that value, but if another user clicks the APP again, a pop up will say "already open"

I would like to do better, instead of pop up window, when another user clicks the APP with a parameter, can that already be opened Form1 update its label1's text? is that even possible?

You could use any one of number techinques

  1. NamedPipes
  2. Windows Messages
  3. Windows sockets
  4. WCF
  5. lots more...

I would suggest NamedPipes or probably Windows Messages

As for exactly how to do this, there are plenty of examples on the internet and a good exercise for you to research. If you have a problem with any particular technique please feel welcome to ask another question on the specifics of your problem you are having

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM