C# winform 动态添加控件 以及 事件
C# winform 动态添加控件 以及 事件
以下代码将在加载窗体时动态生成若干按钮,并排列显示在winform上
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
int i = 0;
Point p;
ToolTip tt = null;
public Form1()
{
InitializeComponent();
p = new Point(0, 50);
tt = new ToolTip();
}
public void ClickHandler(Object sender, System.EventArgs e)
{
MessageBox.Show("您已单击按钮: " + ((Button)sender).Text, "小花朵");
}
public void MouseEnterHandler(Object sender, System.EventArgs e)
{
string s = ((Button)sender).Text;
tt.ToolTipTitle = "小花朵";
tt.Show("鼠标进入按钮:" + s, (Button)sender);
}
public void MouseHoverHandler(Object sender, System.EventArgs e)
{
//MessageBox.Show("mouse hover : " + (Button)sender).Text);
//tt.Hide((Button)sender);
}
private void Form6_Load(object sender, EventArgs e)
{
for (i = 0; i < 20; i++)
{
Button b = new Button();
b.Text = "" + i;
b.SetBounds(p.X, p.Y, 50, 50);
b.Click += new System.EventHandler(ClickHandler);
b.MouseEnter += new System.EventHandler(MouseEnterHandler);
b.MouseHover += new System.EventHandler(MouseHoverHandler);
this.Controls.Add(b);
p.X += 50;
if (p.X >= this.Width - 50)
{
p.X = 0;
p.Y += 60;
}
}
}
}
}
以下代码将在加载窗体时动态生成若干按钮,并排列显示在winform上
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
int i = 0;
Point p;
ToolTip tt = null;
public Form1()
{
InitializeComponent();
p = new Point(0, 50);
tt = new ToolTip();
}
public void ClickHandler(Object sender, System.EventArgs e)
{
MessageBox.Show("您已单击按钮: " + ((Button)sender).Text, "小花朵");
}
public void MouseEnterHandler(Object sender, System.EventArgs e)
{
string s = ((Button)sender).Text;
tt.ToolTipTitle = "小花朵";
tt.Show("鼠标进入按钮:" + s, (Button)sender);
}
public void MouseHoverHandler(Object sender, System.EventArgs e)
{
//MessageBox.Show("mouse hover : " + (Button)sender).Text);
//tt.Hide((Button)sender);
}
private void Form6_Load(object sender, EventArgs e)
{
for (i = 0; i < 20; i++)
{
Button b = new Button();
b.Text = "" + i;
b.SetBounds(p.X, p.Y, 50, 50);
b.Click += new System.EventHandler(ClickHandler);
b.MouseEnter += new System.EventHandler(MouseEnterHandler);
b.MouseHover += new System.EventHandler(MouseHoverHandler);
this.Controls.Add(b);
p.X += 50;
if (p.X >= this.Width - 50)
{
p.X = 0;
p.Y += 60;
}
}
}
}
}