SoFunction
Updated on 2025-03-07

C# method to implement a pallet program and prohibit multiple application instances from running

This article describes how C# implements a pallet program and prohibits multiple application instances from running. Share it for your reference, as follows:

Pallet program production:

1. Pull a NotifyIcon control onto the form and set the NotifyIcon Icon (it's very important! Otherwise, there will be no effect after running)

2. When the form is closed, minimize the program to the system tray.

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
  //("Program will be minimized to system tray area");   = true; // Cancel close the form  ();
   = false;//Cancel the display of the form in the taskbar  this. = true;//Show the tray icon}

3. Put a context menu, add several basic items, "Show main form", "Exit", and hang this menu on NotifyIcon

private void menuShow_Click(object sender, EventArgs e)
{
  ();
   = true;
  this. = false;
}
private void menuExit_Click(object sender, EventArgs e)
{
  (true);
  ();
}

4. When left-clicking the tray icon, the main form will be displayed. When right-clicking, of course, the menu set above will pop up.

private void notifyIcon1_MouseClick(object sender, MouseEventArgs e)
{
  if ( == )
  {
    ();
     = true;
    this. = false;
  }
}

Prevent this program from running multiple simultaneously

using System;
using ;
using ;
using ;
namespace LuceneTest
{
  static class Program
  {
    /// <summary>
    /// The main entry point of the application.    /// </summary>
    [STAThread]
    static void Main()
    {
      bool bCreatedNew;
      Mutex m = new Mutex(false, "Product_Index_Cntvs", out bCreatedNew);
      if (bCreatedNew)
      {
        ();
        (false);
        (new Form1());
      }
    }
  }
}

I hope this article will be helpful to everyone's C# programming.