前段时间搜到园友的一个段代码,就是判断C#窗体是否被遮挡,但是我试了一下,在窗体最大化的时候没做判断。代码如下:
using System.Runtime.InteropServices; using System; using System.Windows.Forms; using System.Drawing; namespace WindowTimeDev { public static class FormHelper { static Rectangle ScreenRectangle = Rectangle.Empty; static FormHelper() { ScreenRectangle = Screen.PrimaryScreen.WorkingArea; } [DllImport("user32.dll")] public static extern IntPtr GetWindow(IntPtr hWnd, uint wWcmd); [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool GetWindowRect(IntPtr hWnd, ref RECT lpRect); [DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr hWnd); public static bool IsOverlapped(Form form) { return isoverlapped(form.Handle, form); } private static bool isoverlapped(IntPtr win, Form form) { IntPtr preWin = GetWindow(win, 3); //获取显示在Form之上的窗口 if (preWin == null || preWin == IntPtr.Zero) return false; if (!IsWindowVisible(preWin)) return isoverlapped(preWin, form); RECT rect = new RECT(); if (GetWindowRect(preWin, ref rect)) //获取窗体矩形 { Rectangle winrect = new Rectangle(rect.Left, rect.Top, rect.Right - rect.Left, rect.Bottom - rect.Top); if (winrect.Width == ScreenRectangle.Width && winrect.Y == ScreenRectangle.Height) //菜单栏。不判断遮挡(可略过) return isoverlapped(preWin, form); if (winrect.X == 0 && winrect.Width == 54 && winrect.Height == 54) //开始按钮。不判断遮挡(可略过) return isoverlapped(preWin, form); Rectangle formRect = new Rectangle(form.Location, form.Size); //Form窗体矩形 if (formRect.IntersectsWith(winrect)) //判断是否遮挡 return true; } return isoverlapped(preWin, form); } } [StructLayout(LayoutKind.Sequential)] public struct RECT { public int Left; public int Top; public int Right; public int Bottom; } }
在窗体中使用时的代码如下:
if(FormHelper.IsOverlapped(this)) { //具体操作,比如把窗口显示到前台 }
在我的博文中有一个使用的例子,但是在窗体最大化的时候该函数没做判断,所以请园友修改上面的函数,使得在窗体最大化的时候能够进行判断。
已联系作者解决。。。