How to restrict a program to a single instance

CK CK 3788 
Created at
Updated at  
734 0 0

In the program's Main method, call ProcessUtils.ThisProcessIsAlreadyRunning() to determine if another instance of the program is already running. ThisProcessIsAlreadyRunning attempts to create a Mutex object with the same name as the program (Application.ProductName). If it fails, the Mutex object already exists (and was created by another instance of the same program).

If another instance of the program is already running, that instance is made visible and input focus is set to it. Otherwise a new instance of the program is launched.

Program.cs:

using System;
using System.Collections.Generic;
using System.Windows.Forms;
using PU;

namespace WindowsApplication1
{
    static class Program
    {
        [STAThread]
        static void Main()
        {
            // If this program is already running, set focus
            // to that instance and quit.
            if (ProcessUtils.ThisProcessIsAlreadyRunning())
            {
                // "Form1" is the caption (Text property) of the main form.
                ProcessUtils.SetFocusToPreviousInstance("Form1");
            }
            else
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new Form1());
            }
        }
    }
}


ProcessUtils.cs:

using System;
using System.Diagnostics;
using System.Threading;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace PU
{
    /// Summary description for ProcessUtils.
    public static class ProcessUtils
    {
        private static Mutex mutex = null;

        /// Determine if the current process is already running
        public static bool ThisProcessIsAlreadyRunning()
        {
            // Only want to call this method once, at startup.
            Debug.Assert(mutex == null);

            // createdNew needs to be false in .Net 2.0, otherwise, if another instance of
            // this program is running, the Mutex constructor will block, and then throw 
            // an exception if the other instance is shut down.
            bool createdNew = false;

            mutex = new Mutex(false, Application.ProductName, out createdNew);

            Debug.Assert(mutex != null);

            return !createdNew;
        }

        [DllImport("user32.dll", SetLastError = true)]
        static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        static extern bool SetForegroundWindow(IntPtr hWnd);

        [DllImport("user32.dll")]
        static extern bool IsIconic(IntPtr hWnd);

        [DllImport("user32.dll")]
        static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

        const int SW_RESTORE = 9;

        [DllImport("user32.dll")]
        static extern IntPtr GetLastActivePopup(IntPtr hWnd);

        [DllImport("user32.dll")]
        static extern bool IsWindowEnabled(IntPtr hWnd);

        /// Set focus to the previous instance of the specified program.
        public static void SetFocusToPreviousInstance(string windowCaption)
        {
            // Look for previous instance of this program.
            IntPtr hWnd = FindWindow(null, windowCaption);

            // If a previous instance of this program was found...
            if (hWnd != null)
            {
                // Is it displaying a popup window?
                IntPtr hPopupWnd = GetLastActivePopup(hWnd);

                // If so, set focus to the popup window. Otherwise set focus
                // to the program's main window.
                if (hPopupWnd != null && IsWindowEnabled(hPopupWnd))
                {
                    hWnd = hPopupWnd;
                }

                SetForegroundWindow(hWnd);

                // If program is minimized, restore it.
                if (IsIconic(hWnd))
                {
                    ShowWindow(hWnd, SW_RESTORE);
                }
            }
        }
    }
}


 

