0

自定义控件添加到其父级。在父窗体的form_lord(). 自定义控件绘制事件不起作用(自定义控件 onpaint 事件处的断点甚至无法触发)

代码是这样的(我不知道为什么):

自定义控件:

public class Box : Control
{
    public Rectangle rect; 

    public Box(Rectangle rect)
    {
        this.rect = rect;
    } 

    protected override void OnPaint(PaintEventArgs e)
    {
        e.Graphics.FillRectangle(new SolidBrush(Color.Chocolate), rect);
        base.OnPaint(e);
    } 
} 

public partial class Form1 : Form
{ 
    private void Form1_Load(object sender, EventArgs e)
    {
        Box box = new Box( new Rectangle(100, 100, 100, 130) );

        this.Controls.add(box);
    } 
} 
4

2 回答 2

1

尝试设置控件的宽度和高度,下面的这个解决方案适合我

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            Load +=new EventHandler(Form1_Load);
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Box box = new Box(new Rectangle(0, 0, 100, 100));
            box.Width = 200;
            box.Height = 200;
            this.Controls.Add(box);
        } 

    }

    public class Box : Control
    {
        public Rectangle rect;

        public Box(Rectangle rect)
        {
            this.rect = rect;
        }

        protected override void OnPaint(PaintEventArgs e)
        {

            e.Graphics.FillRectangle(new SolidBrush(Color.Chocolate), rect);
            base.OnPaint(e);
        }



    } 
于 2012-11-25T10:40:25.633 回答
0

尝试继承BoxUserControl.

于 2012-11-25T10:31:25.353 回答