Allow Application Run Only Once

ID - _BUGFISH - E#94
^Top
<< Back
Mobile-Menu










Allow Application Run Only Once
Category: C-Sharp
Sub-Category:
Creator: Jan-Maurice Dahlmanns
Created: 2020-11-22 17:44:49
Modified: 2024-11-19 04:15:17
Views: 653

Caution: 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.

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());
        }
    }
}

 

Currently 0 Upvotes!

captcha image
System - 2024-11-05 18:27:39
Commenting System Initialized! Have a very nice day!

Switches: 0 | Arrivals: 7 | Visits: 7
This Website is using Session Cookies for Site Functionality.