此代码不报告任何错误,应该有效。按钮背景图像不会更改。知道什么可能是错的吗?
void MyHandler(object sender, EventArgs e, string val)
{
//Process
Process.Start(@val);
//Change button bkground image
var button = (Button)sender;
button.BackgroundImage = global::Test.Properties.Resources.impOK;
}
编辑从另一个事件处理程序创建的按钮调用事件MyHandler。
private async void button3_Click(object sender, EventArgs e)
{
...
foreach (KeyValuePair<string, string> pair in printerDic)
{
//Init
String val = pair.Value;
String ky = pair.Key;
//Button
Button bt_imp = new Button();
if (List_localServPrnLink.Contains(val))
{
bt_imp.BackgroundImage = global::Test.Properties.Resources.impOK;
}
else
{
bt_imp.BackgroundImage = global::Test.Properties.Resources.impX;
}
bt_imp.Size = new System.Drawing.Size(30, 30);
bt_imp.Location = new Point(horizotal, vertical - bt_imp.Height / 2);
bt_imp.Click += (s, ea) => { MyHandler(sender, e, val); };//passing printer instal link when click
...
vertical += 30;//Prochaine Ligne...
this.Invoke((MethodInvoker)delegate { // runs on UI thread,
tabPage1.Controls.Add(bt_imp);
tabPage1.Controls.Add(lb_impBt);
});
}
... }
答案 0 :(得分:0)
您button3_Click
处理程序中的这一行不正确:
bt_imp.Click += (s, ea) => { MyHandler(sender, e, val); };
它现在正在做的是从调用方法中捕获发送方/事件参数。您要做的是让MyHandler
从bt_imp
点击中获取发件人/参数,因此您需要将其更改为:
bt_imp.Click += (s, ea) => { MyHandler(s, ea, val); };
匿名方法中的命名参数。
您需要做的第二件事是确保在UI线程上调用UI更改。你在button3_Click
处理程序中做得很好,但在MyHandler
例程中错过了它,所以只需在UI线程上调用后台更改:
this.Invoke((MethodInvoker)delegate { // runs on UI thread,
button.BackgroundImage = global::Test.Properties.Resources.impOK;
});
这应该照顾它。