0
votes


I'm new for create user control, and in my first usercontrol i used from picturebox and label ,
picturebox for draw a shape and label for show text over that shape. i was set picturebox parent for label, and label backcolor to transparent also if don't have any text label set to visible = false

now i have a problem, when label is visible, i can't see picturebox correctly.

enter image description here

how can i solve this problem ?

also paint event on user control not work

    private void Ucontrol_Paint(object sender, PaintEventArgs e)
    {
        if (RightToLeft)
        {
            lblTxt.RightToLeft = System.Windows.Forms.RightToLeft.Yes;
        }
        else
        {
            lblTxt.RightToLeft = System.Windows.Forms.RightToLeft.No;
        }

        lblTxt.ForeColor = FontColor;
        lblTxt.Text = Txt;
        if (Question)
        {
            BorderColor = Color.DarkBlue;
            BackColor = Color.FromArgb(75, 163, 234);
            CreateQuestion(BorderColor, BackColor);
        }
        else
        {
            BorderColor = Color.DarkGreen;
            BackColor = Color.FromArgb(59, 226, 75);
            CreateAnswer(BorderColor, BackColor);
        }
    }
1
You have accepted a wrong answer. All you need to add to your code was one line to add the label to the picturebox's controls collection and one to set its location. Pictubreboxes don't help with that in the as containers do but they work just as well. - TaW

1 Answers

-1
votes

Forms controls don't have really a transpartent background, they copy it's parent content.

Also, a PictureBox can't be parent of another control as they aren't container.

Then, instead of using a picturebox just set the usercontrol background image and put the label on it, the transparency should work.

Here is a working example manually drawing the control content:

public partial class UserControl1 : UserControl
{
    public UserControl1()
    {
        InitializeComponent();

        Label lbl = new Label();
        lbl.Location = new Point(10, 10);
        lbl.Width = 150;
        lbl.Height = 150;
        lbl.BackColor = Color.Transparent;
        lbl.Text = @"asdfasdfasdfasdf\r\nasdfasdfasdf\r\n\r\nasdfasdfasdf";

        lbl.Visible = true;

        this.Controls.Add(lbl);
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);

        e.Graphics.FillRectangle(Brushes.Red, new Rectangle(10, 10, 100, 100));
        e.Graphics.FillEllipse(Brushes.Yellow, new Rectangle(10, 10, 100, 100));
    }
}