Since I've try many ways to stop the multiple instance problem on handheld device which running on .net compact framework 3.5.
Currently , I got the solution by create "Mutex" and check if there is the same process is running. I put this statement in "Program.cs" which will executed at first time when program start.
But i think it's not shoot my problems cause I got request fr开发者_开发知识库om user that they need to disable the "program icon" while it's running.
I understand the user's point that sometime they maybe "Open" the program multiple times or more within short period. So , If it still able to "Open". That mean the program will need to initial itself and maybe going fail finally. Is it possible to absolutely prevent the multiple instance ? or is there another way without programming like edit the registry on Windows CE ?
Here is my source code:
bool firstInstance;
NamedMutex mutex = new NamedMutex(false, "MyApp.exe", out firstInstance);
if (!firstInstance)
{
//DialogResult dialogResult = MessageBox.Show("Process is already running...");
Application.Exit();
}
NamedMutex is class from OpenNetCF.
Your code is almost fine. only missing thing is to remove the application exit and put in there the code needed to bring current running instance on top. i did this in the past so you do not need to disable or hide the icon you simply detect the already running instance and bring it on foreground.
Edit:
here some code snippet:
[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;
}
check these links for more info...
http://www.nesser.org/blog/archives/56 (including comments)
What is the best way to make a single instance application in Compact Framework?
精彩评论