Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/331.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 以编程方式触发System.Windows.Forms.Control事件_C#_.net_Winforms - Fatal编程技术网

C# 以编程方式触发System.Windows.Forms.Control事件

C# 以编程方式触发System.Windows.Forms.Control事件,c#,.net,winforms,C#,.net,Winforms,假设我有一个复选框控件: CheckBox cb = new CheckBox(); cb.CheckedChanged += delegate(object sender, EventArgs e) { MessageBox.Show("hello"); }; 如何以编程方式触发此事件 我能行 cb.Checked = !cb.Checked; cb.Checked = !cb.Checked; 但这很难看,会触发两次…我会重构您的代码: CheckBox cb = new Che

假设我有一个复选框控件:

CheckBox cb = new CheckBox();
cb.CheckedChanged += delegate(object sender, EventArgs e)
{
    MessageBox.Show("hello");
};
如何以编程方式触发此事件

我能行

cb.Checked = !cb.Checked;
cb.Checked = !cb.Checked;

但这很难看,会触发两次…

我会重构您的代码:

CheckBox cb = new CheckBox();
cb.CheckedChanged += delegate(object sender, EventArgs e)
{
    ShowMessageBox();
};

private void ShowMessageBox()
{
    MessageBox.Show("hello");
}
现在,调用
ShowMessageBox
,而不是尝试模拟事件。将您需要的任何信息从事件传递到方法,以防它需要更多的信息来执行其任务:

cb.CheckedChanged += delegate(object sender, EventArgs e)
{
    ShowMessageBox(cb.Checked);
};

private void ShowMessageBox(bool checkedValue)
{
    MessageBox.Show(string.Format("The box was {0}checked", 
        checkedValue ? "" : "un"));
}

我将重构您的代码:

CheckBox cb = new CheckBox();
cb.CheckedChanged += delegate(object sender, EventArgs e)
{
    ShowMessageBox();
};

private void ShowMessageBox()
{
    MessageBox.Show("hello");
}
现在,调用
ShowMessageBox
,而不是尝试模拟事件。将您需要的任何信息从事件传递到方法,以防它需要更多的信息来执行其任务:

cb.CheckedChanged += delegate(object sender, EventArgs e)
{
    ShowMessageBox(cb.Checked);
};

private void ShowMessageBox(bool checkedValue)
{
    MessageBox.Show(string.Format("The box was {0}checked", 
        checkedValue ? "" : "un"));
}

如果有多个事件附加到CheckedChanged?我需要模拟一个真实的事件…@Anders:我不知道在
复选框中有什么方法可以做到这一点。对于常规按钮,有一个方法,但在
CheckBox
(我知道)上没有类似的方法。@Anders:从CheckBox派生您自己的类,并添加一个调用OnCheckChanged()的公共方法。唯一的办法。它很臭,其他代码不会指望Checked属性没有实际更改,它甚至可能不会检查值。@Hans:(+1)是的,这很臭,我真的希望有一个更通用的解决方案。如果CheckedChanged附加了多个事件?我需要模拟一个真实的事件…@Anders:我不知道在
复选框中有什么方法可以做到这一点。对于常规按钮,有一个方法,但在
CheckBox
(我知道)上没有类似的方法。@Anders:从CheckBox派生您自己的类,并添加一个调用OnCheckChanged()的公共方法。唯一的办法。它很臭,其他代码不会指望Checked属性没有实际更改,它甚至可能不会检查值。@Hans:(+1)是的,这很臭,我真的希望有一个更一般的解决方案。