The Method of Realizing Tray Program with C and Prohibiting Multiple Application Instances from Running

  • 2021-09-05 00:40:17
  • OfStack

This article describes the example of C # to implement tray program and prohibit multiple application examples to run. Share it for your reference, as follows:

Making of tray program:

1. Pull an NotifyIcon control onto the form and set Icon of NotifyIcon (very important! Otherwise, you can't see the effect after running)

2. Minimize the program to the system tray when the form is closed


private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
  //MessageBox.Show(" The program will be minimized to the system tray area ");
  e.Cancel = true; //  Cancel closing the form 
  this.Hide();
  this.ShowInTaskbar = false;// Cancel the display of the form in the taskbar 
  this.notifyIcon1.Visible = true;// Show 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)
{
  this.Show();
  this.ShowInTaskbar = true;
  this.notifyIcon1.Visible = false;
}
private void menuExit_Click(object sender, EventArgs e)
{
  this.Dispose(true);
  Application.ExitThread();
}

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


private void notifyIcon1_MouseClick(object sender, MouseEventArgs e)
{
  if (e.Button == MouseButtons.Left)
  {
    this.Show();
    this.ShowInTaskbar = true;
    this.notifyIcon1.Visible = false;
  }
}

Prevent this program from running multiple at the same time


using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Threading;
namespace LuceneTest
{
  static class Program
  {
    /// <summary>
    ///  The main entry point for the application. 
    /// </summary>
    [STAThread]
    static void Main()
    {
      bool bCreatedNew;
      Mutex m = new Mutex(false, "Product_Index_Cntvs", out bCreatedNew);
      if (bCreatedNew)
      {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
      }
    }
  }
}

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


Related articles: