首页 新闻 会员 周边 捐助

散分啦。C#窗体是否被遮挡函数判断问题

0
悬赏园豆:30 [已解决问题] 解决于 2024-04-08 21:23

前段时间搜到园友的一个段代码,就是判断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))
{
   //具体操作,比如把窗口显示到前台
}

 

在我的博文中有一个使用的例子,但是在窗体最大化的时候该函数没做判断,所以请园友修改上面的函数,使得在窗体最大化的时候能够进行判断

https://www.cnblogs.com/lzhdim/p/18048174

lzhdim的主页 lzhdim | 小虾三级 | 园豆:650
提问于:2024-03-08 20:22
< >
分享
最佳答案
0

已联系作者解决。。。

lzhdim | 小虾三级 |园豆:650 | 2024-04-08 21:22
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册