Windows
C#
Panel

C# 動的にPanelを生成する

Panel を動的に作成する。

using System;
using System.Windows.Forms;
using System.Drawing;

class FormMain : Form {

  Panel panel1;

  [STAThread]
  public static void Main() {
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    Application.Run( new FormMain());
  }

  FormMain()
  {
    Text = "Button Click Sample";
    ClientSize = new Size(600, 400);
    Button btn1 = new Button();
    btn1.Location = new Point(50, 50);
    btn1.Text = "Create Panel";
    btn1.Click += btn1_Click;
    Controls.AddRange(new Control[] { btn1 });

    this.Controls.Add(panel1);
  }

  public void CreateMyPanel()
  {
     panel1 = new Panel();

     // Initialize the Panel control.
     panel1.Location = new Point(56,72);
     panel1.Size = new Size(264, 152);

     // Set the Borderstyle for the Panel to three-dimensional.
     panel1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;

     // Add the Panel control to the form.
     this.Controls.Add(panel1);
  }

  void btn1_Click(object sender, System.EventArgs e) {
     CreateMyPanel();
     MessageBox.Show("Panel Close.", "message!");
     this.Controls.Remove(panel1);
  }
}

image1.png

image2.png