views:

636

answers:

1

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?

A: 

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.

Soviut
I found that when I checked the focus property of the window, it would return that it had focus even though it was behing another window. I then tried the activate and deactive events, which worked, but deactivate would fire when I clicked the toggle sys tray icon, even though the window was visible
Brehtt