using System.ComponentModel; using System.Diagnostics; using System.Runtime.InteropServices; using System.Runtime.Versioning; using Avalonia.Controls; namespace FinalToken.App; [SupportedOSPlatform("windows")] internal static partial class WindowsActivation { public static void Activate(Window window) { if (window.TryGetPlatformHandle() is not { } platform) return; var handle = platform.Handle; if (SetForegroundWindow(handle) != 0) return; var foreground = GetForegroundWindow(); if (foreground == 0) return; var foregroundThread = GetWindowThreadProcessId(foreground, out _); var ownThread = GetCurrentThreadId(); if (foregroundThread == ownThread || AttachThreadInput(ownThread, foregroundThread, 1) == 0) return; try { SetForegroundWindow(handle); } finally { AttachThreadInput(ownThread, foregroundThread, 0); } } // D8: a launcher transfers its foreground permission before the running app activates. public static void AllowRunningInstance() { using var current = Process.GetCurrentProcess(); foreach (var candidate in Process.GetProcessesByName(current.ProcessName)) { using (candidate) { try { if (candidate.Id != current.Id && candidate.SessionId == current.SessionId && string.Equals(candidate.MainModule?.FileName, Environment.ProcessPath, StringComparison.OrdinalIgnoreCase)) AllowSetForegroundWindow(candidate.Id); } catch (Exception e) when (e is Win32Exception or InvalidOperationException) { } } } } [LibraryImport("user32.dll")] private static partial int AllowSetForegroundWindow(int processId); [LibraryImport("user32.dll")] private static partial int SetForegroundWindow(nint window); [LibraryImport("user32.dll")] private static partial nint GetForegroundWindow(); [LibraryImport("user32.dll")] private static partial uint GetWindowThreadProcessId(nint window, out uint processId); [LibraryImport("kernel32.dll")] private static partial uint GetCurrentThreadId(); [LibraryImport("user32.dll")] private static partial int AttachThreadInput(uint first, uint second, int attach); }