Florian Geisenhof

Anwendung nur 1x ausführen
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;
}

Posted: Okt 26 2010, 12:51 von phlow666 | mit 3 comment(s)
Abgelegt unter:
UnhandledException-Event
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);
}

Posted: Okt 26 2010, 12:49 von phlow666 | mit 2 comment(s)
Abgelegt unter: ,
Willkommen in meinem neuen Blog
Und los gehts....
Posted: Okt 25 2010, 12:50 von phlow666 | mit no comments
Abgelegt unter: