Reputation: 4273
I have a form with opacity set to 0. How would I be able to paint a filled rectangle inside that form, that is 50% transparent ?
//brush1 transparency is set at 128 (50%)
SolidBrush brush1 = new SolidBrush(Color.FromArgb(128, 100, 100, 100));
private void Form1_Paint(object sender, PaintEventArgs e)
{
e.Grapics.FillRectangle(brush1, rectangle1);
}
If I paint using e.Graphics
,nothing is drawn on the screen, since the form's opacity is 0.
I tried drawing using Graphics g = Graphics.FromHwnd(IntPtr.Zero);
but it is so slow (only slow with brushes with transparency), that is absolutely ineffective.
Edit: I am doing this to draw to the screen. The form is being used a transparent canvas in order to achieve that. I tried using BackColor = Color.LightGreen; TransparencyKey = Color.LightGreen;
but that just draws the rectangle LightGreen
.
This is what I want to achieve:
Upvotes: 0
Views: 2362
Reputation: 10622
You can achieve this by using two forms. One with a partial opacity on the background and other with Transparency key on the foreground.
The transparent Window is in a Label kept on a form named Foreground_Form. And the background is a form named Form_TransparentBack
Form_TransparentBack
public partial class Form_TransparentBack : Form
{
public Form_TransparentBack(Form _foregroundForm)
{
InitializeComponent();
StartPosition = _foregroundForm.StartPosition;
Location = _foregroundForm.Location;
Size = _foregroundForm.Size;
_foregroundForm.Resize += _foregroundForm_Resize;
FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
_foregroundForm.LocationChanged += _foregroundForm_LocationChanged;
ShowInTaskbar = false;
BackColor = Color.WhiteSmoke;
Opacity = 0.5;
Timer timer = new Timer() { Interval = 10};
timer.Tick += delegate(object sn, EventArgs ea)
{
(sn as Timer).Stop();
_foregroundForm.ShowDialog();
};
timer.Start();
Show();
}
void _foregroundForm_LocationChanged(object sender, EventArgs e)
{
Location = (sender as Form).Location;
}
void _foregroundForm_Resize(object sender, EventArgs e)
{
WindowState = (sender as Form).WindowState;
Size = (sender as Form).Size;
}
}
Foreground_Form
public partial class Foreground_Form : Form
{
public Foreground_Form()
{
InitializeComponent();
FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; // required
TransparencyKey = this.BackColor; // required
StartPosition = FormStartPosition.CenterScreen;
this.Paint += Foreground_Form_Paint;
}
void Foreground_Form_Paint(object sender, PaintEventArgs e)
{
//this is for the Stroke
e.Graphics.DrawRectangle(Pens.White, new Rectangle(0, 0, Width - 1, Height - 1));
}
}
Now you can call any form with the transparent background. For the transparency, you should set the TransparencyKey to the form to be displayed.
private void button1_Click(object sender, EventArgs e)
{
new Form_TransparentBack(new Foreground_Form());
}
Upvotes: 1