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?