vez veces una que programa mismo mas formulario evitar ejecute consola cerrar aplicación aplicacion abrir abra c# .net windows winforms

c# - veces - evitar que una aplicación java se ejecute mas de una vez



¿Cómo forzar a la aplicación C#.net a ejecutar solo una instancia en Windows? (4)

Esto es lo que uso en mi aplicación:

static void Main() { bool mutexCreated = false; System.Threading.Mutex mutex = new System.Threading.Mutex( true, @"Local/slimCODE.slimKEYS.exe", out mutexCreated ); if( !mutexCreated ) { if( MessageBox.Show( "slimKEYS is already running. Hotkeys cannot be shared between different instances. Are you sure you wish to run this second instance?", "slimKEYS already running", MessageBoxButtons.YesNo, MessageBoxIcon.Question ) != DialogResult.Yes ) { mutex.Close(); return; } } // The usual stuff with Application.Run() mutex.Close(); }

Posible duplicado:
¿Cuál es la forma correcta de crear una aplicación de instancia única?

¿Cómo forzar a la aplicación C # .net a ejecutar solo una instancia en Windows?


Otra forma de instancia única de una aplicación es verificar sus sumas de hash. después de jugar con mutex (no funcionó como yo quería) lo conseguí trabajando de esta manera:

[DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] static extern bool SetForegroundWindow(IntPtr hWnd); public Main() { InitializeComponent(); Process current = Process.GetCurrentProcess(); string currentmd5 = md5hash(current.MainModule.FileName); Process[] processlist = Process.GetProcesses(); foreach (Process process in processlist) { if (process.Id != current.Id) { try { if (currentmd5 == md5hash(process.MainModule.FileName)) { SetForegroundWindow(process.MainWindowHandle); Environment.Exit(0); } } catch (/* your exception */) { /* your exception goes here */ } } } } private string md5hash(string file) { string check; using (FileStream FileCheck = File.OpenRead(file)) { MD5 md5 = new MD5CryptoServiceProvider(); byte[] md5Hash = md5.ComputeHash(FileCheck); check = BitConverter.ToString(md5Hash).Replace("-", "").ToLower(); } return check; }

solo verifica las sumas de md5 por id de proceso.

si se encuentra una instancia de esta aplicación, enfoca la aplicación en ejecución y sale por sí misma.

puede cambiarle el nombre o hacer lo que quiera con su archivo. no se abrirá dos veces si el hash md5 es el mismo.

¿alguien tiene sugerencias para eso? Sé que se responde, pero tal vez alguien está buscando una alternativa mutex.


Prefiero una solución mutex similar a la siguiente. De esta forma, vuelve a centrarse en la aplicación si ya está cargada

using System.Threading; [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] static extern bool SetForegroundWindow(IntPtr hWnd); /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { bool createdNew = true; using (Mutex mutex = new Mutex(true, "MyApplicationName", out createdNew)) { if (createdNew) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new MainForm()); } else { Process current = Process.GetCurrentProcess(); foreach (Process process in Process.GetProcessesByName(current.ProcessName)) { if (process.Id != current.Id) { SetForegroundWindow(process.MainWindowHandle); break; } } } } }


para forzar la ejecución de solo un instance de un programa en .net (C #) use este código en el archivo program.cs:

public static Process PriorProcess() // Returns a System.Diagnostics.Process pointing to // a pre-existing process with the same name as the // current one, if any; or null if the current process // is unique. { Process curr = Process.GetCurrentProcess(); Process[] procs = Process.GetProcessesByName(curr.ProcessName); foreach (Process p in procs) { if ((p.Id != curr.Id) && (p.MainModule.FileName == curr.MainModule.FileName)) return p; } return null; }

y el folowing:

[STAThread] static void Main() { if (PriorProcess() != null) { MessageBox.Show("Another instance of the app is already running."); return; } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form()); }