C# 如何在WinForm下实现透明控件

难点

C# WinForm开发时,想要实现漂亮的透明背景动画效果。默认情况下,背景都是一个灰度图片,最多可以换成白色。
如果想实现透明效果,只能根据大背景颜色,调整控件背景颜色。
但是一旦大背景或控件本身有纹理,则很容易看出来不是透明背景,效果很差。
使用继承的方式特别复杂,并且运行效率低。用下面的技巧可以避开复杂,实现透明部品。缺点是一个部品得占用一个对话框。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
I've found a workaround for this problem, which I have on my own. 
Most of what I've read over here is true. 
And the approaches "à la" AlphaBlendTextBox are way too complex or too time-consuming for some environments, already heavily charged.
Assume you have a given background color and a given picture or whatever you want to see through the RichTextBox control. 

This is what I've done (summarized):
on the main form, you place the picture, text, buttons or whatever as projected, 
with the proper background color and / or picture
create a new form and position it wherever appropriate
set this new form TransparencyKey to SystemColors.InactiveBorder
take care of this form border properties (FormBorderStyle to FormBorderStyle.None; 
ControlBox,MinimizeBox, MaximizeBox and ShowIcon to false, TopMost to true, StartPosition to FormStartPosition.Manual, 
SizeGripStyle to SizeGripStyle.Hide), so there's no visible form structures
create a RichTextBox with the same size of the form and located on its upper, left corner
set this box BackColor to SystemColors.InactiveBorder (remember the TransparencyKey?) and its BorderStyle to None as well
take care of textbox contents: color(s), font(s) and strings
synchronize this form visibility with whatever you need to and... voilà! 
You can see your application background through whatever you write and edit on the text box!
I can't pretend this approach fits everybody, but it is way simpler than others I've seen and, 
as long as I can keep it that way, I do prefer the simpler solutions.
Of course, when you close the main form, you must take care of the child form, 
but this is pretty basic for you, isn't it?
Enjoy!


参考:
https://stackoverflow.com/questions/5557365/textbox-with-a-transparent-background