我有一个应用程序,我已成功应用互斥锁,以确保只有一个应用程序实例一次运行。它几乎是解决方案的直接副本:What is the correct way to create a single-instance application?
问题在于第二个实例的命令行参数。我想将它传递给第一个实例,我决定尝试使用MemoryMappedFile来实现这一目标。我已经修改了上面的互斥解决方案来尝试实现这一点,但是在尝试" OpenExisting"时我得到了一个FileNotFoundException。我尝试了许多不同的解决方案来尝试解决这个问题,但似乎都没有。我做错了什么? (我打算把这个arg写给MMF,但是现在我只是用二进制文件作为测试):
namespace MyApplication
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
static Mutex mutex = new Mutex(true, "{E6FD8A59-1754-4EA5-8996-2F1BC3AC5D87}");
[STAThread]
static void Main(string[] args)
{
if (mutex.WaitOne(TimeSpan.Zero, true))
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
if (args.Length == 1)
{
Application.Run(new Form1(args[0]));
}
else
{
Application.Run(new Form1());
}
mutex.ReleaseMutex();
}
else
{
NativeMethods.PostMessage((IntPtr)NativeMethods.HWND_BROADCAST, NativeMethods.WM_SHOWME, IntPtr.Zero, IntPtr.Zero);
if (args.Length == 1)
{
if (File.Exists(args[0]))
{
MemoryMappedFile mmf = MemoryMappedFile.CreateNew("filetoopen", 10000);
using (MemoryMappedViewStream stream = mmf.CreateViewStream())
{
BinaryWriter writer = new BinaryWriter(stream);
writer.Write(1);
}
NativeMethods.PostMessage((IntPtr)NativeMethods.HWND_BROADCAST, NativeMethods.WM_OPENFILE, IntPtr.Zero, IntPtr.Zero);
}
}
}
}
}
internal class NativeMethods
{
public const int HWND_BROADCAST = 0xffff;
public static readonly int WM_SHOWME = RegisterWindowMessage("WM_SHOWME");
public static readonly int WM_OPENFILE = RegisterWindowMessage("WM_OPENFILE");
[DllImport("user32.dll")]
public static extern bool PostMessage(IntPtr hwnd, int msg, IntPtr wparam, IntPtr lparam);
[DllImport("user32.dll")]
public static extern int RegisterWindowMessage(string message);
}
}
Form1中的相关代码:
protected override void WndProc(ref Message m)
{
if (m.Msg == NativeMethods.WM_SHOWME)
{
ShowMe(); //This works fine. Method excluded.
}
else if (m.Msg == NativeMethods.WM_OPENFILE)
{
try
{
MemoryMappedFile mmf = MemoryMappedFile.OpenExisting("Global\\filetoopen");
using (MemoryMappedViewStream stream = mmf.CreateViewStream())
{
BinaryReader reader = new BinaryReader(stream);
MessageBox.Show(reader.ReadBoolean().ToString());
}
}
catch (FileNotFoundException)
{
MessageBox.Show("File not found.");
}
}
base.WndProc(ref m);
}