├── .gitignore
├── LICENSE
├── README.md
└── src
├── ISingleInstance.cs
├── NativeMethods.cs
├── ObsoleteSingleInstance.cs
├── SerializationExtensions.cs
├── SingleInstance.cs
├── SingleInstanceCore.csproj
├── SingleInstanceCore.sln
└── WM.cs
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 | ##
4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
5 |
6 | # User-specific files
7 | *.rsuser
8 | *.suo
9 | *.user
10 | *.userosscache
11 | *.sln.docstates
12 |
13 | # User-specific files (MonoDevelop/Xamarin Studio)
14 | *.userprefs
15 |
16 | # Mono auto generated files
17 | mono_crash.*
18 |
19 | # Build results
20 | [Dd]ebug/
21 | [Dd]ebugPublic/
22 | [Rr]elease/
23 | [Rr]eleases/
24 | x64/
25 | x86/
26 | [Aa][Rr][Mm]/
27 | [Aa][Rr][Mm]64/
28 | bld/
29 | [Bb]in/
30 | [Oo]bj/
31 | [Ll]og/
32 | [Ll]ogs/
33 |
34 | # Visual Studio 2015/2017 cache/options directory
35 | .vs/
36 | # Uncomment if you have tasks that create the project's static files in wwwroot
37 | #wwwroot/
38 |
39 | # Visual Studio 2017 auto generated files
40 | Generated\ Files/
41 |
42 | # MSTest test Results
43 | [Tt]est[Rr]esult*/
44 | [Bb]uild[Ll]og.*
45 |
46 | # NUnit
47 | *.VisualState.xml
48 | TestResult.xml
49 | nunit-*.xml
50 |
51 | # Build Results of an ATL Project
52 | [Dd]ebugPS/
53 | [Rr]eleasePS/
54 | dlldata.c
55 |
56 | # Benchmark Results
57 | BenchmarkDotNet.Artifacts/
58 |
59 | # .NET Core
60 | project.lock.json
61 | project.fragment.lock.json
62 | artifacts/
63 |
64 | # StyleCop
65 | StyleCopReport.xml
66 |
67 | # Files built by Visual Studio
68 | *_i.c
69 | *_p.c
70 | *_h.h
71 | *.ilk
72 | *.meta
73 | *.obj
74 | *.iobj
75 | *.pch
76 | *.pdb
77 | *.ipdb
78 | *.pgc
79 | *.pgd
80 | *.rsp
81 | *.sbr
82 | *.tlb
83 | *.tli
84 | *.tlh
85 | *.tmp
86 | *.tmp_proj
87 | *_wpftmp.csproj
88 | *.log
89 | *.vspscc
90 | *.vssscc
91 | .builds
92 | *.pidb
93 | *.svclog
94 | *.scc
95 |
96 | # Chutzpah Test files
97 | _Chutzpah*
98 |
99 | # Visual C++ cache files
100 | ipch/
101 | *.aps
102 | *.ncb
103 | *.opendb
104 | *.opensdf
105 | *.sdf
106 | *.cachefile
107 | *.VC.db
108 | *.VC.VC.opendb
109 |
110 | # Visual Studio profiler
111 | *.psess
112 | *.vsp
113 | *.vspx
114 | *.sap
115 |
116 | # Visual Studio Trace Files
117 | *.e2e
118 |
119 | # TFS 2012 Local Workspace
120 | $tf/
121 |
122 | # Guidance Automation Toolkit
123 | *.gpState
124 |
125 | # ReSharper is a .NET coding add-in
126 | _ReSharper*/
127 | *.[Rr]e[Ss]harper
128 | *.DotSettings.user
129 |
130 | # TeamCity is a build add-in
131 | _TeamCity*
132 |
133 | # DotCover is a Code Coverage Tool
134 | *.dotCover
135 |
136 | # AxoCover is a Code Coverage Tool
137 | .axoCover/*
138 | !.axoCover/settings.json
139 |
140 | # Visual Studio code coverage results
141 | *.coverage
142 | *.coveragexml
143 |
144 | # NCrunch
145 | _NCrunch_*
146 | .*crunch*.local.xml
147 | nCrunchTemp_*
148 |
149 | # MightyMoose
150 | *.mm.*
151 | AutoTest.Net/
152 |
153 | # Web workbench (sass)
154 | .sass-cache/
155 |
156 | # Installshield output folder
157 | [Ee]xpress/
158 |
159 | # DocProject is a documentation generator add-in
160 | DocProject/buildhelp/
161 | DocProject/Help/*.HxT
162 | DocProject/Help/*.HxC
163 | DocProject/Help/*.hhc
164 | DocProject/Help/*.hhk
165 | DocProject/Help/*.hhp
166 | DocProject/Help/Html2
167 | DocProject/Help/html
168 |
169 | # Click-Once directory
170 | publish/
171 |
172 | # Publish Web Output
173 | *.[Pp]ublish.xml
174 | *.azurePubxml
175 | # Note: Comment the next line if you want to checkin your web deploy settings,
176 | # but database connection strings (with potential passwords) will be unencrypted
177 | *.pubxml
178 | *.publishproj
179 |
180 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
181 | # checkin your Azure Web App publish settings, but sensitive information contained
182 | # in these scripts will be unencrypted
183 | PublishScripts/
184 |
185 | # NuGet Packages
186 | *.nupkg
187 | # NuGet Symbol Packages
188 | *.snupkg
189 | # The packages folder can be ignored because of Package Restore
190 | **/[Pp]ackages/*
191 | # except build/, which is used as an MSBuild target.
192 | !**/[Pp]ackages/build/
193 | # Uncomment if necessary however generally it will be regenerated when needed
194 | #!**/[Pp]ackages/repositories.config
195 | # NuGet v3's project.json files produces more ignorable files
196 | *.nuget.props
197 | *.nuget.targets
198 |
199 | # Microsoft Azure Build Output
200 | csx/
201 | *.build.csdef
202 |
203 | # Microsoft Azure Emulator
204 | ecf/
205 | rcf/
206 |
207 | # Windows Store app package directories and files
208 | AppPackages/
209 | BundleArtifacts/
210 | Package.StoreAssociation.xml
211 | _pkginfo.txt
212 | *.appx
213 | *.appxbundle
214 | *.appxupload
215 |
216 | # Visual Studio cache files
217 | # files ending in .cache can be ignored
218 | *.[Cc]ache
219 | # but keep track of directories ending in .cache
220 | !?*.[Cc]ache/
221 |
222 | # Others
223 | ClientBin/
224 | ~$*
225 | *~
226 | *.dbmdl
227 | *.dbproj.schemaview
228 | *.jfm
229 | *.pfx
230 | *.publishsettings
231 | orleans.codegen.cs
232 |
233 | # Including strong name files can present a security risk
234 | # (https://github.com/github/gitignore/pull/2483#issue-259490424)
235 | #*.snk
236 |
237 | # Since there are multiple workflows, uncomment next line to ignore bower_components
238 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
239 | #bower_components/
240 |
241 | # RIA/Silverlight projects
242 | Generated_Code/
243 |
244 | # Backup & report files from converting an old project file
245 | # to a newer Visual Studio version. Backup files are not needed,
246 | # because we have git ;-)
247 | _UpgradeReport_Files/
248 | Backup*/
249 | UpgradeLog*.XML
250 | UpgradeLog*.htm
251 | ServiceFabricBackup/
252 | *.rptproj.bak
253 |
254 | # SQL Server files
255 | *.mdf
256 | *.ldf
257 | *.ndf
258 |
259 | # Business Intelligence projects
260 | *.rdl.data
261 | *.bim.layout
262 | *.bim_*.settings
263 | *.rptproj.rsuser
264 | *- [Bb]ackup.rdl
265 | *- [Bb]ackup ([0-9]).rdl
266 | *- [Bb]ackup ([0-9][0-9]).rdl
267 |
268 | # Microsoft Fakes
269 | FakesAssemblies/
270 |
271 | # GhostDoc plugin setting file
272 | *.GhostDoc.xml
273 |
274 | # Node.js Tools for Visual Studio
275 | .ntvs_analysis.dat
276 | node_modules/
277 |
278 | # Visual Studio 6 build log
279 | *.plg
280 |
281 | # Visual Studio 6 workspace options file
282 | *.opt
283 |
284 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
285 | *.vbw
286 |
287 | # Visual Studio LightSwitch build output
288 | **/*.HTMLClient/GeneratedArtifacts
289 | **/*.DesktopClient/GeneratedArtifacts
290 | **/*.DesktopClient/ModelManifest.xml
291 | **/*.Server/GeneratedArtifacts
292 | **/*.Server/ModelManifest.xml
293 | _Pvt_Extensions
294 |
295 | # Paket dependency manager
296 | .paket/paket.exe
297 | paket-files/
298 |
299 | # FAKE - F# Make
300 | .fake/
301 |
302 | # CodeRush personal settings
303 | .cr/personal
304 |
305 | # Python Tools for Visual Studio (PTVS)
306 | __pycache__/
307 | *.pyc
308 |
309 | # Cake - Uncomment if you are using it
310 | # tools/**
311 | # !tools/packages.config
312 |
313 | # Tabs Studio
314 | *.tss
315 |
316 | # Telerik's JustMock configuration file
317 | *.jmconfig
318 |
319 | # BizTalk build output
320 | *.btp.cs
321 | *.btm.cs
322 | *.odx.cs
323 | *.xsd.cs
324 |
325 | # OpenCover UI analysis results
326 | OpenCover/
327 |
328 | # Azure Stream Analytics local run output
329 | ASALocalRun/
330 |
331 | # MSBuild Binary and Structured Log
332 | *.binlog
333 |
334 | # NVidia Nsight GPU debugger configuration file
335 | *.nvuser
336 |
337 | # MFractors (Xamarin productivity tool) working folder
338 | .mfractor/
339 |
340 | # Local History for Visual Studio
341 | .localhistory/
342 |
343 | # BeatPulse healthcheck temp database
344 | healthchecksdb
345 |
346 | # Backup folder for Package Reference Convert tool in Visual Studio 2017
347 | MigrationBackup/
348 |
349 | # Ionide (cross platform F# VS Code tools) working folder
350 | .ionide/
351 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2020 Soheil Khodaei
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # SingleInstanceCore
2 | For single instance applications on .NET Core
3 |
4 | NuGet Package: https://www.nuget.org/packages/SingleInstanceCore/
5 | # Usage
6 |
7 | Note: Usage examples are for WPF and Winforms desktop applications. For other platforms/frameworks, inheritance and initialization should be done accordingly, not exactly like the examples.
8 |
9 | The class that handles instance invokation should inherit ISingleInstance and implement OnInstanceInvoked method.
10 |
11 | ## WPF
12 | E.g. in App class (`App.xaml.cs`):
13 | ```csharp
14 | public partial class App : Application, ISingleInstance
15 | {
16 | public void OnInstanceInvoked(string[] args)
17 | {
18 | // What to do with the args another instance has sent
19 | }
20 | // ...
21 | }
22 | ```
23 | Initialization of instance should be done when application is starting, and cleanup method should be called on the exit point of the application.
24 |
25 | E.g. in App class (`App.xaml.cs`):
26 | ```csharp
27 | private void Application_Startup(object sender, StartupEventArgs e)
28 | {
29 | bool isFirstInstance = this.InitializeAsFirstInstance("soheilkd_ExampleIPC");
30 | if (!isFirstInstance)
31 | {
32 | //If it's not the first instance, arguments are automatically passed to the first instance
33 | //OnInstanceInvoked will be raised on the first instance
34 | //You may shut down the current instance
35 | Current.Shutdown();
36 | }
37 | }
38 |
39 | private void Application_Exit(object sender, ExitEventArgs e)
40 | {
41 | //Do not forget to cleanup
42 | SingleInstance.Cleanup();
43 | }
44 | ```
45 |
46 | ## Winforms
47 | Winforms doesn't have an Application.cs that could implement the `ISingleInstance` interface. We have to define one ourselves.
48 | ```csharp
49 | static class Program
50 | {
51 | [STAThread]
52 | static void Main(string[] args)
53 | {
54 | var app = new YourApplication();
55 |
56 | var isFirstInstance = app.InitializeAsFirstInstance(nameof(YourApplication));
57 | if (isFirstInstance)
58 | {
59 | try
60 | {
61 | app.Run();
62 | }
63 | finally
64 | {
65 | SingleInstance.Cleanup();
66 | }
67 | }
68 | }
69 | }
70 |
71 | class YourApplication : ISingleInstance
72 | {
73 | public void Run()
74 | {
75 | Application.SetHighDpiMode(HighDpiMode.SystemAware);
76 | Application.EnableVisualStyles();
77 | Application.SetCompatibleTextRenderingDefault(false);
78 | Application.Run(new MainForm()); // Blocks until the main window is closed
79 | }
80 |
81 | public void OnInstanceInvoked(string[] args)
82 | {
83 | // What to do with the args another instance has sent
84 | }
85 | }
86 |
87 | ```
88 |
--------------------------------------------------------------------------------
/src/ISingleInstance.cs:
--------------------------------------------------------------------------------
1 | namespace SingleInstanceCore
2 | {
3 | public interface ISingleInstance
4 | {
5 | public void OnInstanceInvoked(string[] args);
6 | }
7 | }
8 |
--------------------------------------------------------------------------------
/src/NativeMethods.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.ComponentModel;
3 | using System.Runtime.InteropServices;
4 | using System.Security;
5 |
6 | namespace SingleInstanceCore
7 | {
8 | [SuppressUnmanagedCodeSecurity]
9 | internal static class NativeMethods
10 | {
11 | ///
12 | /// Delegate declaration that matches WndProc signatures.
13 | ///
14 | public delegate IntPtr MessageHandler(WM uMsg, IntPtr wParam, IntPtr lParam, out bool handled);
15 |
16 | [DllImport("shell32.dll", EntryPoint = "CommandLineToArgvW", CharSet = CharSet.Unicode)]
17 | private static extern IntPtr CommandLineToArgvW([MarshalAs(UnmanagedType.LPWStr)] string cmdLine, out int numArgs);
18 |
19 | [DllImport("kernel32.dll", EntryPoint = "LocalFree", SetLastError = true)]
20 | private static extern IntPtr LocalFree(IntPtr hMem);
21 |
22 |
23 | public static string[] CommandLineToArgvW(string cmdLine)
24 | {
25 | IntPtr argv = IntPtr.Zero;
26 | try
27 | {
28 | argv = CommandLineToArgvW(cmdLine, out var numArgs);
29 | if (argv == IntPtr.Zero)
30 | throw new Win32Exception();
31 |
32 | var result = new string[numArgs];
33 |
34 | for (var i = 0; i < numArgs; i++)
35 | {
36 | IntPtr currArg = Marshal.ReadIntPtr(argv, i * Marshal.SizeOf(typeof(IntPtr)));
37 | result[i] = Marshal.PtrToStringUni(currArg);
38 | }
39 |
40 | return result;
41 | }
42 | finally
43 | {
44 | _ = LocalFree(argv);
45 | }
46 | }
47 | }
48 | }
--------------------------------------------------------------------------------
/src/ObsoleteSingleInstance.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.IO;
4 | using System.Text;
5 | using System.Threading;
6 | using System.Windows;
7 | using TinyIpc.Messaging;
8 |
9 | namespace SingleInstanceCore
10 | {
11 | [Obsolete("Use non-generic SingleInstance class instead. Check updated example on Github https://github.com/soheilkd/SingleInstanceCore")]
12 | public static class SingleInstance
13 | where TApplication : Application, ISingleInstance
14 | {
15 | private const string channelNameSufflix = ":SingeInstanceIPCChannel";
16 | private static Mutex singleMutex;
17 | private static TinyMessageBus messageBus; //IPC message bus for communication between instances
18 |
19 | ///
20 | /// Intended to be on app startup
21 | /// Initializes service if the call is from first instance
22 | /// Signals the first instance if it already exists
23 | ///
24 | /// A unique name for IPC channel
25 | /// Whether the call is from application's first instance
26 | public static bool InitializeAsFirstInstance(string uniqueName)
27 | {
28 | var CommandLineArgs = GetCommandLineArgs(uniqueName);
29 | var applicationIdentifier = uniqueName + Environment.UserName;
30 | var channelName = $"{applicationIdentifier}{channelNameSufflix}";
31 | singleMutex = new Mutex(true, applicationIdentifier, out var firstInstance);
32 |
33 | if (firstInstance)
34 | CreateRemoteService(channelName);
35 | else
36 | SignalFirstInstance(channelName, CommandLineArgs);
37 |
38 | return firstInstance;
39 | }
40 |
41 | private static void SignalFirstInstance(string channelName, IList commandLineArgs) => new TinyMessageBus(channelName).PublishAsync(commandLineArgs.Serialize());
42 |
43 | private static void CreateRemoteService(string channelName)
44 | {
45 | messageBus = new TinyMessageBus(channelName);
46 | messageBus.MessageReceived += MessageBus_MessageReceived;
47 | }
48 |
49 | private static void MessageBus_MessageReceived(object sender, TinyMessageReceivedEventArgs e)
50 | {
51 | var app = Application.Current as TApplication;
52 | var args = e.Message.Deserialize();
53 | app.OnInstanceInvoked(args);
54 | }
55 |
56 | private static string[] GetCommandLineArgs(string uniqueApplicationName)
57 | {
58 | var args = Environment.GetCommandLineArgs();
59 | if (args == null)
60 | {
61 | // Try getting commandline arguments from shared location in case of ClickOnce deployed application
62 | var appFolderPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), uniqueApplicationName);
63 | var cmdLinePath = Path.Combine(appFolderPath, "cmdline.txt");
64 | if (File.Exists(cmdLinePath))
65 | {
66 | try
67 | {
68 | using var reader = new StreamReader(cmdLinePath, Encoding.Unicode);
69 | args = NativeMethods.CommandLineToArgvW(reader.ReadToEnd());
70 | File.Delete(cmdLinePath);
71 | }
72 | catch (IOException) { }
73 | }
74 | }
75 | return args ?? Array.Empty();
76 | }
77 |
78 | public static void Cleanup()
79 | {
80 | if (messageBus != null)
81 | {
82 | messageBus.Dispose();
83 | messageBus = null;
84 | }
85 | if (singleMutex != null)
86 | {
87 | singleMutex.Close();
88 | singleMutex = null;
89 | }
90 | }
91 | }
92 | }
93 |
--------------------------------------------------------------------------------
/src/SerializationExtensions.cs:
--------------------------------------------------------------------------------
1 | using System.Text.Json;
2 |
3 | namespace SingleInstanceCore
4 | {
5 | //For inline serializing and deserializing
6 | internal static class SerializationExtensions
7 | {
8 | private static readonly JsonSerializerOptions serializerOptions = new JsonSerializerOptions()
9 | {
10 | PropertyNamingPolicy = null,
11 | AllowTrailingCommas = true
12 | };
13 |
14 | internal static byte[] Serialize(this T obj)
15 | {
16 | return JsonSerializer.SerializeToUtf8Bytes(obj, serializerOptions);
17 | }
18 |
19 | internal static T Deserialize(this byte[] data)
20 | {
21 | return JsonSerializer.Deserialize(data, serializerOptions);
22 | }
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/src/SingleInstance.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.IO;
4 | using System.Text;
5 | using System.Threading;
6 | using TinyIpc.Messaging;
7 |
8 | namespace SingleInstanceCore
9 | {
10 | public static class SingleInstance
11 | {
12 | private const string channelNameSufflix = ":SingeInstanceIPCChannel";
13 | //For detecting if mutex is locked (first instance is already up then)
14 | private static Mutex singleMutex;
15 | //Message bus for communication between instances
16 | private static TinyMessageBus messageBus;
17 |
18 | ///
19 | /// Intended to be on app startup
20 | /// Initializes service if the call is from first instance.
21 | /// Signals the first instance if it already exists
22 | ///
23 | /// A unique name for IPC channel
24 | /// Whether the call is from application's first instance
25 | public static bool InitializeAsFirstInstance(this T instance, string uniqueName) where T:ISingleInstance
26 | {
27 | var CommandLineArgs = GetCommandLineArgs(uniqueName);
28 | var applicationIdentifier = uniqueName + Environment.UserName;
29 | var channelName = $"{applicationIdentifier}{channelNameSufflix}";
30 | singleMutex = new Mutex(true, applicationIdentifier, out var firstInstance);
31 |
32 | if (firstInstance)
33 | CreateRemoteService(instance, channelName);
34 | else
35 | SignalFirstInstance(channelName, CommandLineArgs);
36 |
37 | return firstInstance;
38 | }
39 |
40 | private static void SignalFirstInstance(string channelName, IList commandLineArgs)
41 | {
42 | var bus = GetTinyMessageBus(channelName);
43 | var serializedArgs = commandLineArgs.Serialize();
44 | bus?.PublishAsync(serializedArgs).Wait();
45 | WaitTillMessageGetsPublished(bus);
46 | }
47 |
48 | private static TinyMessageBus GetTinyMessageBus(string channelName, int tryCount = 50)
49 | {
50 | int tries = 0;
51 | var minMessageAge = TimeSpan.FromSeconds(30);
52 | while (tries++ < tryCount)
53 | {
54 | try
55 | {
56 | var bus = new TinyMessageBus(channelName, minMessageAge);
57 | return bus;
58 | }
59 | catch (Exception) { }
60 | }
61 | return default;
62 | }
63 |
64 | private static void WaitTillMessageGetsPublished(TinyMessageBus bus)
65 | {
66 | if (bus == null)
67 | return;
68 |
69 | while (bus.MessagesPublished != 1)
70 | {
71 | Thread.Sleep(10);
72 | }
73 | }
74 |
75 | private static void CreateRemoteService(ISingleInstance instance, string channelName)
76 | {
77 | messageBus = new TinyMessageBus(channelName);
78 | messageBus.MessageReceived += (_, e) =>
79 | {
80 | instance.OnInstanceInvoked(e.Message.Deserialize());
81 | };
82 | }
83 |
84 | private static string[] GetCommandLineArgs(string uniqueApplicationName)
85 | {
86 | var args = Environment.GetCommandLineArgs();
87 | if (args == null)
88 | {
89 | // Try getting commandline arguments from shared location in case of ClickOnce deployed application
90 | var appFolderPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), uniqueApplicationName);
91 | var cmdLinePath = Path.Combine(appFolderPath, "cmdline.txt");
92 | if (File.Exists(cmdLinePath))
93 | {
94 | try
95 | {
96 | using var reader = new StreamReader(cmdLinePath, Encoding.Unicode);
97 | args = NativeMethods.CommandLineToArgvW(reader.ReadToEnd());
98 | File.Delete(cmdLinePath);
99 | }
100 | catch (IOException) { }
101 | }
102 | }
103 | return args ?? Array.Empty();
104 | }
105 |
106 | public static void Cleanup()
107 | {
108 | if (messageBus != null)
109 | {
110 | messageBus.Dispose();
111 | messageBus = null;
112 | }
113 | if (singleMutex != null)
114 | {
115 | singleMutex.Close();
116 | singleMutex = null;
117 | }
118 | }
119 | }
120 | }
121 |
--------------------------------------------------------------------------------
/src/SingleInstanceCore.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 | netcoreapp3.1
4 | true
5 | soheilkd
6 |
7 | https://github.com/soheilkd/SingleInstanceCore
8 | https://github.com/soheilkd/SingleInstanceCore
9 | Github
10 | To create single instance applications on .NET Core/.NET 5
11 | single instance core dotnet
12 | en-US
13 | 2.2.2
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/src/SingleInstanceCore.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio Version 16
4 | VisualStudioVersion = 16.0.29806.167
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SingleInstanceCore", "SingleInstanceCore.csproj", "{215AAC6C-2C2D-4A1C-B8A3-A68545A00983}"
7 | EndProject
8 | Global
9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
10 | Debug|Any CPU = Debug|Any CPU
11 | Release|Any CPU = Release|Any CPU
12 | EndGlobalSection
13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
14 | {215AAC6C-2C2D-4A1C-B8A3-A68545A00983}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
15 | {215AAC6C-2C2D-4A1C-B8A3-A68545A00983}.Debug|Any CPU.Build.0 = Debug|Any CPU
16 | {215AAC6C-2C2D-4A1C-B8A3-A68545A00983}.Release|Any CPU.ActiveCfg = Release|Any CPU
17 | {215AAC6C-2C2D-4A1C-B8A3-A68545A00983}.Release|Any CPU.Build.0 = Release|Any CPU
18 | EndGlobalSection
19 | GlobalSection(SolutionProperties) = preSolution
20 | HideSolutionNode = FALSE
21 | EndGlobalSection
22 | GlobalSection(ExtensibilityGlobals) = postSolution
23 | SolutionGuid = {7C0AA17E-C948-469D-98C0-116F3485941B}
24 | EndGlobalSection
25 | EndGlobal
26 |
--------------------------------------------------------------------------------
/src/WM.cs:
--------------------------------------------------------------------------------
1 | namespace SingleInstanceCore
2 | {
3 | internal enum WM
4 | {
5 | NULL = 0x0000,
6 | CREATE = 0x0001,
7 | DESTROY = 0x0002,
8 | MOVE = 0x0003,
9 | SIZE = 0x0005,
10 | ACTIVATE = 0x0006,
11 | SETFOCUS = 0x0007,
12 | KILLFOCUS = 0x0008,
13 | ENABLE = 0x000A,
14 | SETREDRAW = 0x000B,
15 | SETTEXT = 0x000C,
16 | GETTEXT = 0x000D,
17 | GETTEXTLENGTH = 0x000E,
18 | PAINT = 0x000F,
19 | CLOSE = 0x0010,
20 | QUERYENDSESSION = 0x0011,
21 | QUIT = 0x0012,
22 | QUERYOPEN = 0x0013,
23 | ERASEBKGND = 0x0014,
24 | SYSCOLORCHANGE = 0x0015,
25 | SHOWWINDOW = 0x0018,
26 | ACTIVATEAPP = 0x001C,
27 | SETCURSOR = 0x0020,
28 | MOUSEACTIVATE = 0x0021,
29 | CHILDACTIVATE = 0x0022,
30 | QUEUESYNC = 0x0023,
31 | GETMINMAXINFO = 0x0024,
32 |
33 | WINDOWPOSCHANGING = 0x0046,
34 | WINDOWPOSCHANGED = 0x0047,
35 |
36 | CONTEXTMENU = 0x007B,
37 | STYLECHANGING = 0x007C,
38 | STYLECHANGED = 0x007D,
39 | DISPLAYCHANGE = 0x007E,
40 | GETICON = 0x007F,
41 | SETICON = 0x0080,
42 | NCCREATE = 0x0081,
43 | NCDESTROY = 0x0082,
44 | NCCALCSIZE = 0x0083,
45 | NCHITTEST = 0x0084,
46 | NCPAINT = 0x0085,
47 | NCACTIVATE = 0x0086,
48 | GETDLGCODE = 0x0087,
49 | SYNCPAINT = 0x0088,
50 | NCMOUSEMOVE = 0x00A0,
51 | NCLBUTTONDOWN = 0x00A1,
52 | NCLBUTTONUP = 0x00A2,
53 | NCLBUTTONDBLCLK = 0x00A3,
54 | NCRBUTTONDOWN = 0x00A4,
55 | NCRBUTTONUP = 0x00A5,
56 | NCRBUTTONDBLCLK = 0x00A6,
57 | NCMBUTTONDOWN = 0x00A7,
58 | NCMBUTTONUP = 0x00A8,
59 | NCMBUTTONDBLCLK = 0x00A9,
60 |
61 | SYSKEYDOWN = 0x0104,
62 | SYSKEYUP = 0x0105,
63 | SYSCHAR = 0x0106,
64 | SYSDEADCHAR = 0x0107,
65 | COMMAND = 0x0111,
66 | SYSCOMMAND = 0x0112,
67 |
68 | MOUSEMOVE = 0x0200,
69 | LBUTTONDOWN = 0x0201,
70 | LBUTTONUP = 0x0202,
71 | LBUTTONDBLCLK = 0x0203,
72 | RBUTTONDOWN = 0x0204,
73 | RBUTTONUP = 0x0205,
74 | RBUTTONDBLCLK = 0x0206,
75 | MBUTTONDOWN = 0x0207,
76 | MBUTTONUP = 0x0208,
77 | MBUTTONDBLCLK = 0x0209,
78 | MOUSEWHEEL = 0x020A,
79 | XBUTTONDOWN = 0x020B,
80 | XBUTTONUP = 0x020C,
81 | XBUTTONDBLCLK = 0x020D,
82 | MOUSEHWHEEL = 0x020E,
83 |
84 |
85 | CAPTURECHANGED = 0x0215,
86 |
87 | ENTERSIZEMOVE = 0x0231,
88 | EXITSIZEMOVE = 0x0232,
89 |
90 | IME_SETCONTEXT = 0x0281,
91 | IME_NOTIFY = 0x0282,
92 | IME_CONTROL = 0x0283,
93 | IME_COMPOSITIONFULL = 0x0284,
94 | IME_SELECT = 0x0285,
95 | IME_CHAR = 0x0286,
96 | IME_REQUEST = 0x0288,
97 | IME_KEYDOWN = 0x0290,
98 | IME_KEYUP = 0x0291,
99 |
100 | NCMOUSELEAVE = 0x02A2,
101 |
102 | DWMCOMPOSITIONCHANGED = 0x031E,
103 | DWMNCRENDERINGCHANGED = 0x031F,
104 | DWMCOLORIZATIONCOLORCHANGED = 0x0320,
105 | DWMWINDOWMAXIMIZEDCHANGE = 0x0321,
106 |
107 | #region Windows 7
108 | DWMSENDICONICTHUMBNAIL = 0x0323,
109 | DWMSENDICONICLIVEPREVIEWBITMAP = 0x0326,
110 | #endregion
111 |
112 | USER = 0x0400,
113 |
114 | // This is the hard-coded message value used by WinForms for Shell_NotifyIcon.
115 | // It's relatively safe to reuse.
116 | TRAYMOUSEMESSAGE = 0x800, //WM_USER + 1024
117 | APP = 0x8000,
118 | }
119 | }
120 |
--------------------------------------------------------------------------------