User Tools

Site Tools

blog:2023-06-05_c_winform_app_single_instance



2023-06-05 C#: WinForm App Single Instance

GitHub

Test Code

  •         public Form1()
            {
                InitializeComponent();
            }
    
            private const string MutexName = "SINGLE_INSTANCE_APPLICATION";
            private bool _firstApplicationInstance;
            private Mutex _mutexApplication;
    
            private bool CheckApplicationFirstInstance()
            {
                // Allow for multiple runs but only try and get the mutex once
                if (_mutexApplication == null)
                {
                    _mutexApplication = new Mutex(true, MutexName, out _firstApplicationInstance);
                }
    
                return _firstApplicationInstance;
            }
    
    
            private void Form1_Load(object sender, EventArgs e)
            {
                // Check first instance or not
                if (CheckApplicationFirstInstance())
                {
                    // Yes, this is the first instance
                    // Allow this application
                }
                else
                {
                    // Close application
                    Close();
                }
            }

TAGS

  • 50 person(s) visited this page until now.

Permalink blog/2023-06-05_c_winform_app_single_instance.txt · Last modified: 2023/06/05 17:07 by jethro

oeffentlich