代码之家  ›  专栏  ›  技术社区  ›  Prince Ashitaka

最上面的不是最上面的-wpf

  •  3
  • Prince Ashitaka  · 技术社区  · 14 年前

    我有一份报时表。我已经设置了窗口的最高属性。但是,随机地,其他一些窗口或Visual Studio会出现在时钟之上。

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

    3 回复  |  直到 14 年前
        1
  •  -4
  •   casablanca    14 年前

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

        2
  •  17
  •   Sheridan    11 年前

    我知道这个问题由来已久,但我不太明白为什么被接受的答案得到了更多的选票…或者为什么它被接受…它没有 真正地 回答问题,或提供解决方案和这些天发布的答案,这些短的几乎总是 向下 社区投票和/或删除。嗯,我想是在不同的时间发布的。

    不管怎样,不管它是旧的,我都有一个可能的解决方案,任何人谁可能会遇到这个职位在未来。您可以简单地处理 Window.Deactivated Event 和/或 Application.Deactivated Event . 这个 窗口。已停用 事件 当窗口成为背景窗口时发生 以及 应用程序。已停用 事件 当应用程序不再是前台应用程序时发生 .

    我们的想法是 TopMost 属性到 true 每次申请或 Window 失去焦点:

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

    值得注意的是,其他开发人员也可以使用此技术,因此这并不保证 窗口 总是 保持在最上面,但它对我很有用,而且使用它仍然可以改善情况。

        3
  •  1
  •   user5129133    8 年前

    在设置window.topmost=true时,我也遇到了这个问题,在已经存在的window上,有时候是有效的,有时不是。下面是我的解决方法,如果在运行时丢失了WS-Ex-Topmost样式,您可以将其与其他人提到的窗口停用方法结合起来。

    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);
    
    推荐文章