public bool PreFilterMessage(ref System.Windows.Forms.Message message) { int hwnd = 0; StringBuilder winText = new StringBuilder(); StringBuilder clsName = new StringBuilder(); StringBuilder pText = new StringBuilder(); //获取鼠标所在位置获取窗体或控件的信息,包括Handle,窗体(控件)的标题,窗体(控件)的类名,父容器的标题 APImouse.GetWindowFromPoint(ref hwnd, ref winText, ref clsName, ref pText); // 鼠标左键消息 if (message.Msg >= 513 && message.Msg <= 515) { if (hwnd != (int)listBox1.Handle && hwnd != (int)tbBrand.Handle) pnlBrandList.Visible = false; } return false; } public struct POINT { public int x; public int y; } public class APImouse { [DllImport("user32.dll", EntryPoint = "GetCursorPos")] public static extern int GetCursorPos(ref POINT lpPoint); [DllImport("user32.dll", EntryPoint = "WindowFromPoint")]//指定坐标处窗体句柄 public static extern int WindowFromPoint(int xPoint, int yPoint); [DllImport("user32.dll", EntryPoint = "GetWindowText")]//指定坐标处窗体标题 public static extern int GetWindowText(int hwnd, string lpString, int cch); [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)] static extern int GetClassName(int hWnd, StringBuilder lpClassName, int nMaxCount); [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)] static extern int GetParent(int hWnd); public static void GetWindowFromPoint(ref int hwnd, ref StringBuilder winText, ref StringBuilder clsName, ref StringBuilder pText) { int parentHandle = 0; int maxLen = 128; POINT pnt = new POINT(); parentHandle = GetCursorPos(ref pnt); hwnd = WindowFromPoint(pnt.x, pnt.y); winText = new StringBuilder(maxLen); parentHandle = GetWindowText(hwnd, winText.ToString(), maxLen); clsName = new StringBuilder(maxLen); parentHandle = GetClassName(hwnd, clsName, maxLen); pText = new StringBuilder(maxLen); parentHandle = GetParent(hwnd); parentHandle = GetWindowText(parentHandle, pText.ToString(), maxLen); } }
原文地址:http://www.cnblogs.com/Sabre/p/3854811.html