Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know whether the mouse cursor is over the desktop screen?

Tags:

c#

.net

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.

like image 385
Kavlov Curosov Avatar asked Oct 15 '14 14:10

Kavlov Curosov


Video Answer


1 Answers

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.

like image 116
Masood Avatar answered Nov 14 '22 22:11

Masood