首页 文章

从代码C#停止事件,用户而不是代码调用事件

提问于
浏览
-1

对不起,这可能是一个重复的问题,但我无法理解已在不同答案中提供的解决方案 .

我以不同的方式创建了一个mp3播放器,它一次播放一个mp3文件但是一个列表框有章节,这不仅处理移动特定mp3的位置而且还改变了一个图片框图像 . 现在某个地方我需要从搜索栏中更改列表框的选择但是不想触发以下事件; private void listBox1_SelectedIndexChanged(object sender,EventArgs e)

请指导 .

2 回答

  • 1

    添加一个名为isProcessing的类范围的布尔值 . 将其设置为true . 做你的工作,然后把它设置为假 . 在布尔值中扭曲事件:

    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;
    }
    
  • 0

    阻止选择索引更改事件正常运行的一种方法是使用布尔标志 . 此外,确保在引发某些异常时此抑制不会保留:

    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
    }
    

    附:尝试为控件使用有意义的名称(检查 listBox1 ) . 重新访问代码和/或others have to时,您会感谢自己 .

相关问题