[英]stopping event from code C#, call event by user not by code
抱歉,这可能是一个重复的问题,但我无法理解不同答案中已经提供的解决方案。
我以不同的方式创建了一个 mp3 播放器,它一次播放一个 mp3 文件,但一个列表框有章节,这不仅可以处理移动该特定 mp3 的位置,还可以更改图片框图像。 现在在某处我需要从搜索栏中更改列表框的选择,但不想触发以下事件; private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
请指导。
阻止您的选择索引更改事件按照正常方式进行的一种方法是使用布尔标志。 另外,请确保在引发某些异常时这种抑制不会继续存在:
private bool inhibit = true;
private void doSomeProcessWithInhibit()
{
try
{
inhibit = true;
// processing comes here
}
// if something goes wrong, make sure other functionality is not blocked
finally
{
inhibit = false;
}
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
// fast return to reduce nesting
if (inhibit)
return;
// do event handling stuff here
}
PS 尝试为控件使用有意义的名称(检查listBox1
)。 当您重新访问代码和/或其他人必须这样做时,您会感谢自己。
添加一个具有类范围的布尔值,称为 isProcessing。 将其设置为真。 做你的工作,然后将其设置为false。 在布尔值中扭曲您的事件:
bool isProcessing = true;
private void switchControls(){
isProcessing = true;
//do work;
isProcessing = false;
}
private void MyControl.OnEvent(object sender, EventArgs e){
if(!isProcessing){
//what you would normally do
}
}
或者....
取消注册事件,重新注册它
private void switchControls(){
myButton1.OnClick -= myButtonClick;
//do work
myButton1.OnClick += myButtonClick;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.