Wie stell ich es an, dass mein Programm sich nur einmal starten lässt?

tass

Mitglied
Hallo,

kann mir jemand sagen wie ich es hinbekomme, dass sich mein Programm nur einmal starten lässen. Am besten wärs, wenn bei nochmaligem Aufruf des Programmes, der schon geöffnete Prozess aktiviert wird.

Ich habe zwar schon eine Lösung dafür, aber die braucht viel zuviel Zeit da er alle Prozesse die bereits laufen erst ausliest und dann mit meinem vergleicht.
Ich will nicht jedesmal so lang warten, bis er abgecheckt hat ob das Programm schon läuf.

hier mal mein bisheriger Code

Code:
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Reflection; 

namespace NOnly1Inst
{
	/// <summary>
	/// Zusammenfassung für Class1.
	/// </summary>
	public class COnly1Inst
	{
		public COnly1Inst()
		{
		
		}

		public int IsInit()
		{
			//Get the running instance.
			Process instance = RunningInstance();
			if (instance == null)
			{
				//There isn't another instance, show our form.
				return 1;
			}
			else
			{
				//There is another instance of this process.
				HandleRunningInstance(instance);
			}
			return 0;
		}


		public static Process RunningInstance()
		{
			Process current = Process.GetCurrentProcess();
			Process[] processes = Process.GetProcessesByName (current.ProcessName);

			//Loop through the running processes in with the same name
			foreach (Process process in processes)
			{
				//Ignore the current process
				if (process.Id != current.Id)
				{
					//Make sure that the process is running from the exe file.
					//if (Assembly.GetExecutingAssembly().Location.Replace("/", "\\") ==
					//	current.MainModule.FileName)
					//{
						//Return the other process instance.
						return process;
					//}
				}
			}

			//No other instance was found, return null.
			return null;
		}


		public static void HandleRunningInstance(Process instance)
		{
			//Make sure the window is not minimized or maximized
			ShowWindowAsync (instance.MainWindowHandle , WS_SHOWNORMAL);

			//Set the real intance to foreground window
			SetForegroundWindow (instance.MainWindowHandle);
		}


		[DllImport("User32.dll")] 
		private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);

		[DllImport("User32.dll")] 
		private static extern bool SetForegroundWindow(IntPtr hWnd);
		private const int WS_SHOWNORMAL = 1;
	}
}

Gib es vielleicht eine Möglichkeit in .Net irgend ein Häkchen zu setzen das das für mich macht. Oder kennt jemand eine bessere Lösung als meine?

mfg Tass
 
Hallo!

[thread=183010]Keine mehrfache Instanz zulassen-Thread[/thread]
Kombinier das mit deiner SetForegroundWindow-Methode. Und danke für den Tipp!

MfG cosmo
 
Zurück