在运行时以编程方式添加自定义组件

时间:2011-07-11 08:26:15

标签: c# winforms custom-controls

我在运行时使用自定义组件时遇到问题。 我有这个自定义的FlowLayoutPanel组件:

 public partial class UserControl1 : System.Windows.Forms.FlowLayoutPanel
{

    [Browsable(false)]
    protected override CreateParams CreateParams
    {
        get
        {
            CreateParams cp = base.CreateParams;
            cp.ExStyle |= 0x20;
            return cp;
        }
    }
    protected override void OnPaintBackground(PaintEventArgs e){}

    public UserControl1(){}
}
它没什么复杂的。它所做的就是让背景透明化。

我使用它的dll将这个组件添加到我的工具箱中,当我将它拖放到我的表单时它完全正常。问题是,我无法在运行时以编程方式添加它。

当我运行下面的代码时,它应该在我的自定义FlowLayoutControl之上绘制图片。 但不幸的是它什么也没做。

自定义组件位于WindowsFormsControlLibrary1名称空间下。

 namespace MyFilm_v2._0
 {
  public partial class Form1 : Form
  {

    public Form1()
    {
        InitializeComponent();

        UserControl1 test = new UserControl1();
        test.BackColor = Color.Transparent;
        test.Location = new Point(0, 110);
        test.Width = 660;
        test.Height = 478;

        PictureBox b = new PictureBox();
        b.Location = new Point(100, 100);
        b.Width = 320;
        b.Height = 475;
        b.Image = Properties.Resources.movie;
        this.Controls.Add(b);
        //this.customScrollbar1.Minimum = 0;
        //this.customScrollbar1.Maximum = test.DisplayRectangle.Height;
        //this.customScrollbar1.LargeChange = customScrollbar1.Maximum / customScrollbar1.Height + test.Height;
        //this.customScrollbar1.SmallChange = 15;//when click the arrows
        //this.customScrollbar1.Value = Math.Abs(test.AutoScrollPosition.Y);
    }

...

1 个答案:

答案 0 :(得分:2)

您将picturebox添加到测试控件,但是没有将测试添加到表单控件

public Form1()
{
    InitializeComponent();

    UserControl1 test = new UserControl1();
    test.BackColor = Color.Transparent;
    test.Location = new Point(0, 110);
    test.Width = 660;
    test.Height = 478;

    PictureBox b = new PictureBox();
    b.Location = new Point(100, 100);
    b.Width = 320;
    b.Height = 475;
    b.Image = Properties.Resources.movie;
    test.Controls.Add(b);
    this.Controls.Add(test);//<- here
}