Sprache: C#
Aus den tiefen meiner Sourcen wieder mal ein kleiner Snippet
Es könnte ja mal passieren, dass Ihr nicht wollt das euer Programm mehrmals gestartet wird.
Hier ist die Lösung per Kernel32.dll
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);
}
}
}
}
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);
}
}
}
}
Alte URL:
/snippet/programm-nicht-mehrmals-starten-kernel32-dll/357
Mit der Mutex- oder der EventWaitHandle-Klasse stehen in .NET direkt die nötigen Methoden bereit. Ein Durchgriff mit DllImport auf Win32 nicht nicht (mehr) nötig.