104 lines
3.4 KiB
C#
104 lines
3.4 KiB
C#
using System.Configuration;
|
|
using System.Data;
|
|
using System.Windows;
|
|
using System.Threading;
|
|
using System.Diagnostics;
|
|
using System.Runtime.InteropServices;
|
|
using System;
|
|
|
|
namespace ShortcutsHelper
|
|
{
|
|
/// <summary>
|
|
/// Interaction logic for App.xaml
|
|
/// </summary>
|
|
public partial class App : System.Windows.Application
|
|
{
|
|
private static Mutex? _mutex = null;
|
|
private const string MutexName = "ShortcutsHelper_SingleInstance_Mutex";
|
|
|
|
protected override void OnStartup(StartupEventArgs e)
|
|
{
|
|
// Intentar crear un mutex para controlar instancia única
|
|
bool createdNew;
|
|
_mutex = new Mutex(true, MutexName, out createdNew);
|
|
|
|
if (!createdNew)
|
|
{
|
|
// Ya hay una instancia ejecutándose
|
|
// Intentar activar la ventana existente
|
|
ActivateExistingWindow();
|
|
|
|
// Cerrar esta instancia
|
|
Shutdown();
|
|
return;
|
|
}
|
|
|
|
// Primera instancia, continuar normalmente
|
|
base.OnStartup(e);
|
|
}
|
|
|
|
protected override void OnExit(ExitEventArgs e)
|
|
{
|
|
// Liberar el mutex al salir
|
|
_mutex?.ReleaseMutex();
|
|
_mutex?.Dispose();
|
|
base.OnExit(e);
|
|
}
|
|
|
|
private void ActivateExistingWindow()
|
|
{
|
|
try
|
|
{
|
|
// Buscar el proceso de ShortcutsHelper que ya está ejecutándose
|
|
var currentProcess = Process.GetCurrentProcess();
|
|
var processes = Process.GetProcessesByName(currentProcess.ProcessName);
|
|
|
|
foreach (var process in processes)
|
|
{
|
|
// Saltar el proceso actual
|
|
if (process.Id == currentProcess.Id)
|
|
continue;
|
|
|
|
// Intentar activar la ventana principal del proceso
|
|
if (process.MainWindowHandle != IntPtr.Zero)
|
|
{
|
|
// Si la ventana está minimizada, restaurarla
|
|
if (IsIconic(process.MainWindowHandle))
|
|
{
|
|
ShowWindow(process.MainWindowHandle, SW_RESTORE);
|
|
}
|
|
|
|
// Traer al frente y dar foco
|
|
SetForegroundWindow(process.MainWindowHandle);
|
|
BringWindowToTop(process.MainWindowHandle);
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
// Si falla la activación, al menos mostrar un mensaje
|
|
System.Windows.MessageBox.Show($"ShortcutsHelper ya está ejecutándose. Error al activar: {ex.Message}",
|
|
"Aplicación ya en ejecución",
|
|
MessageBoxButton.OK,
|
|
MessageBoxImage.Information);
|
|
}
|
|
}
|
|
|
|
// APIs de Windows para manejo de ventanas
|
|
[DllImport("user32.dll")]
|
|
private static extern bool SetForegroundWindow(IntPtr hWnd);
|
|
|
|
[DllImport("user32.dll")]
|
|
private static extern bool BringWindowToTop(IntPtr hWnd);
|
|
|
|
[DllImport("user32.dll")]
|
|
private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
|
|
|
|
[DllImport("user32.dll")]
|
|
private static extern bool IsIconic(IntPtr hWnd);
|
|
|
|
private const int SW_RESTORE = 9;
|
|
}
|
|
}
|