static void

Single use application (for Windows.Forms)

Avoid concurrency problems

using System;
using System.Diagnostics;
using System.Windows.Forms;
 
namespace Library.Forms
{
    public class FormUtil
    {
        public static string AppAlreadyRunningMessage
        {
            get {return Application.ProductName + " is already running on this machine. "; }
        }
 
        public static string AppNameWithVersion
        {
            get { return Application.ProductName + " " + (new Version(Application.ProductVersion)).ToString(2); }
        }
 
        /// <summary>
        /// Determines whether application is already running.
        /// </summary>
        public static bool IsAppAlreadyRunning()
        {
            Process current = Process.GetCurrentProcess();
            Process[] processes = Process.GetProcessesByName(current.ProcessName);
 
            //check if already running (concurrency issues!)
            if (processes.Length > 1)
                return true;
            return false;
        }
    }
}

Use in Program.cs

static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main(string[] args)
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
 
        //initialize
        Form1 form = new Form1();
 
        //check command line
        if (args.Length > 0)
        {
            if (!form.ReadArgs(args)) MessageBox.Show("Invalid arguments", FormUtil.AppNameWithVersion, MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }
 
        if (FormUtil.IsAppAlreadyRunning())
        {
            MessageBox.Show(
                FormUtil.AppAlreadyRunningMessage, FormUtil.AppNameWithVersion, MessageBoxButtons.OK, MessageBoxIcon.Warning);
            return;
        }
 
        //use the form we initialized above
        Application.Run(form);
    }
}