窗口形式无法从第二个控件显示

时间:2013-07-30 07:49:53

标签: winforms visual-c++

我正在尝试在运行时添加自定义控件。所以我用自己的paint方法创建了一个自定义控件。只要单击“添加”按钮,就会创建一个新控件并将其添加到主窗体中。但是在添加控件时,我看不到其他人,只能先控制。我不知道发生了什么,有人可以帮忙吗?提前谢谢。

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();
         }

1 个答案:

答案 0 :(得分:0)

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

在自定义类中,错过了初始化控件的属性“Location”和“Size”。初始化这些属性后,控件开始按预期显示在表单中。

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);
    }
};
相关问题