首页 > 代码库 > C#判断鼠标是否在自己程序的NotifyIcon上
C#判断鼠标是否在自己程序的NotifyIcon上
/// <summary> /// 程序托盘区图标位置 /// </summary> public class IconInfo { /// <summary> /// 托盘区句柄 /// </summary> public IntPtr hWnd = IntPtr.Zero; /// <summary> /// 图标X坐标 /// </summary> public int X; /// <summary> /// 图标Y坐标 /// </summary> public int Y; /// <summary> /// 图标宽度 /// </summary> public int Width; /// <summary> /// 图标高度 /// </summary> public int Height; public bool InIconRect(Point p) { if (p.X >= X && p.X <= X + Width && p.Y >= Y && p.Y <= Y + Height) { return true; } return false; } }
在图标的MouseMove事件中加入,用来确定图标位置信息
GetIconInfo(); <pre name="code" class="csharp"> //获取图标位置信息 private void GetIconInfo() { Point p = Cursor.Position; MyIcon.hWnd = WindowFromPoint(p); int BtnSize = SendMessage(MyIcon.hWnd, TB_GETBUTTONSIZE, IntPtr.Zero, IntPtr.Zero); MyIcon.Width = BtnSize & 0xFFFF; MyIcon.Height = (BtnSize / 0x10000) & 0xFFFF; Rect rect = new Rect(); if (GetWindowRect(MyIcon.hWnd, out rect)) { if (MyIcon.Width != 0 && MyIcon.Height != 0) { MyIcon.X = (p.X - rect.Left - py) / MyIcon.Width * MyIcon.Width + rect.Left + py; MyIcon.Y = (p.Y - rect.Top - py) / MyIcon.Height * MyIcon.Height + rect.Top + py; } } }
所用到的变量和函数
/// <summary> /// 不同操作系统偏移量 /// </summary> private int py = 0; private const int WM_USER = 0x400; private const int TB_GETBUTTONSIZE = WM_USER + 58; private const int WM_SYSCOMMAND = 0x112; private const long SC_MINIMIZE = 0xF020; private const int WM_MOUSEMOVE = 0X0200; [DllImport("user32.dll")] public static extern int SendMessage(IntPtr hwnd, int wMsg, IntPtr wParam, IntPtr lParam); [DllImport("user32.dll")] private static extern bool GetWindowRect(IntPtr hwnd, out Rect lpRect); [DllImport("User32.dll")] private static extern IntPtr WindowFromPoint(Point p); /// <summary> /// 图标信息 /// </summary> private IconInfo MyIcon = new IconInfo(); // WIN7之后的系统有两像素偏移量 程序load时加入以下代码 OperatingSystem os = Environment.OSVersion; if (os.Platform == PlatformID.Win32NT && os.Version.Major >= 6) { py = 2; }
C#判断鼠标是否在自己程序的NotifyIcon上
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。