委托 button1.MouseClick 事件而不是更改其控件属性
delegate button1.MouseClick event than changes its control properties
嗨,这是我的第一个post,请多多包涵。 ;)
我有一个小的 class 可以在事件发生时生成按钮。
我似乎无法实现的是向委托添加代码 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.
//...
//...
}
}
}
这里:void mybutton_MouseClick(object sender, MouseEventArgs e)
发件人实际上是按钮被点击了。
因此只需将 sender
转换为 Button
即可设置其背景颜色。
像这样:
var mybutton = sender as Button;
mybutton.BackColor = Color.Red
嗨,这是我的第一个post,请多多包涵。 ;)
我有一个小的 class 可以在事件发生时生成按钮。 我似乎无法实现的是向委托添加代码 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.
//...
//...
}
}
}
这里:void mybutton_MouseClick(object sender, MouseEventArgs e)
发件人实际上是按钮被点击了。
因此只需将 sender
转换为 Button
即可设置其背景颜色。
像这样:
var mybutton = sender as Button;
mybutton.BackColor = Color.Red