Il codice che segue permette di avviare una singola istanza di un programma su windows CE
scritto in c# funziona correttamente su Compact Framework 2
La fonte è:
http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=726497&SiteID=1
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Text;
namespace DevWEB
{
static class Program
{
[DllImport("coredll.dll", SetLastError = true)]
private static extern IntPtr CreateEvent(IntPtr lpEventAttributes, bool bManualReset, bool bInitialState, string lpName);
[DllImport("coredll.dll", SetLastError = true)]
private static extern bool CloseHandle(IntPtr hObject);
private const int ERROR_ALREADY_EXISTS = 183;
[DllImport("coredll.dll", SetLastError = true)]
private static extern IntPtr FindWindow(string className, string wndName);
[MTAThread]
static void Main()
{
string path = System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase;
IntPtr handle = CreateEvent(IntPtr.Zero, false, false, path);
int error = System.Runtime.InteropServices.Marshal.GetLastWin32Error();
if (handle != null && (error != ERROR_ALREADY_EXISTS))
{
Application.Run(new Memor.GUI.MainForm());
}
else
{
// Upon startup CF implementation of mscoree looks for a window with a class #NETCF_AGL_PARK
// and title set to the current process executable full path (\Program Files\MyApp\MyApp.exe).
// If found, the runtime presumes that the current application is already running. In this case
// it will be reactivated. To do this the abovementioned window is sent a message 0x8001,
// and then the new instance quits.
// The CF 2.0 is almost identical: This is only when you start the app multiple times before the Form has
// been appeared.
IntPtr hWnd = FindWindow("#NETCF_AGL_PARK_" + path, string.Empty);
if (hWnd != IntPtr.Zero)
{
Microsoft.WindowsCE.Forms.Message msg = Microsoft.WindowsCE.Forms.Message.Create(hWnd, (int)0x8001, (IntPtr)0, (IntPtr)0);
Microsoft.WindowsCE.Forms.MessageWindow.SendMessage(ref msg);
}
}
CloseHandle(handle);
}
}
}