Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make a part of the form partially transparent in C#?

I want to make a part of a form semi-transparent, with additional text on that part which is not transparent.

How can I accomplish this in C#?

like image 852
Haim Bender Avatar asked Oct 11 '09 10:10

Haim Bender


2 Answers

I don't think you can apply transparency (more correctly termed, Opacity) to only a part of a form rather than the complete, whole form.

You can, however, create a custom shaped form (i.e. non-rectangular) quite easily, with various parts of that form being transparent. Depending upon the exact "look" that you're trying to achieve, this may be closest you'll get.

Take a look at these links for creating your own custom-shaped form:

Creating Custom Shaped Windows Forms in .NET
Custom shaped form with a drop down in C#
Shaped Windows Forms and Controls in Visual Studio .NET

The only other alternative may be to display two forms, one of which is set to be partially transparent. You would have to programmatically ensure that the second form is positioned immediately next to the "main" form, and is moved/resized proportionately when the user moves/resizes the "main" form. Although this is two forms, it could be made to look, to the user, that it's actually only one form, although this could be quite tricky to pull off, and would not be a perfect solution (but may be "good enough" depending upon your exact needs).

like image 198
CraigTP Avatar answered Nov 15 '22 21:11

CraigTP


You can do this by creating a fully-transparent window in your form, and then floating a semi-transparent form over the fully-transparent window.

First, set the TransparencyKey of your main form to Color.Red, then place a Panel named panel1 on the form, and set its BackColor to Red. This will create the fully-transparent "window". Create a form-level Form reference like this:

private Form _floater;

Next, put this code in your main form's Load event:

_floater = new Form();
_floater.ShowInTaskbar = false;
_floater.FormBorderStyle = FormBorderStyle.None;
_floater.Opacity = .5;
_floater.Size = panel1.Size;
_floater.StartPosition = FormStartPosition.Manual;
_floater.Location = panel1.PointToScreen(new Point(0, 0));
_floater.Show(this);

Finally, put this code in your main form's Move event:

_floater.Location = panel1.PointToScreen(new Point(0, 0));

The only issue here is that if the user clicks in the semi-transparent "window", the second form will get the focus, so your main form's TitleBar is grayed out.

Click here to run a sample application with this semi-transparent window on a form.

like image 27
MusiGenesis Avatar answered Nov 15 '22 23:11

MusiGenesis