How can I efficiently tell if the mouse is over a top-level window?
By “over”, I mean that the mouse pointer is within the client rectangle of the top-level window and there is no other top-level window over my window at the location of the mouse pointer. In other words, if the user clicked the event would be sent to my top-level window (or one of its child windows).
I am writing in C# using Windows Forms, but I don’t mind using p/invoke to make Win32 calls.
You could use the WinAPI function
WindowFromPoint. Its C# signature is:Note that
POINThere is not the same asSystem.Drawing.Point, but PInvoke provides a declaration forPOINTthat includes an implicit conversion between the two.If you don’t already know the mouse cursor position,
GetCursorPosfinds it:However, the WinAPI calls lots of things “windows”: controls inside a window are also “windows”. Therefore, you might not get a top-level window in the intuitive sense (you might get a radio button, panel, or something else). You could iteratively apply the
GetParentfunction to walk up the GUI hierarchy:Once you find a window with no parent, that window will be a top-level window. Since the point you originally passed in belongs to a control that is not covered by another window, the top-level window is necessarily the one the point belongs to.