What is the best way to determine if a window is actually visible in WPF

这一生的挚爱 提交于 2019-12-14 03:43:28

问题


I'm trying to toggle the display of a small window based on the click of a notify icon in a system tray app. This is simple enough to implement, however when the small window is displayed and another application takes focus and therefore moves in front of it (z-order) I want the toggle to assume that the small window is now hidden, even though it's visibility is still set to visible. Otherwise, clicking the icon would set the windows visiblity to hidden even though it is already hidden behind another. I've tried catching / overriding the activate and deactive methods to keep track but clicking the notify icon will always cause the deactive event to fire first. A similar approach using focus / lost focus didn't work either as the window seemed to think it still had focus even when hidden behind another applications window in active use. In the end I had to resort to native code and the WindowFromPoint method as follows:

using System.Windows.Interop;
using System.Runtime.InteropServices;
using System.Drawing;

[DllImport("user32.dll")]
public static extern IntPtr WindowFromPoint(Point lpPoint);

public static bool IsWindowVisible(System.Windows.Window window) {
    WindowInteropHelper win = new WindowInteropHelper(window);
    int x = (int)(window.Left + (window.Width / 2));
    int y = (int)(window.Top + (window.Height / 2));
    Point p = new Point(x, y);
    return (win.Handle == WindowFromPoint(p));
}

This checks if the window returned at the coordinates of the centre of the window in question matches said window. i.e. the centre of the window in question is visible.

This seems a little hacky, is there a nicer way to achieve the same result?


回答1:


You may not want to rely on whether a window is obstructed as there are many factors that can change the window size, positing, etc. and all of them tie into accessibility features which add even more complexities.

Instead, you may want to check whether or not the window has focus. This is how MSN Messenger knows whether or not to flash orange in the taskbar; it fires a notification and if it doesn't have focus, the taskbar flashes.



来源:https://stackoverflow.com/questions/454792/what-is-the-best-way-to-determine-if-a-window-is-actually-visible-in-wpf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!