嗨,这是我第一篇请跟我说的帖子。 ;)
我有一个小类,在事件发生时生成按钮。 我似乎无法实现的是将代码添加到委托mybutton_MouseClick 这会改变单个生成按钮的颜色。
所以我正在寻找一些可以做的代码: mybutton.BackColor = Color.Red;
namespace test_addObject
{
public partial class Form1 : Form
{
ButtonCreation bc = new ButtonCreation();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
bc.createButton();
}
}
public class ButtonCreation
{
Random rdm = new Random();
public void createButton()
{
Button mybutton = new Button();
Form1.ActiveForm.Controls.Add(mybutton);
mybutton.Location = new Point(
rdm.Next(Form1.ActiveForm.Width - mybutton.Width),
rdm.Next(Form1.ActiveForm.Height - mybutton.Height));
//mybutton.BackColor = Color.Red; //this will generate them red.
mybutton.MouseClick += new MouseEventHandler(mybutton_MouseClick);
}
void mybutton_MouseClick(object sender, MouseEventArgs e)
{
//some code here to change the generated button color when they are clicked individually.
//...
//...
}
}
}
答案 0 :(得分:1)
此处:void mybutton_MouseClick(object sender, MouseEventArgs e)
发件人实际上是点击按钮。
所以只需将sender
投射到Button
,您就可以设置背景颜色了。
像这样:
var mybutton = sender as Button;
mybutton.BackColor = Color.Red