简体   繁体   中英

stopping event from code C#, call event by user not by code

Sorry, this may be a duplicate question, but I couldnot understand the solutions already provided in different answers.

I have created a mp3 player in a different manner, it plays one mp3 file at a time but one listbox have the chapters, which is not only handling to move position of that particular mp3 but also changes a picturebox image. Now somewhere I need to change the selection of the listbox from a seekbar but dont want to fire the following event of; private void listBox1_SelectedIndexChanged(object sender, EventArgs e)

Please guide.

One way to inhibit your selection indexed change event doing its normal way is to use a boolean flag. Also, make sure that this inhibition does not stay around when some exception is raised:

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 Try to use meaningful names for controls (check listBox1 ). You will thank yourself when revisiting the code and/or others have to .

Add a Boolean with class scope called something like isProcessing. Set it to true. Do your work, then set it to false. Warp your event in the Boolean:

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
   }
}

OR....

Deregister the event, the re-register it

private void switchControls(){
     myButton1.OnClick -= myButtonClick;
     //do work
     myButton1.OnClick += myButtonClick;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM