C# form drawing question
What is the easiest way to make a tra开发者_开发百科nsparent overlay over the elements in my form?
I wish to make a simple black (with opacity = 0.5) overlay for my form and activate it if my application is doing something (like a fadescreen).
Thank you.
You can create a transparent control by inherit a control you want use
a Tranparent Panel example :
class TransparentPanel : Panel
{
protected override CreateParams CreateParams
{
get
{
CreateParams createParams = base.CreateParams;
createParams.ExStyle |= 0x00000020; // WS_EX_TRANSPARENT
return createParams;
}
}
protected override void OnPaintBackground(PaintEventArgs e)
{
SolidBrush brush = new SolidBrush(Color.FromArgb(100, 0, 0, 0));
e.Graphics.FillRectangle(brush,0,0,this.Width,this.Height);
}
}
And Use this after form laded.s:
void Form1_Load(object sender, EventArgs e)
{
TransparentPanel overlay = new TransparentPanel();
overlay.BackColor = Color.FromArgb(50, Color.Black);
overlay.Width = this.Width;
overlay.Height = this.Height;
this.Controls.Add(overlay);
overlay.BringToFront();
}
The easiest is to override the application OnPaint method, and inside it add the following lines:
if( doingSomething )
{
using( SolidBrush brush = new SolidBrush( Color.FromArgb(128, 0, 0, 0)))
{
e.Graphics.FillRectangle( brush, 0, 0, width, height );
}
}
Then, at the place in code when your doing something, set doingSomething
to true
, and call Invalidate
. When the work is complete, set doingSomething
to false
, and call Invalidate
again.
Have you tried adding a semi-transparent control to your form that covers the entire form area? Have the control dock to the entire form, so that it resizes with the form. Make sure it is topmost in the Z-order, so that all the other controls are rendered below it.
精彩评论