<p>Using C# and WPF under .NET (rather than <a href="http://en.wikipedia.org/wiki/Windows_Forms" rel="noreferrer">Windows Forms</a> or console), what is the correct way to create an application that can only be run as a single instance?</p>

<p>I know it has something to do with some mythical thing called a mutex, rarely can I find someone that bothers to stop and explain what one of these are.</p>

<p>The code needs to also inform the already-running instance that the user tried to start a second one, and maybe also pass any command-line arguments if any existed.</p>

[{'answer_id': 19165, 'author': 'jason saldo', 'author_id': 1293, 'author_profile': 'https://Stackoverflow.com/users/1293', 'pm_score': 7, 'selected': False, 'text': '<p>From <a href="http://www.albahari.com/threading/part2.html#_MutexSingleAppInstance" rel="noreferrer">here</a>.</p>\n\n<p>A common use for a cross-process Mutex is to ensure that only instance of a program can run at a time. Here\'s how it\'s done:</p>\n\n<pre><code>class OneAtATimePlease {\n\n  // Use a name unique to the application (eg include your company URL)\n  static Mutex mutex = new Mutex (false, "oreilly.com OneAtATimeDemo");\n\n  static void Main()\n  {\n    // Wait 5 seconds if contended – in case another instance\n    // of the program is in the process of shutting down.\n    if (!mutex.WaitOne(TimeSpan.FromSeconds (5), false))\n    {\n        Console.WriteLine("Another instance of the app is running. Bye!");\n        return;\n    }\n\n    try\n    {    \n        Console.WriteLine("Running - press Enter to exit");\n        Console.ReadLine();\n    }\n    finally\n    {\n        mutex.ReleaseMutex();\n    }    \n  }    \n}\n</code></pre>\n\n<p>A good feature of Mutex is that if the application terminates without ReleaseMutex first being called, the CLR will release the Mutex automatically.</p>\n'}, {'answer_id': 19326, 'author': 'Dale Ragan', 'author_id': 1117, 'author_profile': 'https://Stackoverflow.com/users/1117', 'pm_score': 7, 'selected': False, 'text': '<p>You could use the Mutex class, but you will soon find out that you will need to implement the code to pass the arguments and such yourself.  Well, I learned a trick when programming in WinForms when I read <a href="http://sellsbrothers.com/wfbook/" rel="noreferrer">Chris Sell\'s book</a>.  This trick uses logic that is already available to us in the framework.  I don\'t know about you, but when I learn about stuff I can reuse in the framework, that is usually the route I take instead of reinventing the wheel.  Unless of course it doesn\'t do everything I want.</p>\n\n<p>When I got into WPF, I came up with a way to use that same code, but in a WPF application.  This solution should meet your needs based off your question.</p>\n\n<p>First, we need to create our application class.  In this class we are going override the OnStartup event and create a method called Activate, which will be used later.</p>\n\n<pre><code>public class SingleInstanceApplication : System.Windows.Application\n{\n    protected override void OnStartup(System.Windows.StartupEventArgs e)\n    {\n        // Call the OnStartup event on our base class\n        base.OnStartup(e);\n\n        // Create our MainWindow and show it\n        MainWindow window = new MainWindow();\n        window.Show();\n    }\n\n    public void Activate()\n    {\n        // Reactivate the main window\n        MainWindow.Activate();\n    }\n}\n</code></pre>\n\n<p>Second, we will need to create a class that can manage our instances.  Before we go through that, we are actually going to reuse some code that is in the Microsoft.VisualBasic assembly.  Since, I am using C# in this example, I had to make a reference to the assembly.  If you are using VB.NET, you don\'t have to do anything.  The class we are going to use is WindowsFormsApplicationBase and inherit our instance manager off of it and then leverage properties and events to handle the single instancing.</p>\n\n<pre><code>public class SingleInstanceManager : Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase\n{\n    private SingleInstanceApplication _application;\n    private System.Collections.ObjectModel.ReadOnlyCollection&lt;string&gt; _commandLine;\n\n    public SingleInstanceManager()\n    {\n        IsSingleInstance = true;\n    }\n\n    protected override bool OnStartup(Microsoft.VisualBasic.ApplicationServices.StartupEventArgs eventArgs)\n    {\n        // First time _application is launched\n        _commandLine = eventArgs.CommandLine;\n        _application = new SingleInstanceApplication();\n        _application.Run();\n        return false;\n    }\n\n    protected override void OnStartupNextInstance(StartupNextInstanceEventArgs eventArgs)\n    {\n        // Subsequent launches\n        base.OnStartupNextInstance(eventArgs);\n        _commandLine = eventArgs.CommandLine;\n        _application.Activate();\n    }\n}\n</code></pre>\n\n<p>Basically, we are using the VB bits to detect single instance\'s and process accordingly.  OnStartup will be fired when the first instance loads.  OnStartupNextInstance is fired when the application is re-run again.  As you can see, I can get to what was passed on the command line through the event arguments.  I set the value to an instance field.  You could parse the command line here, or you could pass it to your application through the constructor and the call to the Activate method.</p>\n\n<p>Third, it\'s time to create our EntryPoint.  Instead of newing up the application like you would normally do, we are going to take advantage of our SingleInstanceManager.</p>\n\n<pre><code>public class EntryPoint\n{\n    [STAThread]\n    public static void Main(string[] args)\n    {\n        SingleInstanceManager manager = new SingleInstanceManager();\n        manager.Run(args);\n    }\n}\n</code></pre>\n\n<p>Well, I hope you are able to follow everything and be able use this implementation and make it your own.</p>\n'}, {'answer_id': 481203, 'author': 'Matt Davison', 'author_id': 1995476, 'author_profile': 'https://Stackoverflow.com/users/1995476', 'pm_score': 2, 'selected': False, 'text': '<p>You should never use a named mutex to implement a single-instance application (or at least not for production code). Malicious code can easily DoS (<a href="https://en.wikipedia.org/wiki/Denial-of-service_attack" rel="nofollow noreferrer">Denial of Service</a>) your ass...</p>\n'}, {'answer_id': 522874, 'author': 'Matt Davis', 'author_id': 51170, 'author_profile': 'https://Stackoverflow.com/users/51170', 'pm_score': 10, 'selected': True, 'text': '<p>Here is a very good <a href="http://sanity-free.org/143/csharp_dotnet_single_instance_application.html" rel="noreferrer">article</a> regarding the Mutex solution.  The approach described by the article is advantageous for two reasons.</p>\n\n<p>First, it does not require a dependency on the Microsoft.VisualBasic assembly.  If my project already had a dependency on that assembly, I would probably advocate using the approach <a href="https://stackoverflow.com/a/19326/3195477">shown in another answer</a>.  But as it is, I do not use the Microsoft.VisualBasic assembly, and I\'d rather not add an unnecessary dependency to my project.</p>\n\n<p>Second, the article shows how to bring the existing instance of the application to the foreground when the user tries to start another instance.  That\'s a very nice touch that the other Mutex solutions described here do not address.</p>\n\n<hr>\n\n<h3>UPDATE</h3>\n\n<p>As of 8/1/2014, the article I linked to above is still active, but the blog hasn\'t been updated in a while.  That makes me worry that eventually it might disappear, and with it, the advocated solution.  I\'m reproducing the content of the article here for posterity.  The words belong solely to the blog owner at <a href="http://sanity-free.org/" rel="noreferrer">Sanity Free Coding</a>.</p>\n\n<blockquote>\n  <p>Today I wanted to refactor some code that prohibited my application\n  from running multiple instances of itself.</p>\n  \n  <p>Previously I had use <a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.process(v=vs.110).aspx" rel="noreferrer">System.Diagnostics.Process</a> to search for an\n  instance of my myapp.exe in the process list. While this works, it\n  brings on a lot of overhead, and I wanted something cleaner.</p>\n  \n  <p>Knowing that I could use a mutex for this (but never having done it\n  before) I set out to cut down my code and simplify my life.</p>\n  \n  <p>In the class of my application main I created a static named <a href="http://msdn.microsoft.com/en-us/library/system.threading.mutex(v=vs.110).aspx" rel="noreferrer">Mutex</a>:</p>\n</blockquote>\n\n<pre><code>static class Program\n{\n    static Mutex mutex = new Mutex(true, "{8F6F0AC4-B9A1-45fd-A8CF-72F04E6BDE8F}");\n    [STAThread]\n    ...\n}\n</code></pre>\n\n<blockquote>\n  <p>Having a named mutex allows us to stack synchronization across\n  multiple threads and processes which is just the magic I\'m looking\n  for.</p>\n  \n  <p><a href="http://msdn.microsoft.com/en-us/library/58195swd(v=vs.110).aspx" rel="noreferrer">Mutex.WaitOne</a> has an overload that specifies an amount of time for us\n  to wait. Since we\'re not actually wanting to synchronizing our code\n  (more just check if it is currently in use) we use the overload with\n  two parameters: <a href="http://msdn.microsoft.com/en-us/library/85bbbxt9(v=vs.110).aspx" rel="noreferrer">Mutex.WaitOne(Timespan timeout, bool exitContext)</a>.\n  Wait one returns true if it is able to enter, and false if it wasn\'t.\n  In this case, we don\'t want to wait at all; If our mutex is being\n  used, skip it, and move on, so we pass in TimeSpan.Zero (wait 0\n  milliseconds), and set the exitContext to true so we can exit the\n  synchronization context before we try to aquire a lock on it. Using\n  this, we wrap our Application.Run code inside something like this:</p>\n</blockquote>\n\n<pre><code>static class Program\n{\n    static Mutex mutex = new Mutex(true, "{8F6F0AC4-B9A1-45fd-A8CF-72F04E6BDE8F}");\n    [STAThread]\n    static void Main() {\n        if(mutex.WaitOne(TimeSpan.Zero, true)) {\n            Application.EnableVisualStyles();\n            Application.SetCompatibleTextRenderingDefault(false);\n            Application.Run(new Form1());\n            mutex.ReleaseMutex();\n        } else {\n            MessageBox.Show("only one instance at a time");\n        }\n    }\n}\n</code></pre>\n\n<blockquote>\n  <p>So, if our app is running, WaitOne will return false, and we\'ll get a\n  message box.</p>\n  \n  <p>Instead of showing a message box, I opted to utilize a little Win32 to\n  notify my running instance that someone forgot that it was already\n  running (by bringing itself to the top of all the other windows). To\n  achieve this I used <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/ms644944(v=vs.85).aspx" rel="noreferrer">PostMessage</a> to broadcast a custom message to every\n  window (the custom message was registered with <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/ms644947(v=vs.85).aspx" rel="noreferrer">RegisterWindowMessage</a>\n  by my running application, which means only my application knows what\n  it is) then my second instance exits. The running application instance\n  would receive that notification and process it. In order to do that, I\n  overrode <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.form.wndproc(v=vs.110).aspx" rel="noreferrer">WndProc</a> in my main form and listened for my custom\n  notification. When I received that notification I set the form\'s\n  TopMost property to true to bring it up on top.</p>\n  \n  <p>Here is what I ended up with:</p>\n  \n  <ul>\n  <li>Program.cs</li>\n  </ul>\n</blockquote>\n\n<pre><code>static class Program\n{\n    static Mutex mutex = new Mutex(true, "{8F6F0AC4-B9A1-45fd-A8CF-72F04E6BDE8F}");\n    [STAThread]\n    static void Main() {\n        if(mutex.WaitOne(TimeSpan.Zero, true)) {\n            Application.EnableVisualStyles();\n            Application.SetCompatibleTextRenderingDefault(false);\n            Application.Run(new Form1());\n            mutex.ReleaseMutex();\n        } else {\n            // send our Win32 message to make the currently running instance\n            // jump on top of all the other windows\n            NativeMethods.PostMessage(\n                (IntPtr)NativeMethods.HWND_BROADCAST,\n                NativeMethods.WM_SHOWME,\n                IntPtr.Zero,\n                IntPtr.Zero);\n        }\n    }\n}\n</code></pre>\n\n<blockquote>\n  <ul>\n  <li>NativeMethods.cs</li>\n  </ul>\n</blockquote>\n\n<pre><code>// this class just wraps some Win32 stuff that we\'re going to use\ninternal class NativeMethods\n{\n    public const int HWND_BROADCAST = 0xffff;\n    public static readonly int WM_SHOWME = RegisterWindowMessage("WM_SHOWME");\n    [DllImport("user32")]\n    public static extern bool PostMessage(IntPtr hwnd, int msg, IntPtr wparam, IntPtr lparam);\n    [DllImport("user32")]\n    public static extern int RegisterWindowMessage(string message);\n}\n</code></pre>\n\n<blockquote>\n  <ul>\n  <li>Form1.cs (front side partial)</li>\n  </ul>\n</blockquote>\n\n<pre><code>public partial class Form1 : Form\n{\n    public Form1()\n    {\n        InitializeComponent();\n    }\n    protected override void WndProc(ref Message m)\n    {\n        if(m.Msg == NativeMethods.WM_SHOWME) {\n            ShowMe();\n        }\n        base.WndProc(ref m);\n    }\n    private void ShowMe()\n    {\n        if(WindowState == FormWindowState.Minimized) {\n            WindowState = FormWindowState.Normal;\n        }\n        // get our current "TopMost" value (ours will always be false though)\n        bool top = TopMost;\n        // make our form jump to the top of everything\n        TopMost = true;\n        // set it back to whatever it was\n        TopMost = top;\n    }\n}\n</code></pre>\n'}, {'answer_id': 1924705, 'author': 'Bruce', 'author_id': 133297, 'author_profile': 'https://Stackoverflow.com/users/133297', 'pm_score': 4, 'selected': False, 'text': '<p>Just some thoughts:\nThere are cases when requiring that only one instance of an application is not "lame" as some would have you believe. Database apps, etc. are an order of magnitude more difficult if one allows multiple instances of the app for a single user to access a database (you know, all that updating all the records that are open in multiple instances of the app on the users machine, etc.). \nFirst, for the "name collision thing, don\'t use a human readable name - use a GUID instead or, even better a GUID + the human readable name. Chances of name collision just dropped off the radar and the Mutex doesn\'t care. As someone pointed out, a DOS attack would suck, but if the malicious person has gone to the trouble of getting the mutex name and incorporating it into their app, you are pretty much a target anyway and will have to do MUCH more to protect yourself than just fiddle a mutex name.\nAlso, if one uses the variant of:\nnew Mutex(true, "some GUID plus Name", out AIsFirstInstance), you already have your indicator as to whether or not the Mutex is the first instance.</p>\n'}, {'answer_id': 2295625, 'author': 'Oliver Friedrich', 'author_id': 44532, 'author_profile': 'https://Stackoverflow.com/users/44532', 'pm_score': 4, 'selected': False, 'text': '<p>Well, I have a disposable Class for this that works easily for most use cases:</p>\n\n<p>Use it like this:</p>\n\n<pre><code>static void Main()\n{\n    using (SingleInstanceMutex sim = new SingleInstanceMutex())\n    {\n        if (sim.IsOtherInstanceRunning)\n        {\n            Application.Exit();\n        }\n\n        // Initialize program here.\n    }\n}\n</code></pre>\n\n<p>Here it is:</p>\n\n<pre><code>/// &lt;summary&gt;\n/// Represents a &lt;see cref="SingleInstanceMutex"/&gt; class.\n/// &lt;/summary&gt;\npublic partial class SingleInstanceMutex : IDisposable\n{\n    #region Fields\n\n    /// &lt;summary&gt;\n    /// Indicator whether another instance of this application is running or not.\n    /// &lt;/summary&gt;\n    private bool isNoOtherInstanceRunning;\n\n    /// &lt;summary&gt;\n    /// The &lt;see cref="Mutex"/&gt; used to ask for other instances of this application.\n    /// &lt;/summary&gt;\n    private Mutex singleInstanceMutex = null;\n\n    /// &lt;summary&gt;\n    /// An indicator whether this object is beeing actively disposed or not.\n    /// &lt;/summary&gt;\n    private bool disposed;\n\n    #endregion\n\n    #region Constructor\n\n    /// &lt;summary&gt;\n    /// Initializes a new instance of the &lt;see cref="SingleInstanceMutex"/&gt; class.\n    /// &lt;/summary&gt;\n    public SingleInstanceMutex()\n    {\n        this.singleInstanceMutex = new Mutex(true, Assembly.GetCallingAssembly().FullName, out this.isNoOtherInstanceRunning);\n    }\n\n    #endregion\n\n    #region Properties\n\n    /// &lt;summary&gt;\n    /// Gets an indicator whether another instance of the application is running or not.\n    /// &lt;/summary&gt;\n    public bool IsOtherInstanceRunning\n    {\n        get\n        {\n            return !this.isNoOtherInstanceRunning;\n        }\n    }\n\n    #endregion\n\n    #region Methods\n\n    /// &lt;summary&gt;\n    /// Closes the &lt;see cref="SingleInstanceMutex"/&gt;.\n    /// &lt;/summary&gt;\n    public void Close()\n    {\n        this.ThrowIfDisposed();\n        this.singleInstanceMutex.Close();\n    }\n\n    public void Dispose()\n    {\n        this.Dispose(true);\n        GC.SuppressFinalize(this);\n    }\n\n    private void Dispose(bool disposing)\n    {\n        if (!this.disposed)\n        {\n            /* Release unmanaged ressources */\n\n            if (disposing)\n            {\n                /* Release managed ressources */\n                this.Close();\n            }\n\n            this.disposed = true;\n        }\n    }\n\n    /// &lt;summary&gt;\n    /// Throws an exception if something is tried to be done with an already disposed object.\n    /// &lt;/summary&gt;\n    /// &lt;remarks&gt;\n    /// All public methods of the class must first call this.\n    /// &lt;/remarks&gt;\n    public void ThrowIfDisposed()\n    {\n        if (this.disposed)\n        {\n            throw new ObjectDisposedException(this.GetType().Name);\n        }\n    }\n\n    #endregion\n}\n</code></pre>\n'}, {'answer_id': 2769924, 'author': 'Peter', 'author_id': 331895, 'author_profile': 'https://Stackoverflow.com/users/331895', 'pm_score': 3, 'selected': False, 'text': '<p>So many answers to such a seemingly simple question.  Just to shake things up a little bit here is my solution to this problem.</p>\n\n<p>Creating a Mutex can be troublesome because the JIT-er only sees you using it for a small portion of your code and wants to mark it as ready for garbage collection.  It pretty much wants to out-smart you thinking you are not going to be using that Mutex for that long.  In reality you want to hang onto this Mutex for as long as your application is running.  The best way to tell the garbage collector to leave you Mutex alone is to tell it to keep it alive though out the different generations of garage collection.  Example:</p>\n\n<pre><code>var m = new Mutex(...);\n...\nGC.KeepAlive(m);\n</code></pre>\n\n<p>I lifted the idea from this page: <a href="http://www.ai.uga.edu/~mc/SingleInstance.html" rel="noreferrer">http://www.ai.uga.edu/~mc/SingleInstance.html</a></p>\n'}, {'answer_id': 2932076, 'author': 'huseyint', 'author_id': 39, 'author_profile': 'https://Stackoverflow.com/users/39', 'pm_score': 4, 'selected': False, 'text': '<p>A new one that uses Mutex and IPC stuff, and also passes any command line arguments to the running instance, is <em><a href="http://blogs.microsoft.co.il/blogs/arik/archive/2010/05/28/wpf-single-instance-application.aspx" rel="noreferrer">WPF Single Instance Application</a></em>.</p>\n'}, {'answer_id': 3089321, 'author': 'Sergey Aldoukhov', 'author_id': 58463, 'author_profile': 'https://Stackoverflow.com/users/58463', 'pm_score': 2, 'selected': False, 'text': '<p>Here is what I use. It combined process enumeration to perform switching and mutex to safeguard from "active clickers":</p>\n\n<pre><code>public partial class App\n{\n    [DllImport("user32")]\n    private static extern int OpenIcon(IntPtr hWnd);\n\n    [DllImport("user32.dll")]\n    private static extern bool SetForegroundWindow(IntPtr hWnd);\n\n    protected override void OnStartup(StartupEventArgs e)\n    {\n        base.OnStartup(e);\n        var p = Process\n           .GetProcessesByName(Process.GetCurrentProcess().ProcessName);\n            foreach (var t in p.Where(t =&gt; t.MainWindowHandle != IntPtr.Zero))\n            {\n                OpenIcon(t.MainWindowHandle);\n                SetForegroundWindow(t.MainWindowHandle);\n                Current.Shutdown();\n                return;\n            }\n\n            // there is a chance the user tries to click on the icon repeatedly\n            // and the process cannot be discovered yet\n            bool createdNew;\n            var mutex = new Mutex(true, "MyAwesomeApp", \n               out createdNew);  // must be a variable, though it is unused - \n            // we just need a bit of time until the process shows up\n            if (!createdNew)\n            {\n                Current.Shutdown();\n                return;\n            }\n\n            new Bootstrapper().Run();\n        }\n    }\n</code></pre>\n'}, {'answer_id': 3808173, 'author': 'Simon_Weaver', 'author_id': 16940, 'author_profile': 'https://Stackoverflow.com/users/16940', 'pm_score': 6, 'selected': False, 'text': '<p>MSDN actually has a sample application for both C# and VB to do exactly this: <a href="http://msdn.microsoft.com/en-us/library/ms771662(v=VS.90).aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/ms771662(v=VS.90).aspx</a></p>\n\n<blockquote>\n  <p>The most common and reliable technique\n  for developing single-instance\n  detection is to use the Microsoft .NET\n  Framework remoting infrastructure\n  (System.Remoting). The Microsoft .NET\n  Framework (version 2.0) includes a\n  type, WindowsFormsApplicationBase,\n  which encapsulates the required\n  remoting functionality. To incorporate\n  this type into a WPF application, a\n  type needs to derive from it, and be\n  used as a shim between the application\n  static entry point method, Main, and\n  the WPF application\'s Application\n  type. The shim detects when an\n  application is first launched, and\n  when subsequent launches are\n  attempted, and yields control the WPF\n  Application type to determine how to\n  process the launches.</p>\n</blockquote>\n\n<ul>\n<li>For C# people just take a deep breath and forget about  the whole \'I don\'t wanna include VisualBasic DLL\'. Because of <a href="https://stackoverflow.com/questions/226517/is-the-microsoft-visualbasic-namespace-true-net-code">this</a> and what <a href="http://www.hanselman.com/blog/TheWeeklySourceCode31SingleInstanceWinFormsAndMicrosoftVisualBasicdll.aspx" rel="noreferrer">Scott Hanselman says</a> and the fact that this pretty much is the cleanest solution to the problem and is designed by people who know a lot more about the framework than you do.</li>\n<li>From a usability standpoint the fact is if your user is loading an application and it is already open and you\'re giving them an error message like <code>\'Another instance of the app is running. Bye\'</code> then they\'re not gonna be a very happy user. You simply MUST (in a GUI application) switch to that application and pass in the arguments provided - or if command line parameters have no meaning then you must pop up the application which may have been minimized.</li>\n</ul>\n\n<p>The framework already has support for this - its just that some idiot named the DLL <code>Microsoft.VisualBasic</code> and it didn\'t get put into <code>Microsoft.ApplicationUtils</code> or something like that. Get over it - or open up Reflector.</p>\n\n<p>Tip: If you use this approach exactly as is, and you already have an App.xaml with resources etc. you\'ll want to <a href="http://www.infosysblogs.com/microsoft/2008/09/how_to_write_custom_main_metho.html" rel="noreferrer">take a look at this too</a>.</p>\n'}, {'answer_id': 5536495, 'author': 'Mikhail Semenov', 'author_id': 653772, 'author_profile': 'https://Stackoverflow.com/users/653772', 'pm_score': 2, 'selected': False, 'text': "<p>I found the simpler solution, similar to Dale Ragan's, but slightly modified. It does practically everything you need and based on the standard Microsoft WindowsFormsApplicationBase class.</p>\n\n<p>Firstly, you create SingleInstanceController class, which you can use in all other single-instance applications, which use Windows Forms:</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Windows.Forms;\nusing Microsoft.VisualBasic.ApplicationServices;\n\n\nnamespace SingleInstanceController_NET\n{\n    public class SingleInstanceController\n    : WindowsFormsApplicationBase\n    {\n        public delegate Form CreateMainForm();\n        public delegate void StartNextInstanceDelegate(Form mainWindow);\n        CreateMainForm formCreation;\n        StartNextInstanceDelegate onStartNextInstance;\n        public SingleInstanceController(CreateMainForm formCreation, StartNextInstanceDelegate onStartNextInstance)\n        {\n            // Set whether the application is single instance\n            this.formCreation = formCreation;\n            this.onStartNextInstance = onStartNextInstance;\n            this.IsSingleInstance = true;\n\n            this.StartupNextInstance += new StartupNextInstanceEventHandler(this_StartupNextInstance);                      \n        }\n\n        void this_StartupNextInstance(object sender, StartupNextInstanceEventArgs e)\n        {\n            if (onStartNextInstance != null)\n            {\n                onStartNextInstance(this.MainForm); // This code will be executed when the user tries to start the running program again,\n                                                    // for example, by clicking on the exe file.\n            }                                       // This code can determine how to re-activate the existing main window of the running application.\n        }\n\n        protected override void OnCreateMainForm()\n        {\n            // Instantiate your main application form\n            this.MainForm = formCreation();\n        }\n\n        public void Run()\n        {\n            string[] commandLine = new string[0];\n            base.Run(commandLine);\n        }\n    }\n}\n</code></pre>\n\n<p>Then you can use it in your program as follows:</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Windows.Forms;\nusing SingleInstanceController_NET;\n\nnamespace SingleInstance\n{\n    static class Program\n    {\n        /// &lt;summary&gt;\n        /// The main entry point for the application.\n        /// &lt;/summary&gt;\n        static Form CreateForm()\n        {\n            return new Form1(); // Form1 is used for the main window.\n        }\n\n        static void OnStartNextInstance(Form mainWindow) // When the user tries to restart the application again,\n                                                         // the main window is activated again.\n        {\n            mainWindow.WindowState = FormWindowState.Maximized;\n        }\n        [STAThread]\n        static void Main()\n        {\n            Application.EnableVisualStyles();\n            Application.SetCompatibleTextRenderingDefault(false);            \n            SingleInstanceController controller = new SingleInstanceController(CreateForm, OnStartNextInstance);\n            controller.Run();         \n        }\n    }\n}\n</code></pre>\n\n<p>Both the program and the SingleInstanceController_NET solution should reference Microsoft.VisualBasic . If you just want to reactivate the running application as a normal window when the user tries to restart the running program, the second parameter in the SingleInstanceController can be null. In the given example, the window is maximized.</p>\n"}, {'answer_id': 5919904, 'author': 'Nathan Moinvaziri', 'author_id': 610692, 'author_profile': 'https://Stackoverflow.com/users/610692', 'pm_score': 4, 'selected': False, 'text': '<p>Here is an example that allows you to have a single instance of an application. When any new instances load, they pass their arguments to the main instance that is running.</p>\n\n<pre><code>public partial class App : Application\n{\n    private static Mutex SingleMutex;\n    public static uint MessageId;\n\n    private void Application_Startup(object sender, StartupEventArgs e)\n    {\n        IntPtr Result;\n        IntPtr SendOk;\n        Win32.COPYDATASTRUCT CopyData;\n        string[] Args;\n        IntPtr CopyDataMem;\n        bool AllowMultipleInstances = false;\n\n        Args = Environment.GetCommandLineArgs();\n\n        // TODO: Replace {00000000-0000-0000-0000-000000000000} with your application\'s GUID\n        MessageId   = Win32.RegisterWindowMessage("{00000000-0000-0000-0000-000000000000}");\n        SingleMutex = new Mutex(false, "AppName");\n\n        if ((AllowMultipleInstances) || (!AllowMultipleInstances &amp;&amp; SingleMutex.WaitOne(1, true)))\n        {\n            new Main();\n        }\n        else if (Args.Length &gt; 1)\n        {\n            foreach (Process Proc in Process.GetProcesses())\n            {\n                SendOk = Win32.SendMessageTimeout(Proc.MainWindowHandle, MessageId, IntPtr.Zero, IntPtr.Zero,\n                    Win32.SendMessageTimeoutFlags.SMTO_BLOCK | Win32.SendMessageTimeoutFlags.SMTO_ABORTIFHUNG,\n                    2000, out Result);\n\n                if (SendOk == IntPtr.Zero)\n                    continue;\n                if ((uint)Result != MessageId)\n                    continue;\n\n                CopyDataMem = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(Win32.COPYDATASTRUCT)));\n\n                CopyData.dwData = IntPtr.Zero;\n                CopyData.cbData = Args[1].Length*2;\n                CopyData.lpData = Marshal.StringToHGlobalUni(Args[1]);\n\n                Marshal.StructureToPtr(CopyData, CopyDataMem, false);\n\n                Win32.SendMessageTimeout(Proc.MainWindowHandle, Win32.WM_COPYDATA, IntPtr.Zero, CopyDataMem,\n                    Win32.SendMessageTimeoutFlags.SMTO_BLOCK | Win32.SendMessageTimeoutFlags.SMTO_ABORTIFHUNG,\n                    5000, out Result);\n\n                Marshal.FreeHGlobal(CopyData.lpData);\n                Marshal.FreeHGlobal(CopyDataMem);\n            }\n\n            Shutdown(0);\n        }\n    }\n}\n\npublic partial class Main : Window\n{\n    private void Window_Loaded(object sender, RoutedEventArgs e)\n    {\n        HwndSource Source;\n\n        Source = HwndSource.FromHwnd(new WindowInteropHelper(this).Handle);\n        Source.AddHook(new HwndSourceHook(Window_Proc));\n    }\n\n    private IntPtr Window_Proc(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam, ref bool Handled)\n    {\n        Win32.COPYDATASTRUCT CopyData;\n        string Path;\n\n        if (Msg == Win32.WM_COPYDATA)\n        {\n            CopyData = (Win32.COPYDATASTRUCT)Marshal.PtrToStructure(lParam, typeof(Win32.COPYDATASTRUCT));\n            Path = Marshal.PtrToStringUni(CopyData.lpData, CopyData.cbData / 2);\n\n            if (WindowState == WindowState.Minimized)\n            {\n                // Restore window from tray\n            }\n\n            // Do whatever we want with information\n\n            Activate();\n            Focus();\n        }\n\n        if (Msg == App.MessageId)\n        {\n            Handled = true;\n            return new IntPtr(App.MessageId);\n        }\n\n        return IntPtr.Zero;\n    }\n}\n\npublic class Win32\n{\n    public const uint WM_COPYDATA = 0x004A;\n\n    public struct COPYDATASTRUCT\n    {\n        public IntPtr dwData;\n        public int    cbData;\n        public IntPtr lpData;\n    }\n\n    [Flags]\n    public enum SendMessageTimeoutFlags : uint\n    {\n        SMTO_NORMAL             = 0x0000,\n        SMTO_BLOCK              = 0x0001,\n        SMTO_ABORTIFHUNG        = 0x0002,\n        SMTO_NOTIMEOUTIFNOTHUNG = 0x0008\n    }\n\n    [DllImport("user32.dll", SetLastError=true, CharSet=CharSet.Auto)]\n    public static extern uint RegisterWindowMessage(string lpString);\n    [DllImport("user32.dll")]\n    public static extern IntPtr SendMessageTimeout(\n        IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam,\n        SendMessageTimeoutFlags fuFlags, uint uTimeout, out IntPtr lpdwResult);\n}\n</code></pre>\n'}, {'answer_id': 7030059, 'author': 'Joel Barsotti', 'author_id': 37154, 'author_profile': 'https://Stackoverflow.com/users/37154', 'pm_score': 3, 'selected': False, 'text': '<p>It looks like there is a really good way to handle this:</p>\n\n<p><em><a href="http://blogs.microsoft.co.il/blogs/arik/archive/2010/05/28/wpf-single-instance-application.aspx" rel="nofollow">WPF Single Instance Application</a></em></p>\n\n<p>This provides a class you can add that manages all the mutex and messaging cruff to simplify the your implementation to the point where it\'s simply trivial.</p>\n'}, {'answer_id': 7183246, 'author': 'CharithJ', 'author_id': 591656, 'author_profile': 'https://Stackoverflow.com/users/591656', 'pm_score': 5, 'selected': False, 'text': '<p>This code should go to the main method. Look at <a href="http://joyfulwpf.blogspot.com/2009/05/where-is-main-method-in-my-wpf.html" rel="noreferrer">here</a> for more information about the main method in WPF.</p>\n\n<pre><code>[DllImport("user32.dll")]\nprivate static extern Boolean ShowWindow(IntPtr hWnd, Int32 nCmdShow);\n\nprivate const int SW_SHOWMAXIMIZED = 3;\n\nstatic void Main() \n{\n    Process currentProcess = Process.GetCurrentProcess();\n    var runningProcess = (from process in Process.GetProcesses()\n                          where\n                            process.Id != currentProcess.Id &amp;&amp;\n                            process.ProcessName.Equals(\n                              currentProcess.ProcessName,\n                              StringComparison.Ordinal)\n                          select process).FirstOrDefault();\n    if (runningProcess != null)\n    {\n        ShowWindow(runningProcess.MainWindowHandle, SW_SHOWMAXIMIZED);\n       return; \n    }\n}\n</code></pre>\n\n<p><strong>Method 2</strong></p>\n\n<pre><code>static void Main()\n{\n    string procName = Process.GetCurrentProcess().ProcessName;\n    // get the list of all processes by that name\n\n    Process[] processes=Process.GetProcessesByName(procName);\n\n    if (processes.Length &gt; 1)\n    {\n        MessageBox.Show(procName + " already running");  \n        return;\n    } \n    else\n    {\n        // Application.Run(...);\n    }\n}\n</code></pre>\n\n<p><strong>Note :</strong> Above methods assumes your process/application has a unique name. Because it uses process name to find if any existing processors. So, if your application has a very common name (ie: Notepad), above approach won\'t work. </p>\n'}, {'answer_id': 13646352, 'author': 'carlito', 'author_id': 1865565, 'author_profile': 'https://Stackoverflow.com/users/1865565', 'pm_score': 3, 'selected': False, 'text': '<p>Look at the folllowing code. It is a great and simple solution to prevent multiple instances of a WPF application.</p>\n\n<pre><code>private void Application_Startup(object sender, StartupEventArgs e)\n{\n    Process thisProc = Process.GetCurrentProcess();\n    if (Process.GetProcessesByName(thisProc.ProcessName).Length &gt; 1)\n    {\n        MessageBox.Show("Application running");\n        Application.Current.Shutdown();\n        return;\n    }\n\n    var wLogin = new LoginWindow();\n\n    if (wLogin.ShowDialog() == true)\n    {\n        var wMain = new Main();\n        wMain.WindowState = WindowState.Maximized;\n        wMain.Show();\n    }\n    else\n    {\n        Application.Current.Shutdown();\n    }\n}\n</code></pre>\n'}, {'answer_id': 14337614, 'author': 'Tommaso Belluzzo', 'author_id': 796085, 'author_profile': 'https://Stackoverflow.com/users/796085', 'pm_score': 0, 'selected': False, 'text': '<p>Normally, this is the code I use for single-instance <a href="http://en.wikipedia.org/wiki/Windows_Forms" rel="nofollow">Windows Forms</a> applications:</p>\n\n<pre><code>[STAThread]\npublic static void Main()\n{\n    String assemblyName = Assembly.GetExecutingAssembly().GetName().Name;\n\n    using (Mutex mutex = new Mutex(false, assemblyName))\n    {\n        if (!mutex.WaitOne(0, false))\n        {\n            Boolean shownProcess = false;\n            Process currentProcess = Process.GetCurrentProcess();\n\n            foreach (Process process in Process.GetProcessesByName(currentProcess.ProcessName))\n            {\n                if (!process.Id.Equals(currentProcess.Id) &amp;&amp; process.MainModule.FileName.Equals(currentProcess.MainModule.FileName) &amp;&amp; !process.MainWindowHandle.Equals(IntPtr.Zero))\n                {\n                    IntPtr windowHandle = process.MainWindowHandle;\n\n                    if (NativeMethods.IsIconic(windowHandle))\n                        NativeMethods.ShowWindow(windowHandle, ShowWindowCommand.Restore);\n\n                    NativeMethods.SetForegroundWindow(windowHandle);\n\n                    shownProcess = true;\n                }\n            }\n\n            if (!shownProcess)\n                MessageBox.Show(String.Format(CultureInfo.CurrentCulture, "An instance of {0} is already running!", assemblyName), assemblyName, MessageBoxButtons.OK, MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1, (MessageBoxOptions)0);\n        }\n        else\n        {\n            Application.EnableVisualStyles();\n            Application.SetCompatibleTextRenderingDefault(false);\n            Application.Run(new Form());\n        }\n    }\n}\n</code></pre>\n\n<p>Where native components are:</p>\n\n<pre><code>[DllImport("User32.dll", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)]\n[return: MarshalAs(UnmanagedType.Bool)]\ninternal static extern Boolean IsIconic([In] IntPtr windowHandle);\n\n[DllImport("User32.dll", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)]\n[return: MarshalAs(UnmanagedType.Bool)]\ninternal static extern Boolean SetForegroundWindow([In] IntPtr windowHandle);\n\n[DllImport("User32.dll", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)]\n[return: MarshalAs(UnmanagedType.Bool)]\ninternal static extern Boolean ShowWindow([In] IntPtr windowHandle, [In] ShowWindowCommand command);\n\npublic enum ShowWindowCommand : int\n{\n    Hide                   = 0x0,\n    ShowNormal             = 0x1,\n    ShowMinimized          = 0x2,\n    ShowMaximized          = 0x3,\n    ShowNormalNotActive    = 0x4,\n    Minimize               = 0x6,\n    ShowMinimizedNotActive = 0x7,\n    ShowCurrentNotActive   = 0x8,\n    Restore                = 0x9,\n    ShowDefault            = 0xA,\n    ForceMinimize          = 0xB\n}\n</code></pre>\n'}, {'answer_id': 16097909, 'author': 'Dan', 'author_id': 1507012, 'author_profile': 'https://Stackoverflow.com/users/1507012', 'pm_score': 3, 'selected': False, 'text': '<p>The following code is my WCF named pipes solution to register a single-instance application. It\'s nice because it also raises an event when another instance attempts to start, and receives the command line of the other instance.</p>\n\n<p>It\'s geared toward WPF because it uses the <code>System.Windows.StartupEventHandler</code> class, but this could be easily modified.</p>\n\n<p>This code requires a reference to <code>PresentationFramework</code>, and <code>System.ServiceModel</code>.</p>\n\n<p><strong>Usage:</strong></p>\n\n<pre><code>class Program\n{\n    static void Main()\n    {\n        var applicationId = new Guid("b54f7b0d-87f9-4df9-9686-4d8fd76066dc");\n\n        if (SingleInstanceManager.VerifySingleInstance(applicationId))\n        {\n            SingleInstanceManager.OtherInstanceStarted += OnOtherInstanceStarted;\n\n            // Start the application\n        }\n    }\n\n    static void OnOtherInstanceStarted(object sender, StartupEventArgs e)\n    {\n        // Do something in response to another instance starting up.\n    }\n}\n</code></pre>\n\n<h3>Source Code:</h3>\n\n<pre><code>/// &lt;summary&gt;\n/// A class to use for single-instance applications.\n/// &lt;/summary&gt;\npublic static class SingleInstanceManager\n{\n  /// &lt;summary&gt;\n  /// Raised when another instance attempts to start up.\n  /// &lt;/summary&gt;\n  public static event StartupEventHandler OtherInstanceStarted;\n\n  /// &lt;summary&gt;\n  /// Checks to see if this instance is the first instance running on this machine.  If it is not, this method will\n  /// send the main instance this instance\'s startup information.\n  /// &lt;/summary&gt;\n  /// &lt;param name="guid"&gt;The application\'s unique identifier.&lt;/param&gt;\n  /// &lt;returns&gt;True if this instance is the main instance.&lt;/returns&gt;\n  public static bool VerifySingleInstace(Guid guid)\n  {\n    if (!AttemptPublishService(guid))\n    {\n      NotifyMainInstance(guid);\n\n      return false;\n    }\n\n    return true;\n  }\n\n  /// &lt;summary&gt;\n  /// Attempts to publish the service.\n  /// &lt;/summary&gt;\n  /// &lt;param name="guid"&gt;The application\'s unique identifier.&lt;/param&gt;\n  /// &lt;returns&gt;True if the service was published successfully.&lt;/returns&gt;\n  private static bool AttemptPublishService(Guid guid)\n  {\n    try\n    {\n      ServiceHost serviceHost = new ServiceHost(typeof(SingleInstance));\n      NetNamedPipeBinding binding = new NetNamedPipeBinding(NetNamedPipeSecurityMode.None);\n      serviceHost.AddServiceEndpoint(typeof(ISingleInstance), binding, CreateAddress(guid));\n      serviceHost.Open();\n\n      return true;\n    }\n    catch\n    {\n      return false;\n    }\n  }\n\n  /// &lt;summary&gt;\n  /// Notifies the main instance that this instance is attempting to start up.\n  /// &lt;/summary&gt;\n  /// &lt;param name="guid"&gt;The application\'s unique identifier.&lt;/param&gt;\n  private static void NotifyMainInstance(Guid guid)\n  {\n    NetNamedPipeBinding binding = new NetNamedPipeBinding(NetNamedPipeSecurityMode.None);\n    EndpointAddress remoteAddress = new EndpointAddress(CreateAddress(guid));\n    using (ChannelFactory&lt;ISingleInstance&gt; factory = new ChannelFactory&lt;ISingleInstance&gt;(binding, remoteAddress))\n    {\n      ISingleInstance singleInstance = factory.CreateChannel();\n      singleInstance.NotifyMainInstance(Environment.GetCommandLineArgs());\n    }\n  }\n\n  /// &lt;summary&gt;\n  /// Creates an address to publish/contact the service at based on a globally unique identifier.\n  /// &lt;/summary&gt;\n  /// &lt;param name="guid"&gt;The identifier for the application.&lt;/param&gt;\n  /// &lt;returns&gt;The address to publish/contact the service.&lt;/returns&gt;\n  private static string CreateAddress(Guid guid)\n  {\n    return string.Format(CultureInfo.CurrentCulture, "net.pipe://localhost/{0}", guid);\n  }\n\n  /// &lt;summary&gt;\n  /// The interface that describes the single instance service.\n  /// &lt;/summary&gt;\n  [ServiceContract]\n  private interface ISingleInstance\n  {\n    /// &lt;summary&gt;\n    /// Notifies the main instance that another instance of the application attempted to start.\n    /// &lt;/summary&gt;\n    /// &lt;param name="args"&gt;The other instance\'s command-line arguments.&lt;/param&gt;\n    [OperationContract]\n    void NotifyMainInstance(string[] args);\n  }\n\n  /// &lt;summary&gt;\n  /// The implementation of the single instance service interface.\n  /// &lt;/summary&gt;\n  private class SingleInstance : ISingleInstance\n  {\n    /// &lt;summary&gt;\n    /// Notifies the main instance that another instance of the application attempted to start.\n    /// &lt;/summary&gt;\n    /// &lt;param name="args"&gt;The other instance\'s command-line arguments.&lt;/param&gt;\n    public void NotifyMainInstance(string[] args)\n    {\n      if (OtherInstanceStarted != null)\n      {\n        Type type = typeof(StartupEventArgs);\n        ConstructorInfo constructor = type.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, Type.EmptyTypes, null);\n        StartupEventArgs e = (StartupEventArgs)constructor.Invoke(null);\n        FieldInfo argsField = type.GetField("_args", BindingFlags.Instance | BindingFlags.NonPublic);\n        Debug.Assert(argsField != null);\n        argsField.SetValue(e, args);\n\n        OtherInstanceStarted(null, e);\n      }\n    }\n  }\n}\n</code></pre>\n'}, {'answer_id': 16522305, 'author': 'Simon Mourier', 'author_id': 403671, 'author_profile': 'https://Stackoverflow.com/users/403671', 'pm_score': 4, 'selected': False, 'text': '<p>The code <a href="http://sanity-free.org/143/csharp_dotnet_single_instance_application.html" rel="noreferrer">C# .NET Single Instance Application</a> that is the reference for the marked answer is a great start.</p>\n\n<p>However, I found it doesn\'t handle very well the cases when the instance that already exist has a modal dialog open, whether that dialog is a managed one (like another Form such as an about box), or an unmanaged one (like the OpenFileDialog even when using the standard .NET class). With the original code, the main form is activated, but the modal one stays unactive, which looks strange, plus the user must click on it to keep using the app.</p>\n\n<p>So, I have create a SingleInstance utility class to handle all this quite automatically for Winforms and WPF applications.</p>\n\n<p><strong>Winforms</strong>:</p>\n\n<p>1) modify the Program class like this:</p>\n\n<pre><code>static class Program\n{\n    public static readonly SingleInstance Singleton = new SingleInstance(typeof(Program).FullName);\n\n    [STAThread]\n    static void Main(string[] args)\n    {\n        // NOTE: if this always return false, close &amp; restart Visual Studio\n        // this is probably due to the vshost.exe thing\n        Singleton.RunFirstInstance(() =&gt;\n        {\n            SingleInstanceMain(args);\n        });\n    }\n\n    public static void SingleInstanceMain(string[] args)\n    {\n        // standard code that was in Main now goes here\n        Application.EnableVisualStyles();\n        Application.SetCompatibleTextRenderingDefault(false);\n        Application.Run(new Form1());\n    }\n}\n</code></pre>\n\n<p>2) modify the main window class like this:</p>\n\n<pre><code>public partial class Form1 : Form\n{\n    public Form1()\n    {\n        InitializeComponent();\n    }\n\n    protected override void WndProc(ref Message m)\n    {\n        // if needed, the singleton will restore this window\n        Program.Singleton.OnWndProc(this, m, true);\n\n        // TODO: handle specific messages here if needed\n        base.WndProc(ref m);\n    }\n}\n</code></pre>\n\n<p><strong>WPF:</strong></p>\n\n<p>1) modify the App page like this (and make sure you set its build action to page to be able to redefine the Main method):</p>\n\n<pre><code>public partial class App : Application\n{\n    public static readonly SingleInstance Singleton = new SingleInstance(typeof(App).FullName);\n\n    [STAThread]\n    public static void Main(string[] args)\n    {\n        // NOTE: if this always return false, close &amp; restart Visual Studio\n        // this is probably due to the vshost.exe thing\n        Singleton.RunFirstInstance(() =&gt;\n        {\n            SingleInstanceMain(args);\n        });\n    }\n\n    public static void SingleInstanceMain(string[] args)\n    {\n        // standard code that was in Main now goes here\n        App app = new App();\n        app.InitializeComponent();\n        app.Run();\n    }\n}\n</code></pre>\n\n<p>2) modify the main window class like this:</p>\n\n<pre><code>public partial class MainWindow : Window\n{\n    private HwndSource _source;\n\n    public MainWindow()\n    {\n        InitializeComponent();\n    }\n\n    protected override void OnSourceInitialized(EventArgs e)\n    {\n        base.OnSourceInitialized(e);\n        _source = (HwndSource)PresentationSource.FromVisual(this);\n        _source.AddHook(HwndSourceHook);\n    }\n\n    protected virtual IntPtr HwndSourceHook(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)\n    {\n        // if needed, the singleton will restore this window\n        App.Singleton.OnWndProc(hwnd, msg, wParam, lParam, true, true);\n\n        // TODO: handle other specific message\n        return IntPtr.Zero;\n    }\n</code></pre>\n\n<p>And here is the utility class:</p>\n\n<pre><code>using System;\nusing System.ComponentModel;\nusing System.Runtime.InteropServices;\nusing System.Threading;\n\nnamespace SingleInstanceUtilities\n{\n    public sealed class SingleInstance\n    {\n        private const int HWND_BROADCAST = 0xFFFF;\n\n        [DllImport("user32.dll")]\n        private static extern bool PostMessage(IntPtr hwnd, int msg, IntPtr wparam, IntPtr lparam);\n\n        [DllImport("user32.dll", CharSet = CharSet.Unicode)]\n        private static extern int RegisterWindowMessage(string message);\n\n        [DllImport("user32.dll")]\n        private static extern bool SetForegroundWindow(IntPtr hWnd);\n\n        public SingleInstance(string uniqueName)\n        {\n            if (uniqueName == null)\n                throw new ArgumentNullException("uniqueName");\n\n            Mutex = new Mutex(true, uniqueName);\n            Message = RegisterWindowMessage("WM_" + uniqueName);\n        }\n\n        public Mutex Mutex { get; private set; }\n        public int Message { get; private set; }\n\n        public void RunFirstInstance(Action action)\n        {\n            RunFirstInstance(action, IntPtr.Zero, IntPtr.Zero);\n        }\n\n        // NOTE: if this always return false, close &amp; restart Visual Studio\n        // this is probably due to the vshost.exe thing\n        public void RunFirstInstance(Action action, IntPtr wParam, IntPtr lParam)\n        {\n            if (action == null)\n                throw new ArgumentNullException("action");\n\n            if (WaitForMutext(wParam, lParam))\n            {\n                try\n                {\n                    action();\n                }\n                finally\n                {\n                    ReleaseMutex();\n                }\n            }\n        }\n\n        public static void ActivateWindow(IntPtr hwnd)\n        {\n            if (hwnd == IntPtr.Zero)\n                return;\n\n            FormUtilities.ActivateWindow(FormUtilities.GetModalWindow(hwnd));\n        }\n\n        public void OnWndProc(IntPtr hwnd, int m, IntPtr wParam, IntPtr lParam, bool restorePlacement, bool activate)\n        {\n            if (m == Message)\n            {\n                if (restorePlacement)\n                {\n                    WindowPlacement placement = WindowPlacement.GetPlacement(hwnd, false);\n                    if (placement.IsValid &amp;&amp; placement.IsMinimized)\n                    {\n                        const int SW_SHOWNORMAL = 1;\n                        placement.ShowCmd = SW_SHOWNORMAL;\n                        placement.SetPlacement(hwnd);\n                    }\n                }\n\n                if (activate)\n                {\n                    SetForegroundWindow(hwnd);\n                    FormUtilities.ActivateWindow(FormUtilities.GetModalWindow(hwnd));\n                }\n            }\n        }\n\n#if WINFORMS // define this for Winforms apps\n        public void OnWndProc(System.Windows.Forms.Form form, int m, IntPtr wParam, IntPtr lParam, bool activate)\n        {\n            if (form == null)\n                throw new ArgumentNullException("form");\n\n            if (m == Message)\n            {\n                if (activate)\n                {\n                    if (form.WindowState == System.Windows.Forms.FormWindowState.Minimized)\n                    {\n                        form.WindowState = System.Windows.Forms.FormWindowState.Normal;\n                    }\n\n                    form.Activate();\n                    FormUtilities.ActivateWindow(FormUtilities.GetModalWindow(form.Handle));\n                }\n            }\n        }\n\n        public void OnWndProc(System.Windows.Forms.Form form, System.Windows.Forms.Message m, bool activate)\n        {\n            if (form == null)\n                throw new ArgumentNullException("form");\n\n            OnWndProc(form, m.Msg, m.WParam, m.LParam, activate);\n        }\n#endif\n\n        public void ReleaseMutex()\n        {\n            Mutex.ReleaseMutex();\n        }\n\n        public bool WaitForMutext(bool force, IntPtr wParam, IntPtr lParam)\n        {\n            bool b = PrivateWaitForMutext(force);\n            if (!b)\n            {\n                PostMessage((IntPtr)HWND_BROADCAST, Message, wParam, lParam);\n            }\n            return b;\n        }\n\n        public bool WaitForMutext(IntPtr wParam, IntPtr lParam)\n        {\n            return WaitForMutext(false, wParam, lParam);\n        }\n\n        private bool PrivateWaitForMutext(bool force)\n        {\n            if (force)\n                return true;\n\n            try\n            {\n                return Mutex.WaitOne(TimeSpan.Zero, true);\n            }\n            catch (AbandonedMutexException)\n            {\n                return true;\n            }\n        }\n    }\n\n    // NOTE: don\'t add any field or public get/set property, as this must exactly map to Windows\' WINDOWPLACEMENT structure\n    [StructLayout(LayoutKind.Sequential)]\n    public struct WindowPlacement\n    {\n        public int Length { get; set; }\n        public int Flags { get; set; }\n        public int ShowCmd { get; set; }\n        public int MinPositionX { get; set; }\n        public int MinPositionY { get; set; }\n        public int MaxPositionX { get; set; }\n        public int MaxPositionY { get; set; }\n        public int NormalPositionLeft { get; set; }\n        public int NormalPositionTop { get; set; }\n        public int NormalPositionRight { get; set; }\n        public int NormalPositionBottom { get; set; }\n\n        [DllImport("user32.dll", SetLastError = true)]\n        private static extern bool SetWindowPlacement(IntPtr hWnd, ref WindowPlacement lpwndpl);\n\n        [DllImport("user32.dll", SetLastError = true)]\n        private static extern bool GetWindowPlacement(IntPtr hWnd, ref WindowPlacement lpwndpl);\n\n        private const int SW_SHOWMINIMIZED = 2;\n\n        public bool IsMinimized\n        {\n            get\n            {\n                return ShowCmd == SW_SHOWMINIMIZED;\n            }\n        }\n\n        public bool IsValid\n        {\n            get\n            {\n                return Length == Marshal.SizeOf(typeof(WindowPlacement));\n            }\n        }\n\n        public void SetPlacement(IntPtr windowHandle)\n        {\n            SetWindowPlacement(windowHandle, ref this);\n        }\n\n        public static WindowPlacement GetPlacement(IntPtr windowHandle, bool throwOnError)\n        {\n            WindowPlacement placement = new WindowPlacement();\n            if (windowHandle == IntPtr.Zero)\n                return placement;\n\n            placement.Length = Marshal.SizeOf(typeof(WindowPlacement));\n            if (!GetWindowPlacement(windowHandle, ref placement))\n            {\n                if (throwOnError)\n                    throw new Win32Exception(Marshal.GetLastWin32Error());\n\n                return new WindowPlacement();\n            }\n            return placement;\n        }\n    }\n\n    public static class FormUtilities\n    {\n        [DllImport("user32.dll")]\n        private static extern IntPtr GetWindow(IntPtr hWnd, int uCmd);\n\n        [DllImport("user32.dll", SetLastError = true)]\n        private static extern IntPtr SetActiveWindow(IntPtr hWnd);\n\n        [DllImport("user32.dll")]\n        private static extern bool IsWindowVisible(IntPtr hWnd);\n\n        [DllImport("kernel32.dll")]\n        public static extern int GetCurrentThreadId();\n\n        private delegate bool EnumChildrenCallback(IntPtr hwnd, IntPtr lParam);\n\n        [DllImport("user32.dll")]\n        private static extern bool EnumThreadWindows(int dwThreadId, EnumChildrenCallback lpEnumFunc, IntPtr lParam);\n\n        private class ModalWindowUtil\n        {\n            private const int GW_OWNER = 4;\n            private int _maxOwnershipLevel;\n            private IntPtr _maxOwnershipHandle;\n\n            private bool EnumChildren(IntPtr hwnd, IntPtr lParam)\n            {\n                int level = 1;\n                if (IsWindowVisible(hwnd) &amp;&amp; IsOwned(lParam, hwnd, ref level))\n                {\n                    if (level &gt; _maxOwnershipLevel)\n                    {\n                        _maxOwnershipHandle = hwnd;\n                        _maxOwnershipLevel = level;\n                    }\n                }\n                return true;\n            }\n\n            private static bool IsOwned(IntPtr owner, IntPtr hwnd, ref int level)\n            {\n                IntPtr o = GetWindow(hwnd, GW_OWNER);\n                if (o == IntPtr.Zero)\n                    return false;\n\n                if (o == owner)\n                    return true;\n\n                level++;\n                return IsOwned(owner, o, ref level);\n            }\n\n            public static void ActivateWindow(IntPtr hwnd)\n            {\n                if (hwnd != IntPtr.Zero)\n                {\n                    SetActiveWindow(hwnd);\n                }\n            }\n\n            public static IntPtr GetModalWindow(IntPtr owner)\n            {\n                ModalWindowUtil util = new ModalWindowUtil();\n                EnumThreadWindows(GetCurrentThreadId(), util.EnumChildren, owner);\n                return util._maxOwnershipHandle; // may be IntPtr.Zero\n            }\n        }\n\n        public static void ActivateWindow(IntPtr hwnd)\n        {\n            ModalWindowUtil.ActivateWindow(hwnd);\n        }\n\n        public static IntPtr GetModalWindow(IntPtr owner)\n        {\n            return ModalWindowUtil.GetModalWindow(owner);\n        }\n    }\n}\n</code></pre>\n'}, {'answer_id': 19470753, 'author': 'Cornel Marian', 'author_id': 736113, 'author_profile': 'https://Stackoverflow.com/users/736113', 'pm_score': 1, 'selected': False, 'text': '<p>Use mutex solution:</p>\n\n<pre><code>using System;\nusing System.Windows.Forms;\nusing System.Threading;\n\nnamespace OneAndOnlyOne\n{\nstatic class Program\n{\n    static String _mutexID = " // generate guid"\n    /// &lt;summary&gt;\n    /// The main entry point for the application.\n    /// &lt;/summary&gt;\n    [STAThread]\n    static void Main()\n    {\n        Application.EnableVisualStyles();\n        Application.SetCompatibleTextRenderingDefault(false);\n\n        Boolean _isNotRunning;\n        using (Mutex _mutex = new Mutex(true, _mutexID, out _isNotRunning))\n        {\n            if (_isNotRunning)\n            {\n                Application.Run(new Form1());\n            }\n            else\n            {\n                MessageBox.Show("An instance is already running.");\n                return;\n            }\n        }\n    }\n}\n}\n</code></pre>\n'}, {'answer_id': 20278491, 'author': 'Jason Lim', 'author_id': 1973634, 'author_profile': 'https://Stackoverflow.com/users/1973634', 'pm_score': 1, 'selected': False, 'text': '<p>Here\'s a lightweight solution I use which allows the application to bring an already existing window to the foreground without resorting to custom windows messages or blindly searching process names.</p>\n\n<pre><code>[DllImport("user32.dll")]\nstatic extern bool SetForegroundWindow(IntPtr hWnd);\n\nstatic readonly string guid = "&lt;Application Guid&gt;";\n\nstatic void Main()\n{\n    Mutex mutex = null;\n    if (!CreateMutex(out mutex))\n        return;\n\n    // Application startup code.\n\n    Environment.SetEnvironmentVariable(guid, null, EnvironmentVariableTarget.User);\n}\n\nstatic bool CreateMutex(out Mutex mutex)\n{\n    bool createdNew = false;\n    mutex = new Mutex(false, guid, out createdNew);\n\n    if (createdNew)\n    {\n        Process process = Process.GetCurrentProcess();\n        string value = process.Id.ToString();\n\n        Environment.SetEnvironmentVariable(guid, value, EnvironmentVariableTarget.User);\n    }\n    else\n    {\n        string value = Environment.GetEnvironmentVariable(guid, EnvironmentVariableTarget.User);\n        Process process = null;\n        int processId = -1;\n\n        if (int.TryParse(value, out processId))\n            process = Process.GetProcessById(processId);\n\n        if (process == null || !SetForegroundWindow(process.MainWindowHandle))\n            MessageBox.Show("Unable to start application. An instance of this application is already running.");\n    }\n\n    return createdNew;\n}\n</code></pre>\n\n<p>Edit: You can also store and initialize mutex and createdNew statically, but you\'ll need to explicitly dispose/release the mutex once you\'re done with it. Personally, I prefer keeping the mutex local as it will be automatically disposed of even if the application closes without ever reaching the end of Main.</p>\n'}, {'answer_id': 20412588, 'author': 'Eric Ouellet', 'author_id': 452845, 'author_profile': 'https://Stackoverflow.com/users/452845', 'pm_score': 2, 'selected': False, 'text': '<p><strong>Update 2017-01-25.</strong> After trying few things, I decided to go with VisualBasic.dll it is easier and works better (at least for me). I let my previous answer just as reference...</p>\n\n<p>Just as reference, this is how I did without passing arguments (which I can\'t find any reason to do so... I mean a single app with arguments that as to be passed out from one instance to another one).\nIf file association is required, then an app should (per users standard expectation) be instanciated for each doc. If you have to pass args to existing app, I  think I would used vb dll.</p>\n\n<p>Not passing args (just single instance app), I prefer not registering a new Window message and not override the message loop as defined in Matt Davis Solution. Although it\'s not a big deal to add a VisualBasic dll, but I prefer not add a new reference just to do single instance app. Also, I do prefer instanciate a new class with Main instead of calling Shutdown from App.Startup override to ensure to exit as soon as possible.</p>\n\n<p>In hope that anybody will like it... or will inspire a little bit :-) </p>\n\n<p>Project startup class should be set as \'SingleInstanceApp\'.</p>\n\n<pre><code>public class SingleInstanceApp\n{\n    [STAThread]\n    public static void Main(string[] args)\n    {\n        Mutex _mutexSingleInstance = new Mutex(true, "MonitorMeSingleInstance");\n\n        if (_mutexSingleInstance.WaitOne(TimeSpan.Zero, true))\n        {\n            try\n            {\n                var app = new App();\n                app.InitializeComponent();\n                app.Run();\n\n            }\n            finally\n            {\n                _mutexSingleInstance.ReleaseMutex();\n                _mutexSingleInstance.Close();\n            }\n        }\n        else\n        {\n            MessageBox.Show("One instance is already running.");\n\n            var processes = Process.GetProcessesByName(Assembly.GetEntryAssembly().GetName().Name);\n            {\n                if (processes.Length &gt; 1)\n                {\n                    foreach (var process in processes)\n                    {\n                        if (process.Id != Process.GetCurrentProcess().Id)\n                        {\n                            WindowHelper.SetForegroundWindow(process.MainWindowHandle);\n                        }\n                    }\n                }\n            }\n        }\n    }\n}\n</code></pre>\n\n<p>WindowHelper:</p>\n\n<pre><code>using System;\nusing System.Runtime.InteropServices;\nusing System.Windows;\nusing System.Windows.Interop;\nusing System.Windows.Threading;\n\nnamespace HQ.Util.Unmanaged\n{\n    public class WindowHelper\n    {\n        [DllImport("user32.dll")]\n        [return: MarshalAs(UnmanagedType.Bool)]\n        public static extern bool SetForegroundWindow(IntPtr hWnd);\n</code></pre>\n'}, {'answer_id': 25844191, 'author': 'Antoine Diekmann', 'author_id': 1955485, 'author_profile': 'https://Stackoverflow.com/users/1955485', 'pm_score': 0, 'selected': False, 'text': '<p>You can also use the <a href="http://www.softfluent.com/products/codefluent-runtime-client" rel="nofollow">CodeFluent Runtime</a> which is free set of tools. It provides a <a href="http://blog.codefluententities.com/2014/09/10/single-instance-application-in-net/" rel="nofollow">SingleInstance</a> class to implement a single instance application.</p>\n'}, {'answer_id': 28146800, 'author': 'Martin Bech', 'author_id': 1677634, 'author_profile': 'https://Stackoverflow.com/users/1677634', 'pm_score': 2, 'selected': False, 'text': '<p>I added a sendMessage Method to the NativeMethods Class.</p>\n\n<p>Apparently the postmessage method dosent work, if the application is not show in the taskbar, however using the sendmessage method solves this.</p>\n\n<pre><code>class NativeMethods\n{\n    public const int HWND_BROADCAST = 0xffff;\n    public static readonly int WM_SHOWME = RegisterWindowMessage("WM_SHOWME");\n    [DllImport("user32")]\n    public static extern bool PostMessage(IntPtr hwnd, int msg, IntPtr wparam, IntPtr lparam);\n    [DllImport("user32.dll", CharSet = CharSet.Auto)]\n    public static extern IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);\n    [DllImport("user32")]\n    public static extern int RegisterWindowMessage(string message);\n}\n</code></pre>\n'}, {'answer_id': 38212569, 'author': 'Code Scratcher', 'author_id': 4342676, 'author_profile': 'https://Stackoverflow.com/users/4342676', 'pm_score': 0, 'selected': False, 'text': '<p>Here is a solution:</p>\n\n<pre><code>Protected Overrides Sub OnStartup(e As StartupEventArgs)\n    Const appName As String = "TestApp"\n    Dim createdNew As Boolean\n    _mutex = New Mutex(True, appName, createdNew)\n    If Not createdNew Then\n        \'app is already running! Exiting the application\n        MessageBox.Show("Application is already running.")\n        Application.Current.Shutdown()\n    End If\n    MyBase.OnStartup(e)\nEnd Sub\n</code></pre>\n'}, {'answer_id': 38306338, 'author': 'Siarhei Kuchuk', 'author_id': 212746, 'author_profile': 'https://Stackoverflow.com/users/212746', 'pm_score': 1, 'selected': False, 'text': '<p>Here\'s the same thing implemented via Event.</p>\n\n<pre><code>public enum ApplicationSingleInstanceMode\n{\n    CurrentUserSession,\n    AllSessionsOfCurrentUser,\n    Pc\n}\n\npublic class ApplicationSingleInstancePerUser: IDisposable\n{\n    private readonly EventWaitHandle _event;\n\n    /// &lt;summary&gt;\n    /// Shows if the current instance of ghost is the first\n    /// &lt;/summary&gt;\n    public bool FirstInstance { get; private set; }\n\n    /// &lt;summary&gt;\n    /// Initializes \n    /// &lt;/summary&gt;\n    /// &lt;param name="applicationName"&gt;The application name&lt;/param&gt;\n    /// &lt;param name="mode"&gt;The single mode&lt;/param&gt;\n    public ApplicationSingleInstancePerUser(string applicationName, ApplicationSingleInstanceMode mode = ApplicationSingleInstanceMode.CurrentUserSession)\n    {\n        string name;\n        if (mode == ApplicationSingleInstanceMode.CurrentUserSession)\n            name = $"Local\\\\{applicationName}";\n        else if (mode == ApplicationSingleInstanceMode.AllSessionsOfCurrentUser)\n            name = $"Global\\\\{applicationName}{Environment.UserDomainName}";\n        else\n            name = $"Global\\\\{applicationName}";\n\n        try\n        {\n            bool created;\n            _event = new EventWaitHandle(false, EventResetMode.ManualReset, name, out created);\n            FirstInstance = created;\n        }\n        catch\n        {\n        }\n    }\n\n    public void Dispose()\n    {\n        _event.Dispose();\n    }\n}\n</code></pre>\n'}, {'answer_id': 38853721, 'author': 'pStan', 'author_id': 1221380, 'author_profile': 'https://Stackoverflow.com/users/1221380', 'pm_score': 1, 'selected': False, 'text': '<p>This is how I ended up taking care of this issue.  Note that debug code is still in there for testing.  This code is within the OnStartup in the App.xaml.cs file.  (WPF)  </p>\n\n<pre><code>        // Process already running ? \n        if (Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName).Length &gt; 1)\n        {\n\n            // Show your error message\n            MessageBox.Show("xxx is already running.  \\r\\n\\r\\nIf the original process is hung up you may need to restart your computer, or kill the current xxx process using the task manager.", "xxx is already running!", MessageBoxButton.OK, MessageBoxImage.Exclamation);\n\n            // This process \n            Process currentProcess = Process.GetCurrentProcess();\n\n            // Get all processes running on the local computer.\n            Process[] localAll = Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName);\n\n            // ID of this process... \n            int temp = currentProcess.Id;\n            MessageBox.Show("This Process ID:  " + temp.ToString());\n\n            for (int i = 0; i &lt; localAll.Length; i++)\n            {\n                // Find the other process \n                if (localAll[i].Id != currentProcess.Id)\n                {\n                    MessageBox.Show("Original Process ID (Switching to):  " + localAll[i].Id.ToString());\n\n                    // Switch to it... \n                    SetForegroundWindow(localAll[i].MainWindowHandle);\n\n                }\n            }\n\n            Application.Current.Shutdown();\n\n        }\n</code></pre>\n\n<p>This may have issues that I have not caught yet.  If I run into any I\'ll update my answer.      </p>\n'}, {'answer_id': 39160390, 'author': 'kakopappa', 'author_id': 192901, 'author_profile': 'https://Stackoverflow.com/users/192901', 'pm_score': 0, 'selected': False, 'text': '<p>Here is my 2 cents</p>\n\n<pre><code> static class Program\n    {\n        [STAThread]\n        static void Main()\n        {\n            bool createdNew;\n            using (new Mutex(true, "MyApp", out createdNew))\n            {\n                if (createdNew) {\n                    Application.EnableVisualStyles();\n                    Application.SetCompatibleTextRenderingDefault(false);\n                    var mainClass = new SynGesturesLogic();\n                    Application.ApplicationExit += mainClass.tray_exit;\n                    Application.Run();\n                }\n                else\n                {\n                    var current = Process.GetCurrentProcess();\n                    foreach (var process in Process.GetProcessesByName(current.ProcessName).Where(process =&gt; process.Id != current.Id))\n                    {\n                        NativeMethods.SetForegroundWindow(process.MainWindowHandle);\n                        break;\n                    }\n                }\n            }\n        }\n    }\n</code></pre>\n'}, {'answer_id': 39775932, 'author': 'Pete', 'author_id': 2833784, 'author_profile': 'https://Stackoverflow.com/users/2833784', 'pm_score': 0, 'selected': False, 'text': '<p>I like a solution to allow multiple Instances, if the exe is called from an other path. I modified CharithJ solution Method 1:</p>\n\n<pre><code>   static class Program {\n    [DllImport("user32.dll")]\n    private static extern bool ShowWindow(IntPtr hWnd, Int32 nCmdShow);\n    [DllImport("User32.dll")]\n    public static extern Int32 SetForegroundWindow(IntPtr hWnd);\n    [STAThread]\n    static void Main() {\n        Process currentProcess = Process.GetCurrentProcess();\n        foreach (var process in Process.GetProcesses()) {\n            try {\n                if ((process.Id != currentProcess.Id) &amp;&amp; \n                    (process.ProcessName == currentProcess.ProcessName) &amp;&amp;\n                    (process.MainModule.FileName == currentProcess.MainModule.FileName)) {\n                    ShowWindow(process.MainWindowHandle, 5); // const int SW_SHOW = 5; //Activates the window and displays it in its current size and position. \n                    SetForegroundWindow(process.MainWindowHandle);\n                    return;\n                }\n            } catch (Exception ex) {\n                //ignore Exception "Access denied "\n            }\n        }\n\n        Application.EnableVisualStyles();\n        Application.SetCompatibleTextRenderingDefault(false);\n        Application.Run(new Form1());\n    }\n}\n</code></pre>\n'}, {'answer_id': 41390636, 'author': 'newbieguy', 'author_id': 4477797, 'author_profile': 'https://Stackoverflow.com/users/4477797', 'pm_score': 2, 'selected': False, 'text': '<p>Not using Mutex though, simple answer:</p>\n\n<pre><code>System.Diagnostics;    \n...\nstring thisprocessname = Process.GetCurrentProcess().ProcessName;\n\nif (Process.GetProcesses().Count(p =&gt; p.ProcessName == thisprocessname) &gt; 1)\n                return;\n</code></pre>\n\n<p>Put it inside the <code>Program.Main()</code>.<br>\n<strong>Example</strong>:</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing System.Windows.Forms;\nusing System.Diagnostics;\n\nnamespace Sample\n{\n    static class Program\n    {\n        /// &lt;summary&gt;\n        /// The main entry point for the application.\n        /// &lt;/summary&gt;\n        [STAThread]\n        static void Main()\n        {\n            //simple add Diagnostics namespace, and these 3 lines below \n            string thisprocessname = Process.GetCurrentProcess().ProcessName;\n            if (Process.GetProcesses().Count(p =&gt; p.ProcessName == thisprocessname) &gt; 1)\n                return;\n\n            Application.EnableVisualStyles();\n            Application.SetCompatibleTextRenderingDefault(false);\n            Application.Run(new Sample());\n        }\n    }\n}\n</code></pre>\n\n<p>You can add <code>MessageBox.Show</code> to the <code>if</code>-statement and put "Application already running".<br>\nThis might be helpful to someone.</p>\n'}, {'answer_id': 41599502, 'author': 'Divins Mathew', 'author_id': 3201403, 'author_profile': 'https://Stackoverflow.com/users/3201403', 'pm_score': 0, 'selected': False, 'text': '<p>Simply using a <code>StreamWriter</code>, how about this?</p>\n\n<pre><code>System.IO.File.StreamWriter OpenFlag = null;   //globally\n</code></pre>\n\n<p>and</p>\n\n<pre><code>try\n{\n    OpenFlag = new StreamWriter(Path.GetTempPath() + "OpenedIfRunning");\n}\ncatch (System.IO.IOException) //file in use\n{\n    Environment.Exit(0);\n}\n</code></pre>\n'}, {'answer_id': 45778772, 'author': 'A.T.', 'author_id': 2734629, 'author_profile': 'https://Stackoverflow.com/users/2734629', 'pm_score': 2, 'selected': False, 'text': '<p>Named-mutex-based approaches are not cross-platform because named mutexes are not global in Mono. Process-enumeration-based approaches don\'t have any synchronization and may result in incorrect behavior (e.g. multiple processes started at the same time may all self-terminate depending on timing). Windowing-system-based approaches are not desirable in a console application. This solution, built on top of Divin\'s answer, addresses all these issues:</p>\n\n<pre><code>using System;\nusing System.IO;\n\nnamespace TestCs\n{\n    public class Program\n    {\n        // The app id must be unique. Generate a new guid for your application. \n        public static string AppId = "01234567-89ab-cdef-0123-456789abcdef";\n\n        // The stream is stored globally to ensure that it won\'t be disposed before the application terminates.\n        public static FileStream UniqueInstanceStream;\n\n        public static int Main(string[] args)\n        {\n            EnsureUniqueInstance();\n\n            // Your code here.\n\n            return 0;\n        }\n\n        private static void EnsureUniqueInstance()\n        {\n            // Note: If you want the check to be per-user, use Environment.SpecialFolder.ApplicationData instead.\n            string lockDir = Path.Combine(\n                Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData),\n                "UniqueInstanceApps");\n            string lockPath = Path.Combine(lockDir, $"{AppId}.unique");\n\n            Directory.CreateDirectory(lockDir);\n\n            try\n            {\n                // Create the file with exclusive write access. If this fails, then another process is executing.\n                UniqueInstanceStream = File.Open(lockPath, FileMode.Create, FileAccess.Write, FileShare.None);\n\n                // Although only the line above should be sufficient, when debugging with a vshost on Visual Studio\n                // (that acts as a proxy), the IO exception isn\'t passed to the application before a Write is executed.\n                UniqueInstanceStream.Write(new byte[] { 0 }, 0, 1);\n                UniqueInstanceStream.Flush();\n            }\n            catch\n            {\n                throw new Exception("Another instance of the application is already running.");\n            }\n        }\n    }\n}\n</code></pre>\n'}, {'answer_id': 47849014, 'author': 'Legends', 'author_id': 2581562, 'author_profile': 'https://Stackoverflow.com/users/2581562', 'pm_score': 2, 'selected': False, 'text': '<p><strong>[I have provided sample code for console and wpf applications below.]</strong></p>\n\n<p>You only have to check the value of the <code>createdNew</code> variable (example below!), after you create the named Mutex instance.</p>\n\n<p>The boolean <code>createdNew</code> will return <strong>false:</strong></p>\n\n<blockquote>\n  <p>if the Mutex instance named "YourApplicationNameHere" was already\n  created on the system somewhere </p>\n</blockquote>\n\n<p>The boolean <code>createdNew</code> will return <strong>true:</strong></p>\n\n<blockquote>\n  <p>if this is the first Mutex named "YourApplicationNameHere" on the\n  system.</p>\n</blockquote>\n\n<p><hr>\n<strong>Console application - Example:</strong></p>\n\n<pre><code>static Mutex m = null;\n\nstatic void Main(string[] args)\n{\n    const string mutexName = "YourApplicationNameHere";\n    bool createdNew = false;\n\n    try\n    {\n        // Initializes a new instance of the Mutex class with a Boolean value that indicates \n        // whether the calling thread should have initial ownership of the mutex, a string that is the name of the mutex, \n        // and a Boolean value that, when the method returns, indicates whether the calling thread was granted initial ownership of the mutex.\n\n        using (m = new Mutex(true, mutexName, out createdNew))\n        {\n            if (!createdNew)\n            {\n                Console.WriteLine("instance is alreday running... shutting down !!!");\n                Console.Read();\n                return; // Exit the application\n            }\n\n            // Run your windows forms app here\n            Console.WriteLine("Single instance app is running!");\n            Console.ReadLine();\n        }\n\n\n    }\n    catch (Exception ex)\n    {\n\n        Console.WriteLine(ex.Message);\n        Console.ReadLine();\n    }\n}\n</code></pre>\n\n<p><strong>WPF-Example:</strong></p>\n\n<pre><code>public partial class App : Application\n{\nstatic Mutex m = null;\n\nprotected override void OnStartup(StartupEventArgs e)\n{\n\n    const string mutexName = "YourApplicationNameHere";\n    bool createdNew = false;\n\n    try\n    {\n        // Initializes a new instance of the Mutex class with a Boolean value that indicates \n        // whether the calling thread should have initial ownership of the mutex, a string that is the name of the mutex, \n        // and a Boolean value that, when the method returns, indicates whether the calling thread was granted initial ownership of the mutex.\n\n        m = new Mutex(true, mutexName, out createdNew);\n\n        if (!createdNew)\n        {\n            Current.Shutdown(); // Exit the application\n        }\n\n    }\n    catch (Exception)\n    {\n        throw;\n    }\n\n    base.OnStartup(e);\n}\n\n\nprotected override void OnExit(ExitEventArgs e)\n{\n    if (m != null)\n    {\n        m.Dispose();\n    }\n    base.OnExit(e);\n}\n}\n</code></pre>\n'}, {'answer_id': 48657296, 'author': 'A.J.Bauer', 'author_id': 1278334, 'author_profile': 'https://Stackoverflow.com/users/1278334', 'pm_score': 1, 'selected': False, 'text': '<p>A time saving solution for C# Winforms...</p>\n\n<p>Program.cs:</p>\n\n<pre><code>using System;\nusing System.Windows.Forms;\n// needs reference to Microsoft.VisualBasic\nusing Microsoft.VisualBasic.ApplicationServices;  \n\nnamespace YourNamespace\n{\n    public class SingleInstanceController : WindowsFormsApplicationBase\n    {\n        public SingleInstanceController()\n        {\n            this.IsSingleInstance = true;\n        }\n\n        protected override void OnStartupNextInstance(StartupNextInstanceEventArgs e)\n        {\n            e.BringToForeground = true;\n            base.OnStartupNextInstance(e);\n        }\n\n        protected override void OnCreateMainForm()\n        {\n            this.MainForm = new Form1();\n        }\n    }\n\n    static class Program\n    {\n        [STAThread]\n        static void Main()\n        {\n            Application.EnableVisualStyles();\n            Application.SetCompatibleTextRenderingDefault(false);\n            string[] args = Environment.GetCommandLineArgs();\n            SingleInstanceController controller = new SingleInstanceController();\n            controller.Run(args);\n        }\n    }\n}\n</code></pre>\n'}, {'answer_id': 49796895, 'author': 'Deniz', 'author_id': 9569602, 'author_profile': 'https://Stackoverflow.com/users/9569602', 'pm_score': 2, 'selected': False, 'text': '<p>I can\'t find a <strong>short solution</strong> here so I hope someone will like this:</p>\n\n<p><strong>UPDATED 2018-09-20</strong></p>\n\n<p>Put this code in your <code>Program.cs</code>:</p>\n\n<pre><code>using System.Diagnostics;\n\nstatic void Main()\n{\n    Process thisProcess = Process.GetCurrentProcess();\n    Process[] allProcesses = Process.GetProcessesByName(thisProcess.ProcessName);\n    if (allProcesses.Length &gt; 1)\n    {\n        // Don\'t put a MessageBox in here because the user could spam this MessageBox.\n        return;\n    }\n\n    // Optional code. If you don\'t want that someone runs your ".exe" with a different name:\n\n    string exeName = AppDomain.CurrentDomain.FriendlyName;\n    // in debug mode, don\'t forget that you don\'t use your normal .exe name.\n    // Debug uses the .vshost.exe.\n    if (exeName != "the name of your executable.exe") \n    {\n        // You can add a MessageBox here if you want.\n        // To point out to users that the name got changed and maybe what the name should be or something like that^^ \n        MessageBox.Show("The executable name should be \\"the name of your executable.exe\\"", \n            "Wrong executable name", MessageBoxButtons.OK, MessageBoxIcon.Error);\n        return;\n    }\n\n    // Following code is default code:\n    Application.EnableVisualStyles();\n    Application.SetCompatibleTextRenderingDefault(false);\n    Application.Run(new MainForm());\n}\n</code></pre>\n'}, {'answer_id': 57140889, 'author': 'Vishnu Babu', 'author_id': 5342284, 'author_profile': 'https://Stackoverflow.com/users/5342284', 'pm_score': 2, 'selected': False, 'text': '<p>I use <a href="https://learn.microsoft.com/en-us/dotnet/api/system.threading.mutex?view=netframework-4.8" rel="nofollow noreferrer">Mutex</a> in my solution for preventing multiple instances.</p>\n\n<pre><code>static Mutex mutex = null;\n//A string that is the name of the mutex\nstring mutexName = @"Global\\test";\n//Prevent Multiple Instances of Application\nbool onlyInstance = false;\nmutex = new Mutex(true, mutexName, out onlyInstance);\n\nif (!onlyInstance)\n{\n  MessageBox.Show("You are already running this application in your system.", "Already Running..", MessageBoxButton.OK);\n  Application.Current.Shutdown();\n}\n</code></pre>\n'}, {'answer_id': 59851185, 'author': 'Alexandru Dicu', 'author_id': 1140388, 'author_profile': 'https://Stackoverflow.com/users/1140388', 'pm_score': 1, 'selected': False, 'text': '<p>Please check the proposed solution from <a href="https://stackoverflow.com/questions/59706160/c-sharp-dot-net-core-single-instance-app-passing-parameters-to-first-instance">here</a> that uses a semaphore to determine if an existing instance is already running, works for a WPF application and can pass arguments from second instance to the first already running instance by using a TcpListener and a TcpClient:</p>\n\n<p>It works also for .NET Core, not only for .NET Framework.</p>\n'}, {'answer_id': 62712773, 'author': 'std8590', 'author_id': 13319821, 'author_profile': 'https://Stackoverflow.com/users/13319821', 'pm_score': 0, 'selected': False, 'text': '<p>My favourite solution is from MVP Daniel Vaughan:\n<a href="http://danielvaughan.org/posts/.net/wpf/2010/08/01/Enforcing-Single-Instance-WPF-Applications/" rel="nofollow noreferrer">Enforcing Single Instance Wpf Applications</a></p>\n<p>It use MemoryMappedFile to send command line arguments to the first instance:</p>\n<pre><code>/// &lt;summary&gt;\n/// This class allows restricting the number of executables in execution, to one.\n/// &lt;/summary&gt;\npublic sealed class SingletonApplicationEnforcer\n{\n    readonly Action&lt;IEnumerable&lt;string&gt;&gt; processArgsFunc;\n    readonly string applicationId;\n    Thread thread;\n    string argDelimiter = &quot;_;;_&quot;;\n\n    /// &lt;summary&gt;\n    /// Gets or sets the string that is used to join \n    /// the string array of arguments in memory.\n    /// &lt;/summary&gt;\n    /// &lt;value&gt;The arg delimeter.&lt;/value&gt;\n    public string ArgDelimeter\n    {\n        get\n        {\n            return argDelimiter;\n        }\n        set\n        {\n            argDelimiter = value;\n        }\n    }\n\n    /// &lt;summary&gt;\n    /// Initializes a new instance of the &lt;see cref=&quot;SingletonApplicationEnforcer&quot;/&gt; class.\n    /// &lt;/summary&gt;\n    /// &lt;param name=&quot;processArgsFunc&quot;&gt;A handler for processing command line args \n    /// when they are received from another application instance.&lt;/param&gt;\n    /// &lt;param name=&quot;applicationId&quot;&gt;The application id used \n    /// for naming the &lt;seealso cref=&quot;EventWaitHandle&quot;/&gt;.&lt;/param&gt;\n    public SingletonApplicationEnforcer(Action&lt;IEnumerable&lt;string&gt;&gt; processArgsFunc, \n        string applicationId = &quot;DisciplesRock&quot;)\n    {\n        if (processArgsFunc == null)\n        {\n            throw new ArgumentNullException(&quot;processArgsFunc&quot;);\n        }\n        this.processArgsFunc = processArgsFunc;\n        this.applicationId = applicationId;\n    }\n\n    /// &lt;summary&gt;\n    /// Determines if this application instance is not the singleton instance.\n    /// If this application is not the singleton, then it should exit.\n    /// &lt;/summary&gt;\n    /// &lt;returns&gt;&lt;c&gt;true&lt;/c&gt; if the application should shutdown, \n    /// otherwise &lt;c&gt;false&lt;/c&gt;.&lt;/returns&gt;\n    public bool ShouldApplicationExit()\n    {\n        bool createdNew;\n        string argsWaitHandleName = &quot;ArgsWaitHandle_&quot; + applicationId;\n        string memoryFileName = &quot;ArgFile_&quot; + applicationId;\n\n        EventWaitHandle argsWaitHandle = new EventWaitHandle(\n            false, EventResetMode.AutoReset, argsWaitHandleName, out createdNew);\n\n        GC.KeepAlive(argsWaitHandle);\n\n        if (createdNew)\n        {\n            /* This is the main, or singleton application. \n                * A thread is created to service the MemoryMappedFile. \n                * We repeatedly examine this file each time the argsWaitHandle \n                * is Set by a non-singleton application instance. */\n            thread = new Thread(() =&gt;\n                {\n                    try\n                    {\n                        using (MemoryMappedFile file = MemoryMappedFile.CreateOrOpen(memoryFileName, 10000))\n                        {\n                            while (true)\n                            {\n                                argsWaitHandle.WaitOne();\n                                using (MemoryMappedViewStream stream = file.CreateViewStream())\n                                {\n                                    var reader = new BinaryReader(stream);\n                                    string args;\n                                    try\n                                    {\n                                        args = reader.ReadString();\n                                    }\n                                    catch (Exception ex)\n                                    {\n                                        Debug.WriteLine(&quot;Unable to retrieve string. &quot; + ex);\n                                        continue;\n                                    }\n                                    string[] argsSplit = args.Split(new string[] { argDelimiter }, \n                                                                    StringSplitOptions.RemoveEmptyEntries);\n                                    processArgsFunc(argsSplit);\n                                }\n\n                            }\n                        }\n                    }\n                    catch (Exception ex)\n                    {\n                        Debug.WriteLine(&quot;Unable to monitor memory file. &quot; + ex);\n                    }\n                });\n\n            thread.IsBackground = true;\n            thread.Start();\n        }\n        else\n        {\n            /* Non singleton application instance. \n                * Should exit, after passing command line args to singleton process, \n                * via the MemoryMappedFile. */\n            using (MemoryMappedFile mmf = MemoryMappedFile.OpenExisting(memoryFileName))\n            {\n                using (MemoryMappedViewStream stream = mmf.CreateViewStream())\n                {\n                    var writer = new BinaryWriter(stream);\n                    string[] args = Environment.GetCommandLineArgs();\n                    string joined = string.Join(argDelimiter, args);\n                    writer.Write(joined);\n                }\n            }\n            argsWaitHandle.Set();\n        }\n\n        return !createdNew;\n    }\n}\n</code></pre>\n'}, {'answer_id': 68214933, 'author': 'datchung', 'author_id': 4856020, 'author_profile': 'https://Stackoverflow.com/users/4856020', 'pm_score': -1, 'selected': False, 'text': "<p>Based Matt Davis' answer, wrapped into a class for convenience.</p>\n<pre><code>public static class SingleAppInstanceChecker\n{\n    /// &lt;summary&gt;\n    /// Arbitrary unique string\n    /// &lt;/summary&gt;\n    private static Mutex _mutex = new Mutex(true, &quot;0d12ad74-026f-40c3-bdae-e178ddee8602&quot;);\n\n    public static bool IsNotRunning()\n    {\n        return _mutex.WaitOne(TimeSpan.Zero, true);\n    }\n}\n</code></pre>\n<p>Example usage:</p>\n<pre><code>private void Application_Startup(object sender, StartupEventArgs e)\n{\n    if (!SingleAppInstanceChecker.IsNotRunning())\n    {\n        MessageBox.Show(&quot;Application is already running.&quot;);\n\n        // Exit application using:\n        // Environment.Exit(1);\n        // Application.Current.Shutdown();\n        // Etc...\n\n        return;\n    }\n    \n    // Allow startup and continue with normal processing\n    // ...\n}\n</code></pre>\n"}, {'answer_id': 72174023, 'author': 'Hanabi', 'author_id': 14700529, 'author_profile': 'https://Stackoverflow.com/users/14700529', 'pm_score': 0, 'selected': False, 'text': '<p>Here is my entire <code>App.xaml.cs</code>, this code also brings the launched program instance to the foreground:</p>\n<pre class="lang-cs prettyprint-override"><code>public partial class App : Application\n{\n    private static Mutex _mutex = null;\n\n    [DllImport(&quot;user32.dll&quot;)]\n    static extern bool SetForegroundWindow(IntPtr hWnd);\n\n    [DllImport(&quot;user32.dll&quot;)]\n    static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);\n\n    protected override void OnStartup(StartupEventArgs e)\n    {\n        _mutex = new Mutex(true, &quot;YourMutexName&quot;, out var createdNew);\n\n        if (!createdNew)\n        {\n            using (var currentProcess = Process.GetCurrentProcess())\n            {\n                foreach (var process in Process.GetProcessesByName(currentProcess.ProcessName))\n                {\n                    if (process.Id != currentProcess.Id)\n                    {\n                        ShowWindow(process.MainWindowHandle, 9);\n                        SetForegroundWindow(process.MainWindowHandle);\n                    }\n                    process.Dispose();\n                }\n            }\n            // app is already running! Exiting the application  \n            Shutdown();\n        }\n\n        base.OnStartup(e);\n    }\n\n    protected override void OnExit(ExitEventArgs e)\n    {\n        _mutex.Dispose();\n        base.OnExit(e);\n    }\n}\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/19147', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/483/']