Skip to content

Instantly share code, notes, and snippets.

@emoacht
Created February 14, 2025 10:52
Show Gist options
  • Save emoacht/0c5ec23eb52b873aa7458155ac80d0b0 to your computer and use it in GitHub Desktop.
Save emoacht/0c5ec23eb52b873aa7458155ac80d0b0 to your computer and use it in GitHub Desktop.
Check if the cursor is over a specified Window.
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Interop;
public static class CursorHelper
{
[DllImport("User32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool GetCursorPos(out POINT lpPoint);
[DllImport("User32.dll")]
private static extern nint WindowFromPoint(POINT p);
[StructLayout(LayoutKind.Sequential)]
internal struct POINT
{
public int x;
public int y;
}
public static bool IsMouseOverWindow(Window window)
{
if (GetCursorPos(out POINT p))
{
nint h1 = WindowFromPoint(p);
nint h2 = new WindowInteropHelper(window).EnsureHandle();
return (h1 == h2);
}
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment