3

由于我尝试了多种方法来阻止在.net compact framework 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 的类。

4

1 回答 1

6

你的代码几乎没问题。唯一缺少的是删除应用程序出口并将当前正在运行的实例置于顶部所需的代码放入其中。我过去这样做过,因此您无需禁用或隐藏图标,您只需检测已经运行的实例并将其置于前台即可。

编辑:

这里有一些代码片段:

[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(包括评论)

在 Compact Framework 中制作单实例应用程序的最佳方式是什么?

于 2011-09-20T07:24:30.217 回答