Um sicherzustellen, dass eine Anwendung auf einem PC nur 1x ausgeführt wird, bietet sich folgende Möglichkeit an.
private const string MyApplicationMutex = "MY_APPLICATION_MUTEX";
private static void Main()
{
if (IsApplicationRunning())
return;
var mutex = new Mutex(true, MyApplicationMutex);
GC.KeepAlive(mutex);
Application.Run(new MyForm());
}
public static bool IsApplicationRunning()
{
try
{
Mutex mutex = Mutex.OpenExisting(MyApplicationMutex);
mutex.Close();
return true;
}
catch (Exception ex)
{
//Mein ExceptionHandling
}
return false;
}
Entwickelt man eine Anwendung, kann es schon mal vorkommen, dass man vergisst eine Exception zu fangen. Dem kann anhand eines Events abeholfen werden.
Es gibt in der Klasse
AppDomain das Property
CurrentDomain. Diese
CurrentDomain hat den Event
UnhandledException. Dieses Event abonniere ich wie folgt in meiner
Main.
private static void Main()
{
var currentDomain = AppDomain.CurrentDomain;
currentDomain.UnhandledException += CurrentDomainUnhandledException;
Application.Run(new MyForm());
}Dieses Event wird dann mit folgender Methode in das Windows-Ereignislog geschrieben.
private static void CurrentDomainUnhandledException(object sender, UnhandledExceptionEventArgs e)
{
const string sSource = "MeineAnwendung";
const string sLog = "Application";
var sb = new StringBuilder();
sb.AppendLine(String.Format("{0} UnhandledException:", sSource));
if (e != null)
{
if (e.ExceptionObject != null)
sb.AppendLine(String.Format("ExceptionObject --> {0}", e.ExceptionObject));
}
if (sender != null)
sb.AppendLine(String.Format("Sender --> {0}", sender));
var sEvent = sb.ToString();
if (!EventLog.SourceExists(sSource))
EventLog.CreateEventSource(sSource, sLog);
EventLog.WriteEntry(sSource, sEvent, EventLogEntryType.Error, 666);
}