Entwickler-Ecke

Basistechnologien - Programm nicht mehrmals starten


_Joe_ - Fr 04.12.09 14:28
Titel: Programm nicht mehrmals starten
Hallo,

ich bin zur Zeit auf der Suche nach einer Möglichkeit ein Programm nur einmal zu starten. Also wenn ich ein zweites mal drauf drücke soll es nichts machen außer Abbrechen. Das ganze Funktioniert auch recht gut aber vielleicht gibt es noch was besser?

sowas habe ich gefunden:
Quelle: http://dotnet-snippets.de/dns/programm-nicht-mehrmals-starten-kernel32dll-SID357.aspx

C#-Quelltext
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
static class Program {
       
[DllImport("kernel32.dll", SetLastError = true)]
static extern IntPtr CreateMutex( IntPtr lpMutexAttributes, bool bInitialOwner, string lpName );

[DllImport("kernel32.dll")]
static extern bool ReleaseMutex( IntPtr hMutex );

const int PRG_RUNNING = 183;

[STAThread]
static void Main() {
  IntPtr mutex = IntPtr.Zero;

  try {
    mutex = CreateMutex(IntPtr.Zero, false, Application.ProductName);

    if (mutex != IntPtr.Zero) {
      if (Marshal.GetLastWin32Error() != PRG_RUNNING) {
        // Programm läuft noch nicht, kann also richtig gestartet werden
        // Bitte durch eigene Form ersetzen
        Application.Run(new Form1());
      } else {
        MessageBox.Show("Programm wurde bereits gestartet!""Info", MessageBoxButtons.OK, MessageBoxIcon.Error);
      }
    }
  } catch (Exception e) {
    MessageBox.Show(e.Message, "Fehler", MessageBoxButtons.OK, MessageBoxIcon.Error);
  } finally {
    // und wieder freigeben
    if (mutex != IntPtr.Zero) {
      ReleaseMutex(mutex);
    }
  }
   
}
}


Kha - Fr 04.12.09 15:34

user profile icon_Joe_ hat folgendes geschrieben Zum zitierten Posting springen:
sowas habe ich gefunden:
Quelle: http://dotnet-snippets.de/dns/programm-nicht-mehrmals-starten-kernel32dll-SID357.aspx
:gruebel:
Wie herbivore in den Kommentaren schreibt, geht es viel einfacher, und direkt darunter findest du auch diesen Link: http://dotnet-snippets.de/dns/c-programm-nicht-mehrmals-starten-net-SID358.aspx :zwinker:


_Joe_ - Fr 04.12.09 17:15

Lesen ist eben doch Macht, danke