C# winform check if control is physicaly visible

后端 未结 9 1660
有刺的猬
有刺的猬 2020-12-09 01:58

Is it possible to determine if at least one pixel of a control can be seen (by a property or maybe using event notification).

NB : I am not looking for the Visible p

9条回答
  •  不知归路
    2020-12-09 02:35

    Inspired by Hans's answer I've implemented this behavior in this way;

        [DllImport("user32.dll")]
        static extern IntPtr WindowFromPoint(POINT Point);
    
        [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(p.X, p.Y);
            }
    
            public static implicit operator POINT(System.Drawing.Point p)
            {
                return new POINT(p.X, p.Y);
            }
        }
    
        public static bool IsControlVisibleToUser(this Control control)
        {
            var pos = control.PointToScreen(control.Location);
            var pointsToCheck = new POINT[]
                                    {
                                        pos,
                                        new Point(pos.X + control.Width - 1, pos.Y),
                                        new Point(pos.X, pos.Y + control.Height - 1),
                                        new Point(pos.X + control.Width - 1, pos.Y + control.Height - 1),
                                        new Point(pos.X + control.Width/2, pos.Y + control.Height/2)
                                    };
    
            foreach (var p in pointsToCheck)
            {
                var hwnd = WindowFromPoint(p);
                var other = Control.FromChildHandle(hwnd);
                if (other == null)
                    continue;
    
                if (control == other || control.Contains(other))
                    return true;
            }
    
            return false;
        }
    

提交回复
热议问题