Skip to content

Instantly share code, notes, and snippets.

@Platonenkov
Created May 25, 2021 10:36
Show Gist options
  • Save Platonenkov/97c655220f5281fed877fcbe6d268cb3 to your computer and use it in GitHub Desktop.
Save Platonenkov/97c655220f5281fed877fcbe6d268cb3 to your computer and use it in GitHub Desktop.
WPF Check for second Instance
public static class ApplicationInstance
{
/// <summary> Проверяет запущен ли уже экземпляр приложения </summary>
/// <returns>true - запущен, false - нет</returns>
public static bool CheckForSecondInstance()
{
var startup_path = System.Reflection.Assembly.GetEntryAssembly()?.Location;
var startup_file_name = System.IO.Path.GetFileNameWithoutExtension(startup_path);
var processes_with_same_file = Process.GetProcessesByName(startup_file_name);
return processes_with_same_file.Length > 1;
}
/// <summary> Закрывает текущее приложение </summary>
public static void CloseCurrentInstance() => Application.Current.Shutdown();
/// <summary> Проверяет запущено ли уже приложение и если запущено то не запускает новый экземпляр </summary>
public static void CheckForSecondAndClose(bool Inform = true)
{
//Проверка запущено ли приложение в другом окне
if (!CheckForSecondInstance()) return;
if(Inform)
{
var message = Properties.Resources.Application_is_running;
MessageBox.Show(message);
}
CloseCurrentInstance();//закрываем текущий экземпляр
FlashGeneralWindow();//подсвечиваем запущенный ранее экземпляр
}
/// <summary> Подсвечивает запущенный процесс </summary>
public static void FlashGeneralWindow()
{
var process = Process.GetProcessesByName(System.IO.Path.GetFileNameWithoutExtension(System.Reflection.Assembly.GetEntryAssembly()?.Location));
var top = process.FirstOrDefault(p => p.MainWindowTitle.IsNotNullOrWhiteSpace());
if(top is null) return;
FlashWindow.Flash(top.MainWindowHandle);
}
}
public static class FlashWindow
{
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool FlashWindowEx(ref FLASHWINFO pwfi);
[StructLayout(LayoutKind.Sequential)]
private struct FLASHWINFO
{
/// <summary>
/// The size of the structure in bytes.
/// </summary>
public uint cbSize;
/// <summary>
/// A Handle to the Window to be Flashed. The window can be either opened or minimized.
/// </summary>
public IntPtr hwnd;
/// <summary>
/// The Flash Status.
/// </summary>
public uint dwFlags;
/// <summary>
/// The number of times to Flash the window.
/// </summary>
public uint uCount;
/// <summary>
/// The rate at which the Window is to be flashed, in milliseconds. If Zero, the function uses the default cursor blink rate.
/// </summary>
public uint dwTimeout;
}
/// <summary>
/// Stop flashing. The system restores the window to its original stae.
/// </summary>
public const uint FLASHW_STOP = 0;
/// <summary>
/// Flash the window caption.
/// </summary>
public const uint FLASHW_CAPTION = 1;
/// <summary>
/// Flash the taskbar button.
/// </summary>
public const uint FLASHW_TRAY = 2;
/// <summary>
/// Flash both the window caption and taskbar button.
/// This is equivalent to setting the FLASHW_CAPTION | FLASHW_TRAY flags.
/// </summary>
public const uint FLASHW_ALL = 3;
/// <summary>
/// Flash continuously, until the FLASHW_STOP flag is set.
/// </summary>
public const uint FLASHW_TIMER = 4;
/// <summary>
/// Flash continuously until the window comes to the foreground.
/// </summary>
public const uint FLASHW_TIMERNOFG = 12;
/// <summary>
/// Flash the spacified Window (Form) until it recieves focus.
/// </summary>
/// <param name="win">The Window to Flash.</param>
/// <returns></returns>
public static bool Flash(IntPtr win)
{
// Make sure we're running under Windows 2000 or later
if (Win2000OrLater)
{
var fi = Create_FLASHWINFO(win, FLASHW_ALL | FLASHW_TIMERNOFG, uint.MaxValue, 0);
return FlashWindowEx(ref fi);
}
return false;
}
private static FLASHWINFO Create_FLASHWINFO(IntPtr handle, uint flags, uint count, uint timeout)
{
var fi = new FLASHWINFO();
fi.cbSize = Convert.ToUInt32(Marshal.SizeOf(fi));
fi.hwnd = handle;
fi.dwFlags = flags;
fi.uCount = count;
fi.dwTimeout = timeout;
return fi;
}
/// <summary>
/// Flash the specified Window (win) for the specified number of times
/// </summary>
/// <param name="win">The Form (Window) to Flash.</param>
/// <param name="count">The number of times to Flash.</param>
/// <returns></returns>
public static bool Flash(IntPtr win, uint count)
{
if (Win2000OrLater)
{
var fi = Create_FLASHWINFO(win, FLASHW_ALL, count, 0);
return FlashWindowEx(ref fi);
}
return false;
}
/// <summary>
/// Start Flashing the specified Window (win)
/// </summary>
/// <param name="win">The Form (Window) to Flash.</param>
/// <returns></returns>
public static bool Start(IntPtr win)
{
if (Win2000OrLater)
{
var fi = Create_FLASHWINFO(win, FLASHW_ALL, uint.MaxValue, 0);
return FlashWindowEx(ref fi);
}
return false;
}
/// <summary>
/// Stop Flashing the specified Window (win)
/// </summary>
/// <param name="win"></param>
/// <returns></returns>
public static bool Stop(IntPtr win)
{
if (Win2000OrLater)
{
var fi = Create_FLASHWINFO(win, FLASHW_STOP, uint.MaxValue, 0);
return FlashWindowEx(ref fi);
}
return false;
}
/// <summary>
/// A boolean value indicating whether the application is running on Windows 2000 or later.
/// </summary>
private static bool Win2000OrLater => Environment.OSVersion.Version.Major >= 5;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment