8

I'm trying to get whether the mouse cursor is over the desktop screen. Here is my code:

    [DllImport("user32.dll")]
    public static extern bool GetCursorPos(out Point lpPoint);

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

    [DllImport("user32.dll", SetLastError = false)]
    public static extern IntPtr GetDesktopWindow();

    public static bool IsMouseOverDesktop()
    {
        Point mouseCursor;
        GetCursorPos(out mouseCursor);
        return WindowFromPoint(mouseCursor) == GetDesktopWindow();
    }

but it doesn't work. When the mouse cursor is over the desktop, WindowFromPoint and GetDesktopWindow return different values.

GEOCHET
  • 21,119
  • 15
  • 74
  • 98
  • 5
    The desktop window may not be what you think it is. The desktop window is the very topmost window. It's *not* the window that *explorer* creates and that contains icons, which I would guess is the actual window you're trying to determine if the mouse is over. – Damien_The_Unbeliever Oct 15 '14 at 14:33
  • Perhaps this will help: http://stackoverflow.com/questions/9222451/what-is-the-difference-between-the-getdesktopwindow-and-openinputdesktop-apis-in – DonBoitnott Oct 15 '14 at 14:54
  • 1
    I don't think it is correct to say it is the topmost (I could be wrong though). It is more accurate to say it is the parent of all windows. I would recommend breaking open spy++ and figure out what window WindowFromPoint is giving you and then go from there. – Mike Cheel Oct 15 '14 at 15:01

1 Answers1

1

Now with my idea you can solve your problem like this:

Use this method in your code of form.

public bool IsMouseOverDesktop()
{
 bool IsMouseOverDesktop = false;
 if ((Cursor.Position.X > this.Location.X) && ((Cursor.Position.X - this.Location.X) < this.Width) && (Cursor.Position.Y > this.Location.Y) && ((Cursor.Position.Y - this.Location.Y) < this.Height))
  IsMouseOverDesktop = false;
 else
  IsMouseOverDesktop = true;
 return IsMouseOverDesktop;
}

Then call this method in a event and check is mouse over the desktop or not.

Masood
  • 189
  • 5