0

I am trying to add a custom control at runtime. So i created a custom control with its own paint method. Whenever the "Add" button clicked, a new control is created and added to main form. But While adding controls,I cannot see others, but first control only. I have no idea about what is happening, Can anyone help?. Thanks in advance.

enter image description here

public ref class CustomLine : public UserControl
{
private:
    Point P1,P2;
    Pen ^pen;
public:
    CustomLine(Point p1, Point p2)
    {
        P1 = p1;
        P2 = p2;
        pen = gcnew Pen(Color::Red,2);
    }
protected:
    virtual void OnPaint(System::Windows::Forms::PaintEventArgs ^e) override
    {
        e->Graphics->DrawLine(pen,P1,P2);
    }
};


private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e) 
         {
             int xx1 = Convert::ToInt32(this->x1->Text);
             int yy1 = Convert::ToInt32(this->y1->Text);
             int xx2 = Convert::ToInt32(this->x2->Text);
             int yy2 = Convert::ToInt32(this->y2->Text);
             CustomLine ^cline = gcnew CustomLine(Point(xx1,yy1),Point(xx2,yy2));
             this->Controls->Add(cline);
             this->Invalidate();
         }
4

1 回答 1

0

lc的评论解决了这个问题。谢谢lc。

在自定义类中,缺少初始化控件的属性“位置”和“大小”。初始化这些属性后,控件开始按预期出现在表单中。

public ref class CustomLine : public UserControl
{
private:
    Point P1,P2;
    Pen ^pen;
public:
    CustomLine(Point p1, Point p2)
    {
        P1 = p1;
        P2 = p2;
        this->Location = P1;
        this->Size = System::Drawing::Size(Point(P2.X - P1.X, P2.Y - P1.Y));
        pen = gcnew Pen(Color::Red,2);
    }
protected:
    virtual void OnPaint(System::Windows::Forms::PaintEventArgs ^e) override
    {
        e->Graphics->DrawLine(pen,P1,P2);
    }
};
于 2013-07-30T08:02:36.337 回答