请教大牛一个问题(关于如何防止程序重复打开的问题)
开发环境VS2008 CMP .NET 2.0 下的一个wince 6.0程序(手持pda的条码程序)
遇到问题:触摸屏的话客户经常会重复打开程序,所以我现在要防止程序的重复打开。但是由于是缩减版的。net 2.0 很多方法没有,互斥体也没有。
所以请教各位了,如果解决,给个思路,指点一下也可以。先谢谢大家了。
ps:我用的是C#开发的。
[最优解释]
以上是普通PC版本,如果是WinCE下的话,函数DllImport需要从coredll.dll里面导出,而不是user32.dll
[其他解释]
1 /// Summary description for ProcessUtils.
2 public static class ProcessUtils
3 {
4 private static Mutex mutex = null;
5
6 /// Determine if the current process is already running
7 public static bool ThisProcessIsAlreadyRunning()
8 {
9 // Only want to call this method once, at startup.
Debug.Assert(mutex == null);
// createdNew needs to be false in .Net 2.0, otherwise, if another instance of
// this program is running, the Mutex constructor will block, and then throw
// an exception if the other instance is shut down.
bool createdNew = false;
mutex = new Mutex(false, Application.ProductName, out createdNew);
Debug.Assert(mutex != null);
return !createdNew;
}
[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll")]
static extern bool IsIconic(IntPtr hWnd);
[DllImport("user32.dll")]
static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
const int SW_RESTORE = 9;
[DllImport("user32.dll")]
static extern IntPtr GetLastActivePopup(IntPtr hWnd);
[DllImport("user32.dll")]
static extern bool IsWindowEnabled(IntPtr hWnd);
/// Set focus to the previous instance of the specified program.
public static void SetFocusToPreviousInstance(string windowCaption)
{
// Look for previous instance of this program.
IntPtr hWnd = FindWindow(null, windowCaption);
// If a previous instance of this program was found...
if (hWnd != null)
{
// Is it displaying a popup window?
IntPtr hPopupWnd = GetLastActivePopup(hWnd);
// If so, set focus to the popup window. Otherwise set focus
// to the program's main window.
if (hPopupWnd != null && IsWindowEnabled(hPopupWnd))
{
hWnd = hPopupWnd;
}
SetForegroundWindow(hWnd);
// If program is minimized, restore it.
if (IsIconic(hWnd))
{
ShowWindow(hWnd, SW_RESTORE);
}
}
}
}
this.Close();
InitializeComponent();
SetSyncTime();
}
else
{
FrmConfirmMsg msgs = new FrmConfirmMsg("MC手持版-打开重复", "程序重复打开了", string.Empty);
msgs.ShowDialog();
this.Close();
return;
}
//CommonFunc.SetFocusToPreviousInstance("mc3000");
//InitializeComponent();
//SetSyncTime();
[其他解释]
跟进去调,看哪句不行
[其他解释]