TopMost总是不是TopMost - WPF

时间:2010-09-16 17:57:36

标签: c# wpf topmost

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

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

4 个答案:

答案 0 :(得分:17)

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

无论哪种方式,无论如何,对于今后可能会遇到这篇文章的人,我都有一个可能的解决方案。您只需处理Window.Deactivated Event和/或Application.Deactivated Event即可。当窗口成为后台窗口时发生Window.Deactivated Event ,当应用程序停止作为前台应用程序时发生Application.Deactivated Event

我们的想法是,每次您的申请或TopMost失去焦点时,都会将相关的true属性设置为Window

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

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

答案 1 :(得分:1)

我在设置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);

答案 2 :(得分:1)

在大多数情况下,这应该可以解决问题

private void Window_Deactivated(object sender, EventArgs e)
{
    // The Window was deactivated 
    Topmost = false; // set topmost false first
    Topmost = true; // then set topmost true again.
}

答案 3 :(得分:-4)

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