动态添加控件
2012-04-08 10:16 精诚所至 金石为开 阅读(479) 评论(0) 编辑 收藏 举报本程序实现在程序运行中向窗体添加Button控件,点击按钮就会在窗体上新增一个Button实例,程序界面如下。
添加鼠标滑过按钮改变按钮颜色的代码,点击按钮,TextBox中显示按钮信息,程序代码如下。
using System; using System.Collections.Generic; using System.Drawing; using System.Windows.Forms; namespace eg42_addCtrlAtRuntimeApp { public partial class MainForm : Form { private int count; public MainForm() { InitializeComponent(); } void Btn_MouseEnter(object sender, EventArgs e) { Button currentButton=(Button)sender; currentButton.BackColor=Color.Blue; } void Btn_MouseLeave(object sender, EventArgs e) { Button currentButton=(Button)sender; currentButton.BackColor=System.Windows.Forms.Control.DefaultBackColor; } void Btn_Click(object sender, MouseEventArgs e) { Button currentButton=(Button) sender; txt_msg.Text="你点击了"+currentButton.Text; } void Btn_addButtonMouseClick(object sender, MouseEventArgs e) { count+=2; int localX=this.btn_addButton.Height*count; int localY=10*count; Button toAddButton=new Button(); toAddButton.Name="Button"+count; toAddButton.Text="按钮"+count+""; toAddButton.Location=new Point(localX,localY); toAddButton.MouseEnter+=new EventHandler(this.Btn_MouseEnter); toAddButton.MouseLeave+=new EventHandler(this.Btn_MouseLeave); toAddButton.MouseClick+=new MouseEventHandler(this.Btn_Click); this.Controls.Add(toAddButton); } } }