4
votes

What I want to achieve is a semi-transparent background that covers the screen. And then be able to draw non-transparent brushes on top of it.

What I have tried is to have a form with the size of the screen, then setting it's color and setting this.opacity = 0.5. However this affects all brushes in the form.

Ive also tried setting the background color to Color.Transparent, and then drawing an additional brush that covers the screen with opacity 0.5 before I then draw the opaque brushes... However the background becomes opaque as well. Even though the style flag is set (ControlStyles.SupportsTransparentBackColor, true)

I know I can achieve this by having an additional form. One form for the transparent background and one for the opaque foreground, but isn't that overkill?

Is there a better way?

Update 1: Trying what is suggested in the comments.

Current state: Form1: the main program, calls for the 'overlay' to show, which is: Form2: Overlay background (semi-transparent black) and, Form3: Overlay foreground, this is where the user draws.

Form 1 and 2 works as indended, however Form3 refuses to work with transparency. If I set

this.BackColor = Color.Lime;
this.TransparencyKey = Color.Lime;

then the performance drops and the program lags heavily (although it does become transparent). Ideally I would want to use this.BackColor = Color.Transparent; however that doesn't have any effect (solid background, no alpha).

Note that the form covers the screen and the background is usually the desktop. Maybe that's why it doesn't work?

1
One alternative is creating a screenshot before showing your form, and using that as a background image. Perhaps not the best solution, but it is simple (like me :P)C.Evenhuis
@C.Evenhuis It's a good idea, and I thought about it. I'm trying to make a screenshot program, so I'd like to be able to capture potential videos in the background as well :)Mads M
You need a sandwich of two windows. Bottom one uses Opacity, top one uses TransparencyKey and is the one you paint on. Sample code for the sandwich is here.Hans Passant
@HansPassant Thank you for the suggestion. I have tried implementing two forms. One for the background which is only a black color with opacity set to 0.5. The other is the foreground which has backcolor=transparent and it only shows the drawn brushes. The problem is that the foreground form refuses to become transparent. if I make it transparent by setting backcolor and transparencykey to the same, performance drops and the program lags heavily upon mouse move..Mads M

1 Answers

0
votes

You can override the OnPaintBackground of the form, without calling it's base. This will enable you to specify whatever color you want for the background.

Try this:

protected override void OnPaintBackground(PaintEventArgs e)
{
    using (var brush = new SolidBrush(Color.FromAgrb(50, 0, 0, 0))
    {
        e.Graphics.FillRectangle(brush, e.ClipRectangle);
    }
}