Ich hab eine Anwendung, die im Hintergrund die Tastatur abfragt und auf bestimmte Tastendrücke reagiert. Wenn diese Anwendung aber aus Versehen zweimal läuft, dann crasht das ganze System. Jetzt möchte ich verhindern, dass die Anwendung zweimal gestartet wird. Wie mache ich das?
Prinzipiell stimmt das, was 13thAngel schrieb, schon - aber damit bekommst Du nicht das gängige Verhalten, wie zum Beispiel bei Outlook: Dieses prüft nämlich nicht nur, ob schon eine Instanz vorhanden ist und startet nur bedingt eine neue, sondern falls schon eine Instanz läuft, wird zu dieser gewechselt!
Dazu ist dann ein bisschen mehr Aufwand nötig, eine vorgefertigte Lösung hierfür gibt es aber, nämlich auf CodeProject, die das Umschalten elegant über ein paar P/Invoke-Aufrufe erledigt.
Damit hast Du dann das Verhalten wie zB bei Outlook.
Ergänzend zu Golos Beitrag, hier mal ein interessanter Artikel inklusiv Code: http://blogs.microsoft.co.il/blogs/maxim/archive/2010/02/13/single-instance-application-manager.aspx
// code to ensure that only one copy of the software is running. try{ mutex = Mutex.OpenExisting ( mutexName ); //since it hasn’t thrown an exception, then we already have one copy of the app open. MessageBox.Show ( "A copy of the software is already open. Please check your system tray (notification area).", "My Software", MessageBoxButtons.OK, MessageBoxIcon.Information ); Environment.Exit ( 0 ); } catch{ //since we didn’t find a mutex with that name, create one mutex = new Mutex ( true, mutexName ); }