Tags C# Force Single Instance How to exit application Mutex SetCompatibleTextRenderingDefault SetFocusToPreviousInstance ThisProcessIsAlreadyRunning Facebook X
Comments 0
Similar posts
  1. The best way to enable and disable buttons, menu items and toolbar buttons
    668
  2. How to speed up access to the RichTextBox Lines property
    834
  3. Graphics in C# - Irregular Forms
    914
  4. Extracting the Country from IP Address
    471
  5. How to print character in C# by ASCII code
    480
  6. How To Print Text In C#
    457
  7. How to send binary data through C# CGI app?
    999
  8. Calling Your Main Thread From A Worker Thread In C#
    551
  9. How To Read And Write A Cookie
    365
  10. Using C# With Cookies
    633
  11. To load image from file
    457
  12. How to convert bitmap image to jpeg image ?
    362
  13. How to resize and save PNG or Jpeg Image file ?
    638
  14. How to convert text string to integer ?
    616
  15. How to convert integer to text string ?
    701
  16. How to get process id in C# like windows task manager ?
    872
  17. How To Check If Your Printer Is Connected Using C#
    1,027
  18. How to download/grap web pages or XML document at internet website in Delphi XE?
    880
  19. Thread Implementation in Python
    512
  1. How to set an certain color as transparent color on bitmap
    526
  2. How to display message box in C#
    1,129
  3. URL Encode, Decode function for MFC
    609
  4. How to load HTML resource on MFC ?
    848
  5. How to get GM Time as String ?
    424
  6. Makefile to automate the build process for C++
    285
  7. Finding process name on OS
    414
  8. Convert System.DateTime to UNIX timestamp
    386
  9. Retrieve system information
    498
  10. How to call SetTimer function on MFC CDialog class ?
    652
  11. How to rename(change file name) in C# ?
    1,086
  12. Find Files in certain directory
    937
  13. Implementing C#'s foreach loop in Delphi 8
    464
  14. How to detect resource leaks in a Form
    950
  15. How to exit from a console application
    816
  16. Compress and decompress strings in C#
    977
  17. How to run shell command by MFC ?
    441
  18. Binary Search Sample Code
    409
  19. Double Linked List based in C++
    800
  20. String Replace Function For C#
    1,561
  21. MFC based World Wide Web HTTP Server Source Code
    463
  22. Creating and Using a CAsyncSocket Object to use CAsyncSocket
    473
  23. UDP Send and Receive Using CAsyncSocket
    1,207
  24. Using the shell to receive notification of removable media being inserted or removed
    681
  25. Adding Custom Paper Sizes To Named Printers
    652
  26. Print HTML In C# With Or Without The Web Browser Control And The Print Dialog
    972
  27. A Customizable Printing Text Class
    440
  28. Simplified .NET Printing In C#
    696
  29. C# Lists
    1,166
  30. Simple Example of IF/THEN using C#
    1,272
Recently updated
  1. Google OAuth Token Expiration: Causes and Solutions
    31
  2. Why 100% SEO Guarantees Better User Engagement and How to Achieve It in Your Service
    57
  3. Why SPF and DKIM Are Essential for Linux Email Servers?
    51
  4. How do I create animated background for Google Meet?
    23,256
  5. MaxMind GeoLite2 vs. DB-IP Lite vs. ip-api.com: Choosing the Right Free IP Geolocation Solution
    273
  6. Meet Valkey: Why Redis Changed Its License, Why Valkey is Better, and How to Use It as a Drop-in Replacement
    105
  7. How Rogue Web Scrapers Are Stealing My Content and Destroying My Server
    170
  8. Array of arguments passed to script in PHP
    99
  9. Invalid Auction Storms in Ad Tech
    108
  10. Building MRC-Compliant Instrumentation in Ad Tech: Implementation Steps and Key Challenges
    209
  11. The Two Clocks of Ad Server Architecture
    78
  12. Frequency Cap Architecture Overview
    527
  13. Collecting Proof-of-Play from 100,000 Screens
    154
  14. Vector Search in Relational Databases (RDBs): Trends & Usage Environments
    303
  15. What is RedisVL?
    117
  16. Designing a Skill Registry Architecture: Minimize Token Usage and Maximize AI Performance
    247
  17. TPU & GPU Cluster Management Tools
    258
  18. The Concept of Scaffolding in AI Agents
    245
  19. Beyond Static Pipelines: Architecting LLM Multi-Agent Systems for Autonomous Workflow Orchestration
    599
  20. AI-DLC vs. AI-SDLC: Model-Centric vs. System-Centric AI Development
    269
  21. Fine-Tuning Open-Weight LLMs: Training, Licensing, and Deploying Custom Models with Ollama
    355
  22. Inside the Next-Generation Streaming Architecture: Ultra-Low Latency, SGAI, and AI Codecs
    207
  23. Machine Learning: Training vs. Ranking
    231
  24. The Continuous Learning Machine: Designing a Loop That Actually Turns
    229
  25. The Next-Gen Low-Latency Standards: LL-HLS & MoQ
    204
  26. Designing a Data Curation System Around a Vector Database
    230
  27. Extracting Context from Live Video: The Architecture Got Simpler When We Stopped Building Features
    264
  28. The New Ad Stack Behind Live Sports Streaming: Inside SGAI, EABN, and the Standards Race to Fix Live Monetization
    674
  29. Designing MLOps Architectures to Handle Seasonal Data Drift in EV Fleet Models
    201
  30. From 15 to 40+ FPS: Accelerating PyTorch Object Detection on Automotive ECUs
    233