Home >Backend Development >C++ >How to Display a Transparent Label Over a PictureBox in C#?

How to Display a Transparent Label Over a PictureBox in C#?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-01-25 16:16:10690browse

How to Display a Transparent Label Over a PictureBox in C#?

Show transparent label above PictureBox in C# form

In C# forms, when trying to display a transparent label on a PictureBox, users may encounter a gray background instead of the expected transparency effect. This is because PictureBox is not a container control.

Solution 1: Code Implementation

To resolve this issue, modify the form constructor, change the label's parent to a PictureBox and recalculate its position.

<code class="language-csharp">public Form1() {
    InitializeComponent();
    var pos = label1.Parent.PointToScreen(label1.Location);
    pos = pictureBox1.PointToClient(pos);
    label1.Parent = pictureBox1;
    label1.Location = pos;
    label1.BackColor = Color.Transparent;
}</code>

Solution 2: Design-time enhancement

Alternatively, solve the design-time problem by creating a custom class that inherits from ParentControlDesigner.

<code class="language-csharp">using System.ComponentModel;
using System.Windows.Forms;
using System.Windows.Forms.Design;    // 添加对System.Design的引用

[Designer(typeof(ParentControlDesigner))]
class PictureContainer : PictureBox {}</code>

Description

Set PictureBox as a container control through the above method, the label will become a child control of PictureBox, and its transparency will be displayed correctly on top of PictureBox.

The above is the detailed content of How to Display a Transparent Label Over a PictureBox in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn