如何将动态按钮及其事件添加到窗口窗体

本文关键字:添加 事件 窗口 窗体 动态 按钮 | 更新日期: 2023-09-27 18:33:04

动态添加坐标为X=100,Y=200的按钮;通过单击,表单必须将背景颜色更改为红色,第二次单击更改为绿色。

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
    private int X = 100;
    private int Y = 200;
    Button btn = new Button();
    private void Form1_Load(object sender, EventArgs e)
    {
        this.Controls.Add(btn);
        btn.Location = new Point(X, Y);
        btn.Text = "Click";
        btn.Click += new EventHandler(Mouse_Click);
    }

    private void Mouse_Click(Object s, EventArgs e)
    {
        // what to do here to make button change Form color?
    }
}

如何将动态按钮及其事件添加到窗口窗体

//Create new instance of button
Button btn = new Button();
//Set button Location
btn.Location = new Point(100, 200);
//Set button event handler
btn.Click += new EventHandler(btn_Click);
//Add button to Form
this.Controls.Add(btn);
void btn_click (object sender, EventArgs e)
{
}

更改窗体颜色

void btn_click (object sender, EventArgs e)
{
    this.BackColor = Color.Blue;
    //or
    this.ForeColor = Color.Blue;
}