1 // OpenTween - Client of Twitter
2 // Copyright (c) 2007-2012 kiri_feather (@kiri_feather) <kiri.feather@gmail.com>
3 // (c) 2008-2012 Moz (@syo68k)
4 // (c) 2008-2012 takeshik (@takeshik) <http://www.takeshik.org/>
5 // (c) 2010-2012 anis774 (@anis774) <http://d.hatena.ne.jp/anis774/>
6 // (c) 2010-2012 fantasticswallow (@f_swallow) <http://twitter.com/f_swallow>
7 // (c) 2012 Egtra (@egtra) <http://dev.activebasic.com/egtra/>
8 // (c) 2012 kim_upsilon (@kim_upsilon) <https://upsilo.net/~upsilon/>
9 // All rights reserved.
11 // This file is part of OpenTween.
13 // This program is free software; you can redistribute it and/or modify it
14 // under the terms of the GNU General public License as published by the Free
15 // Software Foundation; either version 3 of the License, or (at your option)
18 // This program is distributed in the hope that it will be useful, but
19 // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
20 // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General public License
23 // You should have received a copy of the GNU General public License along
24 // with this program. If not, see <http://www.gnu.org/licenses/>, or write to
25 // the Free Software Foundation, Inc., 51 Franklin Street - Fifth Floor,
26 // Boston, MA 02110-1301, USA.
31 using System.Diagnostics;
33 using System.Threading;
38 /// アプリケーションの多重起動を抑制するためのクラス
40 public sealed class ApplicationInstanceMutex : IDisposable
42 public bool IsDisposed { get; private set; } = false;
44 private readonly Mutex mutex;
45 private readonly bool createdNew;
47 public ApplicationInstanceMutex(string appName, string settingPath)
49 var name = $"{settingPath.Replace(@"\", "/")}/{appName}";
50 this.mutex = new Mutex(initiallyOwned: true, name, out this.createdNew);
54 /// 他のインスタンスが既に起動している場合は true、それ以外は false
56 public bool InstanceExists
59 public void TryActivatePreviousInstance()
61 // 実行中の同じアプリケーションのウィンドウ・ハンドルの取得
62 var prevProcess = this.GetPreviousProcess();
63 if (prevProcess == null)
66 var windowHandle = NativeMethods.GetWindowHandle((uint)prevProcess.Id, ApplicationSettings.ApplicationName);
67 if (windowHandle != IntPtr.Zero)
68 NativeMethods.SetActiveWindow(windowHandle);
71 private Process? GetPreviousProcess()
75 var currentProcess = Process.GetCurrentProcess();
77 return Process.GetProcessesByName(currentProcess.ProcessName)
78 .Where(p => p.Id != currentProcess.Id)
79 .FirstOrDefault(p => p.MainModule.FileName.Equals(currentProcess.MainModule.FileName, StringComparison.OrdinalIgnoreCase));
92 this.IsDisposed = true;
95 this.mutex.ReleaseMutex();