这是我迄今为止实现创建单个实例 WPF 应用程序的代码:
#region Using Directives
using System;
using System.Globalization;
using System.Reflection;
using System.Threading;
using System.Windows;
using System.Windows.Interop;
#endregion
namespace MyWPF
{
public partial class MainApplication : Application, IDisposable
{
#region Members
private Int32 m_Message;
private Mutex m_Mutex;
#endregion
#region Methods: Functions
private IntPtr HandleMessages(IntPtr handle, Int32 message, IntPtr wParameter, IntPtr lParameter, ref Boolean handled)
{
if (message == m_Message)
{
if (MainWindow.WindowState == WindowState.Minimized)
MainWindow.WindowState = WindowState.Normal;
Boolean topmost = MainWindow.Topmost;
MainWindow.Topmost = true;
MainWindow.Topmost = topmost;
}
return IntPtr.Zero;
}
private void Dispose(Boolean disposing)
{
if (disposing && (m_Mutex != null))
{
m_Mutex.ReleaseMutex();
m_Mutex.Close();
m_Mutex = null;
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
#region Methods: Overrides
protected override void OnStartup(StartupEventArgs e)
{
Assembly assembly = Assembly.GetExecutingAssembly();
Boolean mutexCreated;
String mutexName = String.Format(CultureInfo.InvariantCulture, "Local\\{{{0}}}{{{1}}}", assembly.GetType().GUID, assembly.GetName().Name);
m_Mutex = new Mutex(true, mutexName, out mutexCreated);
m_Message = NativeMethods.RegisterWindowMessage(mutexName);
if (!mutexCreated)
{
m_Mutex = null;
NativeMethods.PostMessage(NativeMethods.HWND_BROADCAST, m_Message, IntPtr.Zero, IntPtr.Zero);
Current.Shutdown();
return;
}
base.OnStartup(e);
MainWindow window = new MainWindow();
MainWindow = window;
window.Show();
HwndSource.FromHwnd((new WindowInteropHelper(window)).Handle).AddHook(new HwndSourceHook(HandleMessages));
}
protected override void OnExit(ExitEventArgs e)
{
Dispose();
base.OnExit(e);
}
#endregion
}
}
一切都工作得非常完美...但我还有一些疑虑,希望能收到您的建议,提高我的方法。
1)由于我正在使用Mutex
,所以Code Analysis要求我实现IDisposable
接口。我的Dispose()
实现足够好吗?因为它永远不会被调用,所以我应该避免使用它吗?
2)在多线程情况下,最好使用m_Mutex = new Mutex(true, mutexName, out mutexCreated);
并检查结果,还是使用m_Mutex = new Mutex(false, mutexName);
然后检查m_Mutex.WaitOne(TimeSpan.Zero, false);
?
3)RegisterWindowMessage
API调用应返回UInt32
,但HwndSourceHook
仅接受Int32
作为消息值。我是否应该担心意外的行为(如大于Int32.MaxValue
的结果)?
4)在OnStartup
覆盖中,即使另一个实例已经在运行并且我将关闭应用程序,我是否应该执行base.OnStartup(e);
?
5)有没有更好的方法将现有实例置于顶部,而不需要设置Topmost
值?也许是Activate()
?
6)您是否能看到我的方法中的任何缺陷?例如关于多线程、异常处理等等。例如...如果我的应用程序在OnStartup
和OnExit
之间崩溃会发生什么?