{"id":1458,"date":"2011-02-14T22:37:56","date_gmt":"2011-02-14T21:37:56","guid":{"rendered":"http:\/\/www.gamlor.info\/wordpress\/?p=1458"},"modified":"2023-04-30T20:29:15","modified_gmt":"2023-04-30T19:29:15","slug":"single-app-instance-in-net","status":"publish","type":"post","link":"https:\/\/www.gamlor.info\/wordpress\/2011\/02\/single-app-instance-in-net\/","title":{"rendered":"Single App-Instance in .NET"},"content":{"rendered":"<div id=\"attachment_1462\" style=\"width: 246px\" class=\"wp-caption alignleft\"><a href=\"https:\/\/www.gamlor.info\/wordpress\/wp-content\/uploads\/2011\/02\/there-can-be-only-one.png\"><img loading=\"lazy\" decoding=\"async\" aria-describedby=\"caption-attachment-1462\" class=\"size-medium wp-image-1462 \" src=\"https:\/\/www.gamlor.info\/wordpress\/wp-content\/uploads\/2011\/02\/there-can-be-only-one-236x300.png\" title=\"Wow, a Highlander reference \\o\/\" alt=\"Wow, a Highlander reference \\o\/\" width=\"236\" height=\"300\" srcset=\"https:\/\/www.gamlor.info\/wordpress\/wp-content\/uploads\/2011\/02\/there-can-be-only-one-236x300.png 236w, https:\/\/www.gamlor.info\/wordpress\/wp-content\/uploads\/2011\/02\/there-can-be-only-one.png 477w\" sizes=\"(max-width: 236px) 100vw, 236px\" \/><\/a><p id=\"caption-attachment-1462\" class=\"wp-caption-text\">There can be only one<\/p><\/div>\n<p>Sometime it makes sense to enforce that only one instance of your application is running, for example a media player application. There are different ways to archive that. I just want to share my solution to this issue. I achive this with a named mutex. Such a mutex is a global resource and visible across processes. In .NET you can use the regular <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/system.threading.mutex.aspx\">Mutex<\/a> class and specify its name:<\/p>\n<script src=\"https:\/\/gist.github.com\/826642.js?file=global-mutex.cs\"><\/script><noscript><pre><code class=\"language-c# c#\">var mutex = new Mutex(true,\n            &quot;YourCompany-YourApp-SingleInstance&quot;);<\/code><\/pre><\/noscript>\n<p>I also added the user-name. This ensures that each user on the machine can start one instance of the application. (Well in reality Windows already does that for you. It makes the mutex only visible withing the same session.)<\/p>\n<script src=\"https:\/\/gist.github.com\/826642.js?file=global-mutex-with-username.cs\"><\/script><noscript><pre><code class=\"language-c# c#\">var mutex = new Mutex(true,\n            &quot;YourCompany-YourApp-SingleInstance-&quot; + Environment.UserName);<\/code><\/pre><\/noscript>\n<p>Now we can just write a regular application which only starts when it can grab the mutex:<\/p>\n<script src=\"https:\/\/gist.github.com\/826642.js?file=start-up-app.cs\"><\/script><noscript><pre><code class=\"language-c# c#\">public class Program\n    {\n        static readonly Mutex mutex = new Mutex(true,\n            &quot;YourCompany-YourApp-SingleInstance-&quot; + Environment.UserName);\n        [STAThread]\n        public static void Main(string[] args)\n        {\n            if (mutex.WaitOne(TimeSpan.Zero, true))\n            {\n                try\n                {\n                    \/\/ now we start the real application.\n                    \/\/ in this case a WPF-app.\n                    new App().Run();\n                } finally\n                {\n                    mutex.ReleaseMutex();\n                }\n            }            \n        }\n    }<\/code><\/pre><\/noscript>\n<p>That\u2019s it, with these few lines you can create a single instance application. However that\u2019s probably not enough, at least for a desktop app. Imagine you are using such an application. You have started the application and it is running in the background. And like any human being you forget that it is running. You desperate click on the application icon to start it, but nothing happens. We need to fix this. The easiest implementation would be to just show a dialog informing that the application is already running. That solution isn\u2019t very user friendly, because the user has to click away the information box and then find the running instance. A much more elegant way is to show the running instance when the user starts the application again. &nbsp;That\u2019s what I did in my application. I use two native Windows function to bring the application back into focus:<\/p>\n<script src=\"https:\/\/gist.github.com\/826642.js?file=FocusSwitcher.cs\"><\/script><noscript><pre><code class=\"language-c# c#\">public class FocusSwitcher\n{\n    [DllImport(&quot;user32.dll&quot;)]\n    private static extern bool ShowWindowAsync(HandleRef hWnd, int nCmdShow);\n    [DllImport(&quot;user32.dll&quot;)] \n    private static extern bool SetForegroundWindow(IntPtr hWnd);\n    private const int SW_MAXIMIZE = 3;\n\n    public static void SwitchToCurrent()\n    {\n        var hWnd = IntPtr.Zero;\n        var thisProcess = Process.GetCurrentProcess();\n        var processes = Process.GetProcessesByName(thisProcess.ProcessName)\n                                .Where(p=&gt;p.Id != thisProcess.Id);\n        foreach (Process runningProcesses in processes)\n        {\n            \/\/ Get the first instance that is not this instance, has the\n            \/\/ same process name and was started from the same file name\n            \/\/ and location. Also check that the process has a valid\n            \/\/ window handle in this session to filter out other user&#039;s\n            \/\/ processes.\n            if (runningProcesses.MainModule.FileName == thisProcess.MainModule.FileName &amp;&amp;\n                runningProcesses.MainWindowHandle != IntPtr.Zero)\n            {\n                hWnd = runningProcesses.MainWindowHandle;\n                ShowWindowAsync(new HandleRef(null, hWnd), SW_MAXIMIZE);\n                SetForegroundWindow(hWnd);\n                break;\n            }\n        }\n    }\n}\n<\/code><\/pre><\/noscript>\n<p>Yes, Win32-API pros might cry about my solution. And there are certainly more elegant solution to bring a running application to the top. But this solution works good enough for me. So my final code calls the focus switch method in the case it cannot grab the mutex.<\/p>\n<script src=\"https:\/\/gist.github.com\/826642.js?file=final-startup.cs\"><\/script><noscript><pre><code class=\"language-c# c#\">public class Program\n    {\n        static readonly Mutex mutex = new Mutex(true,\n            &quot;YourCompany-YourApp-SingleInstance-&quot; + Environment.UserName);\n        [STAThread]\n        public static void Main(string[] args)\n        {\n            if (mutex.WaitOne(TimeSpan.Zero, true))\n            {\n                try\n                {\n                    \/\/ now we start the real application.\n                    \/\/ in this case a WPF-app.\n                    new App().Run();\n                } finally\n                {\n                    mutex.ReleaseMutex();\n                }\n            } \n            else\n            {\n                FocusSwitcher.SwitchToCurrent();\n            }          \n        }\n    }<\/code><\/pre><\/noscript>\n","protected":false},"excerpt":{"rendered":"<p>Sometime it makes sense to enforce that only one instance of your application is running, for example a media player application. There are different ways to archive that. I just&hellip; <\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":"","_links_to":"","_links_to_target":""},"categories":[126],"tags":[21,24],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/www.gamlor.info\/wordpress\/wp-json\/wp\/v2\/posts\/1458"}],"collection":[{"href":"https:\/\/www.gamlor.info\/wordpress\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.gamlor.info\/wordpress\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.gamlor.info\/wordpress\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.gamlor.info\/wordpress\/wp-json\/wp\/v2\/comments?post=1458"}],"version-history":[{"count":10,"href":"https:\/\/www.gamlor.info\/wordpress\/wp-json\/wp\/v2\/posts\/1458\/revisions"}],"predecessor-version":[{"id":3952,"href":"https:\/\/www.gamlor.info\/wordpress\/wp-json\/wp\/v2\/posts\/1458\/revisions\/3952"}],"wp:attachment":[{"href":"https:\/\/www.gamlor.info\/wordpress\/wp-json\/wp\/v2\/media?parent=1458"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.gamlor.info\/wordpress\/wp-json\/wp\/v2\/categories?post=1458"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.gamlor.info\/wordpress\/wp-json\/wp\/v2\/tags?post=1458"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}