18 September 2008

C# Label transparency

I am writing a small configuration editor for work at the moment and have come to make the initial release for the other guys to test. As the tool could end up in the hands of our partners I thought I would add a decent looking splash screen and about box.

Creating a graphic was the easy part. I left room for a label to be added on the splash window to display the application version. This was an approach I took when working with VB6/VC++ many years ago so I could pass the version info in the page load event. The only trouble is that C# label controls do not support full transparency.

I did a bit of searching and reading of docs. It turns out that turning the .BackColor property to Transparent will only set the back ground colour to the colour of the containing control. Hence if like me you have a picture box and a label it will show the back ground colour of the picture box control, grey (or the default control colour).

Therefore, the following (where pb is a picture box control and l is a label) will do the job. The code should be added to the splash window class.

Private void pb_Paint(object sender, PaintEventArgs e)
l.Visible = false;
e.Graphics.DrawString(l.Text, l.Font, new SolidBrush(l.ForeColor), l.Left - pb.Left, l.Top - pb.Top);

No comments: