سؤال

I have a custom Control:

public class Temp : Control
{
    public Temp(Color col, int x, int y)
    {
        Size = new Size(x + 10, y + 10);
        this.x = x;
        this.y = y;

        SetStyle(ControlStyles.SupportsTransparentBackColor, true);
        BackColor = col;
    }

    int x, y;

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

        using (var p = new Pen(Color.Black, 3))
        {
            e.Graphics.DrawLine(p, new Point(10, 10), new Point(x, y));
        }
    }

}

And from the Load event of my Form I add two of these control to the Controls of a Panel I added as the only control of my Form:

panel1.Controls.Add(new Temp(Color.Red, 50, 50));
panel1.Controls.Add(new Temp(Color.Violet, 10, 100));

This is the output:

enter image description here

As you can see the first control cover the second one, while I'd want to display only the two lines, where the controls background color is transparent.

Note that using a transparent BackColor doesn't work:

panel1.Controls.Add(new Temp(Color.Transparent, 50, 50));
panel1.Controls.Add(new Temp(Color.Violet, 10, 100));

And this is the output:

enter image description here

How can I solve this problem? That is, display only (and completely) both my lines?

هل كانت مفيدة؟

المحلول

Instead of Inheriting from Control, create two points in your custom class. Sample code given below

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;

namespace SOWinForm
{
    public partial class Form1 : Form
    {
        List<Line> lines;
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            lines = new List<Line>();
            lines.Add(new Line(){ StartPoint = new Point(10,10), EndPoint = new Point(10,100)});
            lines.Add(new Line() { StartPoint = new Point(10, 10), EndPoint = new Point(50, 50) });
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            foreach (var line in lines)
            {
                using (var p = new Pen(Color.Black, 3))
                {
                    e.Graphics.DrawLine(p, line.StartPoint, line.EndPoint);
                }
            }
        }
    }

    public class Line
    {
        public Point StartPoint {get;set;}
        public Point EndPoint { get; set; }

        //Add Custom Properties
    }
}

نصائح أخرى

When you are setting transparent backcolor that doesn't mean that the background color is transparent but the color of its parent. The parent of first control is the panel(with gray color) so also the color of the control is gray. Set the parent of the first control to be the second one.

valter

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top