是否可以完全阻止.NET Compact Framework上的多个实例?

时间:2011-09-19 09:32:21

标签: c# .net compact-framework multiple-instances handheld

因为我尝试了许多方法来停止在.net紧凑框架3.5上运行的手持设备上的多实例问题。

目前,我通过创建“Mutex”获得解决方案,并检查是否正在运行相同的进程。我把这个语句放在“Program.cs”中,这将在程序启动时第一次执行。

但我认为这不是我的问题,因为我得到了用户的请求,他们需要在运行时禁用“程序图标”。

我理解用户的观点,即有时他们可能会在短时间内“打开”该程序多次或多次。所以,如果它仍然能够“打开”。这意味着程序需要自己初始化,最终可能会失败。是否可以绝对阻止多个实例?还是有另一种没有编程的方式,比如在Windows CE上编辑注册表?


这是我的源代码:

bool firstInstance;
NamedMutex mutex = new NamedMutex(false, "MyApp.exe", out firstInstance);

if (!firstInstance)
{
    //DialogResult dialogResult = MessageBox.Show("Process is already running...");
    Application.Exit();
}

NamedMutex是OpenNetCF的类。

1 个答案:

答案 0 :(得分:5)

你的代码几乎没问题。唯一遗漏的是删除应用程序出口并在其中放入将当前运行的实例置于最前面所需的代码。我之前做过这个,所以你不需要禁用或隐藏你只是检测已经运行的实例的图标并把它带到前台。

修改

这里有一些代码片段:

[DllImport("coredll.dll")]
private static extern IntPtr FindWindow(IntPtr className, string windowName);

[DllImport("coredll.dll")]
internal static extern int SetForegroundWindow(IntPtr hWnd);

[DllImport("coredll.dll")]
private static extern bool SetWindowPos(IntPtr hwnd, int hwnd2, int x,int y, int cx, int cy, int uFlags);

if (IsInstanceRunning())
{
    IntPtr h = FindWindow(IntPtr.Zero, "Form1");
    SetForegroundWindow(h);
    SetWindowPos(h, 0, 0, 0, Screen.PrimaryScreen.Bounds.Width,Screen.PrimaryScreen.Bounds.Height, 0x0040);

    return;
}

查看这些链接以获取更多信息...

http://www.nesser.org/blog/archives/56(包括评论)

What is the best way to make a single instance application in Compact Framework?