在.NET(而不是Windows Forms或控制檯)下使用C#和WPF,建立只能做爲單個實例運行的應用程序的正確方法是什麼? html
我知道它與某種稱爲互斥量的神話事物有關,我不多能找到一個煩人的人來阻止並解釋其中的一個。 app
該代碼還須要告知已經運行的實例用戶試圖啓動第二個實例,而且還可能傳遞任何命令行參數(若是存在)。 ide
看下面的代碼。 這是防止WPF應用程序的多個實例的絕佳解決方案。 ui
private void Application_Startup(object sender, StartupEventArgs e) { Process thisProc = Process.GetCurrentProcess(); if (Process.GetProcessesByName(thisProc.ProcessName).Length > 1) { MessageBox.Show("Application running"); Application.Current.Shutdown(); return; } var wLogin = new LoginWindow(); if (wLogin.ShowDialog() == true) { var wMain = new Main(); wMain.WindowState = WindowState.Maximized; wMain.Show(); } else { Application.Current.Shutdown(); } }
一般,這是我用於單實例Windows Forms應用程序的代碼: this
[STAThread] public static void Main() { String assemblyName = Assembly.GetExecutingAssembly().GetName().Name; using (Mutex mutex = new Mutex(false, assemblyName)) { if (!mutex.WaitOne(0, false)) { Boolean shownProcess = false; Process currentProcess = Process.GetCurrentProcess(); foreach (Process process in Process.GetProcessesByName(currentProcess.ProcessName)) { if (!process.Id.Equals(currentProcess.Id) && process.MainModule.FileName.Equals(currentProcess.MainModule.FileName) && !process.MainWindowHandle.Equals(IntPtr.Zero)) { IntPtr windowHandle = process.MainWindowHandle; if (NativeMethods.IsIconic(windowHandle)) NativeMethods.ShowWindow(windowHandle, ShowWindowCommand.Restore); NativeMethods.SetForegroundWindow(windowHandle); shownProcess = true; } } if (!shownProcess) MessageBox.Show(String.Format(CultureInfo.CurrentCulture, "An instance of {0} is already running!", assemblyName), assemblyName, MessageBoxButtons.OK, MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1, (MessageBoxOptions)0); } else { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form()); } } }
本機組件在哪裏: spa
[DllImport("User32.dll", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern Boolean IsIconic([In] IntPtr windowHandle); [DllImport("User32.dll", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern Boolean SetForegroundWindow([In] IntPtr windowHandle); [DllImport("User32.dll", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern Boolean ShowWindow([In] IntPtr windowHandle, [In] ShowWindowCommand command); public enum ShowWindowCommand : int { Hide = 0x0, ShowNormal = 0x1, ShowMinimized = 0x2, ShowMaximized = 0x3, ShowNormalNotActive = 0x4, Minimize = 0x6, ShowMinimizedNotActive = 0x7, ShowCurrentNotActive = 0x8, Restore = 0x9, ShowDefault = 0xA, ForceMinimize = 0xB }
如下代碼是個人WCF命名管道解決方案,用於註冊單實例應用程序。 很好,由於當另外一個實例嘗試啓動時,它還會引起一個事件,並接收另外一個實例的命令行。 命令行
它面向WPF,由於它使用System.Windows.StartupEventHandler
類,可是能夠輕鬆對其進行修改。 rest
此代碼須要對PresentationFramework
和System.ServiceModel
的引用。 code
用法: orm
class Program { static void Main() { var applicationId = new Guid("b54f7b0d-87f9-4df9-9686-4d8fd76066dc"); if (SingleInstanceManager.VerifySingleInstance(applicationId)) { SingleInstanceManager.OtherInstanceStarted += OnOtherInstanceStarted; // Start the application } } static void OnOtherInstanceStarted(object sender, StartupEventArgs e) { // Do something in response to another instance starting up. } }
/// <summary> /// A class to use for single-instance applications. /// </summary> public static class SingleInstanceManager { /// <summary> /// Raised when another instance attempts to start up. /// </summary> public static event StartupEventHandler OtherInstanceStarted; /// <summary> /// Checks to see if this instance is the first instance running on this machine. If it is not, this method will /// send the main instance this instance's startup information. /// </summary> /// <param name="guid">The application's unique identifier.</param> /// <returns>True if this instance is the main instance.</returns> public static bool VerifySingleInstace(Guid guid) { if (!AttemptPublishService(guid)) { NotifyMainInstance(guid); return false; } return true; } /// <summary> /// Attempts to publish the service. /// </summary> /// <param name="guid">The application's unique identifier.</param> /// <returns>True if the service was published successfully.</returns> private static bool AttemptPublishService(Guid guid) { try { ServiceHost serviceHost = new ServiceHost(typeof(SingleInstance)); NetNamedPipeBinding binding = new NetNamedPipeBinding(NetNamedPipeSecurityMode.None); serviceHost.AddServiceEndpoint(typeof(ISingleInstance), binding, CreateAddress(guid)); serviceHost.Open(); return true; } catch { return false; } } /// <summary> /// Notifies the main instance that this instance is attempting to start up. /// </summary> /// <param name="guid">The application's unique identifier.</param> private static void NotifyMainInstance(Guid guid) { NetNamedPipeBinding binding = new NetNamedPipeBinding(NetNamedPipeSecurityMode.None); EndpointAddress remoteAddress = new EndpointAddress(CreateAddress(guid)); using (ChannelFactory<ISingleInstance> factory = new ChannelFactory<ISingleInstance>(binding, remoteAddress)) { ISingleInstance singleInstance = factory.CreateChannel(); singleInstance.NotifyMainInstance(Environment.GetCommandLineArgs()); } } /// <summary> /// Creates an address to publish/contact the service at based on a globally unique identifier. /// </summary> /// <param name="guid">The identifier for the application.</param> /// <returns>The address to publish/contact the service.</returns> private static string CreateAddress(Guid guid) { return string.Format(CultureInfo.CurrentCulture, "net.pipe://localhost/{0}", guid); } /// <summary> /// The interface that describes the single instance service. /// </summary> [ServiceContract] private interface ISingleInstance { /// <summary> /// Notifies the main instance that another instance of the application attempted to start. /// </summary> /// <param name="args">The other instance's command-line arguments.</param> [OperationContract] void NotifyMainInstance(string[] args); } /// <summary> /// The implementation of the single instance service interface. /// </summary> private class SingleInstance : ISingleInstance { /// <summary> /// Notifies the main instance that another instance of the application attempted to start. /// </summary> /// <param name="args">The other instance's command-line arguments.</param> public void NotifyMainInstance(string[] args) { if (OtherInstanceStarted != null) { Type type = typeof(StartupEventArgs); ConstructorInfo constructor = type.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, Type.EmptyTypes, null); StartupEventArgs e = (StartupEventArgs)constructor.Invoke(null); FieldInfo argsField = type.GetField("_args", BindingFlags.Instance | BindingFlags.NonPublic); Debug.Assert(argsField != null); argsField.SetValue(e, args); OtherInstanceStarted(null, e); } } } }
做爲標記答案的參考,代碼C#.NET單一實例應用程序是一個很好的開始。
可是,我發現當已經存在的實例打開一個模式對話框時,不管該對話框是託管對話框(例如另外一種窗體,如「關於」框)仍是非託管對話框(例如,即便使用標準的.NET類,也可使用OpenFileDialog。 使用原始代碼,主窗體被激活,可是模態窗體保持不活動狀態,這看起來很奇怪,此外用戶必須單擊它才能繼續使用該應用程序。
所以,我已經建立了SingleInstance實用程序類來爲Winforms和WPF應用程序自動處理全部這些。
Winforms :
1)像這樣修改Program類:
static class Program { public static readonly SingleInstance Singleton = new SingleInstance(typeof(Program).FullName); [STAThread] static void Main(string[] args) { // NOTE: if this always return false, close & restart Visual Studio // this is probably due to the vshost.exe thing Singleton.RunFirstInstance(() => { SingleInstanceMain(args); }); } public static void SingleInstanceMain(string[] args) { // standard code that was in Main now goes here Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } }
2)像這樣修改主窗口類:
public partial class Form1 : Form { public Form1() { InitializeComponent(); } protected override void WndProc(ref Message m) { // if needed, the singleton will restore this window Program.Singleton.OnWndProc(this, m, true); // TODO: handle specific messages here if needed base.WndProc(ref m); } }
WPF:
1)像這樣修改App頁面(並確保將其構建操做設置爲page以可以從新定義Main方法):
public partial class App : Application { public static readonly SingleInstance Singleton = new SingleInstance(typeof(App).FullName); [STAThread] public static void Main(string[] args) { // NOTE: if this always return false, close & restart Visual Studio // this is probably due to the vshost.exe thing Singleton.RunFirstInstance(() => { SingleInstanceMain(args); }); } public static void SingleInstanceMain(string[] args) { // standard code that was in Main now goes here App app = new App(); app.InitializeComponent(); app.Run(); } }
2)像這樣修改主窗口類:
public partial class MainWindow : Window { private HwndSource _source; public MainWindow() { InitializeComponent(); } protected override void OnSourceInitialized(EventArgs e) { base.OnSourceInitialized(e); _source = (HwndSource)PresentationSource.FromVisual(this); _source.AddHook(HwndSourceHook); } protected virtual IntPtr HwndSourceHook(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) { // if needed, the singleton will restore this window App.Singleton.OnWndProc(hwnd, msg, wParam, lParam, true, true); // TODO: handle other specific message return IntPtr.Zero; }
這是實用程序類:
using System; using System.ComponentModel; using System.Runtime.InteropServices; using System.Threading; namespace SingleInstanceUtilities { public sealed class SingleInstance { private const int HWND_BROADCAST = 0xFFFF; [DllImport("user32.dll")] private static extern bool PostMessage(IntPtr hwnd, int msg, IntPtr wparam, IntPtr lparam); [DllImport("user32.dll", CharSet = CharSet.Unicode)] private static extern int RegisterWindowMessage(string message); [DllImport("user32.dll")] private static extern bool SetForegroundWindow(IntPtr hWnd); public SingleInstance(string uniqueName) { if (uniqueName == null) throw new ArgumentNullException("uniqueName"); Mutex = new Mutex(true, uniqueName); Message = RegisterWindowMessage("WM_" + uniqueName); } public Mutex Mutex { get; private set; } public int Message { get; private set; } public void RunFirstInstance(Action action) { RunFirstInstance(action, IntPtr.Zero, IntPtr.Zero); } // NOTE: if this always return false, close & restart Visual Studio // this is probably due to the vshost.exe thing public void RunFirstInstance(Action action, IntPtr wParam, IntPtr lParam) { if (action == null) throw new ArgumentNullException("action"); if (WaitForMutext(wParam, lParam)) { try { action(); } finally { ReleaseMutex(); } } } public static void ActivateWindow(IntPtr hwnd) { if (hwnd == IntPtr.Zero) return; FormUtilities.ActivateWindow(FormUtilities.GetModalWindow(hwnd)); } public void OnWndProc(IntPtr hwnd, int m, IntPtr wParam, IntPtr lParam, bool restorePlacement, bool activate) { if (m == Message) { if (restorePlacement) { WindowPlacement placement = WindowPlacement.GetPlacement(hwnd, false); if (placement.IsValid && placement.IsMinimized) { const int SW_SHOWNORMAL = 1; placement.ShowCmd = SW_SHOWNORMAL; placement.SetPlacement(hwnd); } } if (activate) { SetForegroundWindow(hwnd); FormUtilities.ActivateWindow(FormUtilities.GetModalWindow(hwnd)); } } } #if WINFORMS // define this for Winforms apps public void OnWndProc(System.Windows.Forms.Form form, int m, IntPtr wParam, IntPtr lParam, bool activate) { if (form == null) throw new ArgumentNullException("form"); if (m == Message) { if (activate) { if (form.WindowState == System.Windows.Forms.FormWindowState.Minimized) { form.WindowState = System.Windows.Forms.FormWindowState.Normal; } form.Activate(); FormUtilities.ActivateWindow(FormUtilities.GetModalWindow(form.Handle)); } } } public void OnWndProc(System.Windows.Forms.Form form, System.Windows.Forms.Message m, bool activate) { if (form == null) throw new ArgumentNullException("form"); OnWndProc(form, m.Msg, m.WParam, m.LParam, activate); } #endif public void ReleaseMutex() { Mutex.ReleaseMutex(); } public bool WaitForMutext(bool force, IntPtr wParam, IntPtr lParam) { bool b = PrivateWaitForMutext(force); if (!b) { PostMessage((IntPtr)HWND_BROADCAST, Message, wParam, lParam); } return b; } public bool WaitForMutext(IntPtr wParam, IntPtr lParam) { return WaitForMutext(false, wParam, lParam); } private bool PrivateWaitForMutext(bool force) { if (force) return true; try { return Mutex.WaitOne(TimeSpan.Zero, true); } catch (AbandonedMutexException) { return true; } } } // NOTE: don't add any field or public get/set property, as this must exactly map to Windows' WINDOWPLACEMENT structure [StructLayout(LayoutKind.Sequential)] public struct WindowPlacement { public int Length { get; set; } public int Flags { get; set; } public int ShowCmd { get; set; } public int MinPositionX { get; set; } public int MinPositionY { get; set; } public int MaxPositionX { get; set; } public int MaxPositionY { get; set; } public int NormalPositionLeft { get; set; } public int NormalPositionTop { get; set; } public int NormalPositionRight { get; set; } public int NormalPositionBottom { get; set; } [DllImport("user32.dll", SetLastError = true)] private static extern bool SetWindowPlacement(IntPtr hWnd, ref WindowPlacement lpwndpl); [DllImport("user32.dll", SetLastError = true)] private static extern bool GetWindowPlacement(IntPtr hWnd, ref WindowPlacement lpwndpl); private const int SW_SHOWMINIMIZED = 2; public bool IsMinimized { get { return ShowCmd == SW_SHOWMINIMIZED; } } public bool IsValid { get { return Length == Marshal.SizeOf(typeof(WindowPlacement)); } } public void SetPlacement(IntPtr windowHandle) { SetWindowPlacement(windowHandle, ref this); } public static WindowPlacement GetPlacement(IntPtr windowHandle, bool throwOnError) { WindowPlacement placement = new WindowPlacement(); if (windowHandle == IntPtr.Zero) return placement; placement.Length = Marshal.SizeOf(typeof(WindowPlacement)); if (!GetWindowPlacement(windowHandle, ref placement)) { if (throwOnError) throw new Win32Exception(Marshal.GetLastWin32Error()); return new WindowPlacement(); } return placement; } } public static class FormUtilities { [DllImport("user32.dll")] private static extern IntPtr GetWindow(IntPtr hWnd, int uCmd); [DllImport("user32.dll", SetLastError = true)] private static extern IntPtr SetActiveWindow(IntPtr hWnd); [DllImport("user32.dll")] private static extern bool IsWindowVisible(IntPtr hWnd); [DllImport("kernel32.dll")] public static extern int GetCurrentThreadId(); private delegate bool EnumChildrenCallback(IntPtr hwnd, IntPtr lParam); [DllImport("user32.dll")] private static extern bool EnumThreadWindows(int dwThreadId, EnumChildrenCallback lpEnumFunc, IntPtr lParam); private class ModalWindowUtil { private const int GW_OWNER = 4; private int _maxOwnershipLevel; private IntPtr _maxOwnershipHandle; private bool EnumChildren(IntPtr hwnd, IntPtr lParam) { int level = 1; if (IsWindowVisible(hwnd) && IsOwned(lParam, hwnd, ref level)) { if (level > _maxOwnershipLevel) { _maxOwnershipHandle = hwnd; _maxOwnershipLevel = level; } } return true; } private static bool IsOwned(IntPtr owner, IntPtr hwnd, ref int level) { IntPtr o = GetWindow(hwnd, GW_OWNER); if (o == IntPtr.Zero) return false; if (o == owner) return true; level++; return IsOwned(owner, o, ref level); } public static void ActivateWindow(IntPtr hwnd) { if (hwnd != IntPtr.Zero) { SetActiveWindow(hwnd); } } public static IntPtr GetModalWindow(IntPtr owner) { ModalWindowUtil util = new ModalWindowUtil(); EnumThreadWindows(GetCurrentThreadId(), util.EnumChildren, owner); return util._maxOwnershipHandle; // may be IntPtr.Zero } } public static void ActivateWindow(IntPtr hwnd) { ModalWindowUtil.ActivateWindow(hwnd); } public static IntPtr GetModalWindow(IntPtr owner) { return ModalWindowUtil.GetModalWindow(owner); } } }
從這裏 。
跨進程Mutex的常見用法是確保一次只能運行程序實例。 這是完成的過程:
class OneAtATimePlease { // Use a name unique to the application (eg include your company URL) static Mutex mutex = new Mutex (false, "oreilly.com OneAtATimeDemo"); static void Main() { // Wait 5 seconds if contended – in case another instance // of the program is in the process of shutting down. if (!mutex.WaitOne(TimeSpan.FromSeconds (5), false)) { Console.WriteLine("Another instance of the app is running. Bye!"); return; } try { Console.WriteLine("Running - press Enter to exit"); Console.ReadLine(); } finally { mutex.ReleaseMutex(); } } }
Mutex的一個好功能是,若是應用程序在不首先調用ReleaseMutex的狀況下終止,則CLR將自動釋放Mutex。