I started to create a generic usage/reusable method that will help to set the region of a Form to the bounds of its child controls.
But I found a problem when the rectangle of a control intersects with another, I mean the Z-Order, when a control is in front of other and covers a part of the other control in the background, in these circunstances the rectangle of the control in the front is not properly drawn...
See:
...where Button2 is in front of Button1.
Probably is my fault with the usage of the GraphicsPath
class to draw the region path, because I'm not experienced using GDI+ in this way, and maybe I'm writting bad the path...
How can I fix this code to set the expected region?.
Here is the code. Before use it, set the FormBorderStyle
property to None
(a borderless form).
VB.NET:
Public Shared Sub LockFormRegionToControls(ByVal f As Form)
LockFormRegionToControls(Of Control)(f)
End Sub
Public Shared Sub LokckFormRegionToControls(Of T As Control)(ByVal f As Form)
Dim rects As Rectangle() =
(From ctrl As T In f.Controls.OfType(Of T)
Order By f.Controls.GetChildIndex(ctrl) Ascending
Select ctrl.Bounds).ToArray()
Using path As New GraphicsPath()
path.AddRectangles(rects)
f.Region = New Region(path)
End Using
End Sub
C#:
public static void LockFormRegionToControls(Form f) {
LockFormRegionToControls<Control>(f);
}
public static void LockFormRegionToControls<T>(Form f) where T : Control {
Rectangle[] rects = (
from T ctrl in f.Controls.OfType<T>()
orderby f.Controls.GetChildIndex(ctrl) ascending
select ctrl.Bounds).ToArray();
using (GraphicsPath path = new GraphicsPath()) {
path.AddRectangles(rects);
f.Region = new Region(path);
}
}