TopMost总是不是TopMost – WPF

我有一个时钟应用程序。 我已经设置了Window的TopMost属性。 但是,随机地,一些其他窗口或视觉工作室来到时钟之上。

有没有其他方法可以使我的窗口(时钟应用程序)始终显示在所有其他应用程序之上。

你确定它是随机窗口吗? 如果另一个窗口也是最顶层的窗口,则它可能位于窗口上方。

我知道这个问题已经过时了,但是我不太明白为什么接受的答案已经获得了投票……或者为什么它被接受了……它并没有真正回答这个问题,或者提供了解决方案和答案如今这些短片几乎总是被社区投票和/或删除。 好吧,我猜它是在不同的时间发布的。

无论哪种方式,尽管它已经老了,我可以为将来可能会遇到这篇文章的人提供一个可能的解决方案。 您可以简单地处理Window.Deactivated事件和/或Application.Deactivated事件 。 当窗口变为后台窗口时发生 Window.Deactivated事件 ,当 应用程序停止作为前台应用程序时发生 Application.Deactivated事件 。

我们的想法是每次应用程序或Window失去焦点时将相关的TopMost属性设置为true

 private void Window_Deactivated(object sender, EventArgs e) { // The Window was deactivated this.TopMost = true; } 

值得注意的是,其他开发人员也可以使用这种技术,因此这并不能保证您的Window 始终保持最佳状态,但它对我有用,并且通过使用它仍然可以改善情况。

在设置Window.Topmost = true时,我也遇到过这个问题。现有窗口有时可以工作,有时不工作。 下面是我的解决方法,如果WS_EX_TOPMOST样式在运行时丢失,您可以将它与其他人提到的Window_Deactivated方法结合使用。

 App.Current.MainWindow.Topmost = true; // Get this window's handle IntPtr hwnd = new WindowInteropHelper(App.Current.MainWindow).Handle; // Intentionally do not await the result App.Current.Dispatcher.BeginInvoke(new Action(async () => await RetrySetTopMost(hwnd))); 

额外代码:

 private const int RetrySetTopMostDelay = 200; private const int RetrySetTopMostMax = 20; // The code below will retry several times before giving up. This always worked with one retry in my tests. private static async Task RetrySetTopMost(IntPtr hwnd) { for (int i = 0; i < RetrySetTopMostMax; i++) { await Task.Delay(RetrySetTopMostDelay); int winStyle = GetWindowLong(hwnd, GWL_EXSTYLE); if ((winStyle & WS_EX_TOPMOST) != 0) { break; } App.Current.MainWindow.Topmost = false; App.Current.MainWindow.Topmost = true; } } internal const int GWL_EXSTYLE = -20; internal const int WS_EX_TOPMOST = 0x00000008; [DllImport("user32.dll")] internal static extern int GetWindowLong(IntPtr hwnd, int index);