^

Allow Application Run Only Once

Article 94 in C-Sharp

2020-11-22 17:44:49 from bugfish
Allow Application Run Only Once
C-Sharp / Hints
Last Review on: 2021-05-07 01:42:25 | Hits: 117

Here is an example to allow software to run only once on a machine.
If the user tries to start the application again, there will ne a notification box and the program will exit.

[file] program.cs in visual studio

using System;
using System.Threading;
using System.Windows.Forms;

namespace myapplicationnamespace
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        ///  Only Once Instance Mode Mutex Variable and Remove IDE Error Message
            #pragma warning disable IDE0052
            private static Mutex mutex = null;
            #pragma warning restore IDE0052
        [STAThread]
        static void Main()
        {
            //
            // Only One Instance Mode
            //
            // One Instance Mode - Disable Warning Message on FailError
            const string appName = "MyApplicationName";
            #pragma warning disable IDE0018
            bool createdNew;
            #pragma warning restore IDE0018

            mutex = new Mutex(true, appName, out createdNew);

            if (!createdNew)
            {
                // App is Running
                MessageBox.Show("Only one instance allowed!");
                return;
            }

            //Default
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new MainForm());
        }
    }
}

 

I do not guarantee the reliability of the information given here, the code described on this page is executed at your own risk and in the event of damage or other unforeseeable consequences I am in no way responsible or liable.
Comment Section
Currently 0 Upvotes!
captcha image

System - 2021-01-01 19:30:46
We appreciate comments on our site!

This Website is using Session Cookies for Site Functionality and AWStats.
Radio