繁体   English   中英

TopMost并非总是TopMost-WPF

[英]TopMost is not TopMost always - 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);

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

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.
}

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM