How to get a window under the mouse?

As I read, the way to get a window under the mouse is to use WindowFromPoint and what I did, but it will always return the window handle of my window, if I mouse over another window, it will always return my window handle!

Here is my code:

 NativeMethods.POINT p; if (NativeMethods.GetCursorPos(out p)) { IntPtr hWnd = NativeMethods.WindowFromPoint(p); NativeMethods.GetWindowModuleFileName(hWnd, fileName, 2000); string WindowTitle= fileName.ToString().Split('\\')[fileName.ToString().Split('\\').Length - 1]; // WindowTitle will never change, it will get my window only! } //////////////////////////////////////////////////////////////////////////////////////// static class NativeMethods { [DllImport("user32.dll")] public static extern IntPtr WindowFromPoint(POINT Point); [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)] public static extern uint GetWindowModuleFileName(IntPtr hwnd, StringBuilder lpszFileName, uint cchFileNameMax); [DllImport("user32.dll")] public static extern bool GetCursorPos(out NativeMethods.POINT lpPoint); [StructLayout(LayoutKind.Sequential)] public struct POINT { public int X; public int Y; public POINT(int x, int y) { this.X = x; this.Y = y; } public static implicit operator System.Drawing.Point(POINT p) { return new System.Drawing.Point(pX, pY); } public static implicit operator POINT(System.Drawing.Point p) { return new POINT(pX, pY); } } [StructLayout(LayoutKind.Sequential)] public struct RECT { public int Left; public int Top; public int Right; public int Bottom; } } 

EDIT

How I work in WPF, here is my attempt to use invoke in WPF:

 void dispatcherOp_Completed(object sender, EventArgs e) { System.Threading.Thread thread = new System.Threading.Thread( new System.Threading.ThreadStart( delegate() { System.Windows.Threading.DispatcherOperation dispatcherOp = this.Dispatcher.BeginInvoke( System.Windows.Threading.DispatcherPriority.Normal, new Action( delegate() { NativeMethods.POINT p; if (NativeMethods.GetCursorPos(out p)) { IntPtr hWnd = NativeMethods.WindowFromPoint(p); NativeMethods.GetWindowModuleFileName(hWnd, fileName, 2000); uint processID = 0; uint threadID = GetWindowThreadProcessId(hWnd, out processID); string filename= Process.GetProcessById((int)processID).MainModule.FileName; } } )); dispatcherOp.Completed -= new EventHandler(dispatcherOp_Completed); dispatcherOp.Completed += new EventHandler(dispatcherOp_Completed); } )); thread.Start(); } 
+4
source share
1 answer

GetWindowModuleFileName limited to the calling process, it will not work if you pass the HWND belonging to another.

Instead, you can use HWND and p / invoke GetWindowThreadProcessId() to get the process ID, then you can Process.GetProcessById(processId).MainModule.FileName; .

+2
source

All Articles