开发者

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开发者_JAVA百科 transparent.

How can I accomplish this in C#?


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).


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.


I'am not sure if this is even possible with WinForms without exzessessive use of p/invoke calls and workarounds.

You may want to use Windows Presentation Foundation (WPF) instead, where such effects are almost trivial to implement.


Simple:

myForm.Opacity = 80; // Change 80 with your value
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