private static readonly Guid SingleInstanceGuid = new Guid ( "1DADFDD1-DDD1-4390-95B9-5852CFB39807" );
private const int ERROR_ALREADY_EXISTS = 183; // error code returned in case of an already existing event
[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);
[DllImport ( "coredll.dll" , SetLastError = true )]
private static extern IntPtr FindWindow ( string className, string wndName);
public static bool IsSingleInstance () {
var path = Assembly .GetExecutingAssembly (). GetName (). CodeBase;
handle = CreateEvent ( IntPtr .Zero, false , false , SingleInstanceGuid.ToString ());
var error = Marshal.GetLastWin32Error ();
// If the event already exists, find the running application and send it the command 0x8001, which should re-activate the application
if (error == ERROR_ALREADY_EXISTS) {
var hWnd = FindWindow ( "#NETCF_AGL_PARK_" + path, string .Empty);
if (hWnd! = IntPtr .Zero) {
var msg = Message.Create (hWnd, 0x8001, ( IntPtr ) 0, ( IntPtr ) 0);
MessageWindow.SendMessage ( ref msg);
}
return false ;
}
return true ;
}
public static void CloseHandle () {
CloseHandle (handle);
}
if (! SingleInstance.IsSingleInstance ()) {
return ;
}
try {
Application.Run ( new Form1 ());
} catch (Exception ex) {
} finally {
SingleInstance.CloseHandle ();
} * This source code was highlighted with Source Code Highlighter .
Source: https://habr.com/ru/post/30241/
All Articles