fix:窗口置顶异常

This commit is contained in:
PrefacedCorg
2026-04-17 13:14:23 +08:00
parent 7003bb8426
commit 231b850f74
5 changed files with 134 additions and 13 deletions
+3 -1
View File
@@ -401,7 +401,9 @@ namespace Ink_Canvas
if (!ok) return;
}
new NamesInputWindow().ShowDialog();
var namesInputWindow = new NamesInputWindow();
namesInputWindow.Owner = this;
namesInputWindow.ShowDialog();
Window_Loaded(this, null);
}
@@ -1,5 +1,8 @@
using System;
using System;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Interop;
using System.Windows.Threading;
namespace Ink_Canvas
{
@@ -8,9 +11,26 @@ namespace Ink_Canvas
/// </summary>
public partial class YesOrNoNotificationWindow : Window
{
[DllImport("user32.dll")]
private static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);
[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
private static extern bool IsWindowVisible(IntPtr hWnd);
private static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);
private const uint SWP_NOMOVE = 0x0002;
private const uint SWP_NOSIZE = 0x0001;
private const uint SWP_SHOWWINDOW = 0x0040;
private const uint SWP_NOOWNERZORDER = 0x0200;
private readonly Action _yesAction;
private readonly Action _noAction;
private readonly Action _windowClose;
private DispatcherTimer _topmostCheckTimer;
private IntPtr _hwnd;
public YesOrNoNotificationWindow(string text, Action yesAction = null, Action noAction = null, Action windowClose = null)
{
@@ -19,6 +39,62 @@ namespace Ink_Canvas
_windowClose = windowClose;
InitializeComponent();
Label.Text = text;
Loaded += YesOrNoNotificationWindow_Loaded;
Closed += YesOrNoNotificationWindow_Closed;
}
private void YesOrNoNotificationWindow_Loaded(object sender, RoutedEventArgs e)
{
_hwnd = new WindowInteropHelper(this).Handle;
Topmost = true;
Activate();
Focus();
if (_hwnd != IntPtr.Zero)
{
SetWindowPos(_hwnd, HWND_TOPMOST, 0, 0, 0, 0,
SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW | SWP_NOOWNERZORDER);
}
_topmostCheckTimer = new DispatcherTimer();
_topmostCheckTimer.Interval = TimeSpan.FromMilliseconds(100);
_topmostCheckTimer.Tick += TopmostCheckTimer_Tick;
_topmostCheckTimer.Start();
}
private void TopmostCheckTimer_Tick(object sender, EventArgs e)
{
try
{
if (_hwnd == IntPtr.Zero) return;
var foregroundWindow = GetForegroundWindow();
if (foregroundWindow != _hwnd && IsWindowVisible(_hwnd))
{
Topmost = true;
Activate();
Focus();
SetWindowPos(_hwnd, HWND_TOPMOST, 0, 0, 0, 0,
SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW | SWP_NOOWNERZORDER);
}
}
catch (Exception)
{
}
}
private void YesOrNoNotificationWindow_Closed(object sender, EventArgs e)
{
if (_topmostCheckTimer != null)
{
_topmostCheckTimer.Stop();
_topmostCheckTimer.Tick -= TopmostCheckTimer_Tick;
_topmostCheckTimer = null;
}
}
private void ButtonYes_Click(object sender, RoutedEventArgs e)