Home > Software engineering >  How can i toggle the same button click event for two cases?
How can i toggle the same button click event for two cases?

Time:06-27

private void btnRecord_Click(object sender, EventArgs e)
        {
            FFmpeg_Capture record = new FFmpeg_Capture();
            record.Start("Testing", 60);
        }

What i want to do is when i click the button it will change the text of it to "Stop" then when i click again it will do the code :

record.Stop();

and will change the text of the button back to "Record" so i can use the same button to start/stop.

CodePudding user response:

The simplest way may be to introduce the flag which will store the current player state. For just a play/stop this flag may be bool, for more states e.g. play/pause/stop it may be enum. Then you can use this flag to determine the current state and change it accordingly

bool playing = false;
FFmpeg_Capture record = new FFmpeg_Capture();

private void btnRecord_Click(object sender, EventArgs e)
{
    if(playing)
    {
        record.Stop();
        playing = false;
        btnRecord.Text = "Play";
    }
    else
    {
        record.Start("Testing", 60);
        btnRecord.Text = "Stop";
        playing = true;
    }
}

The problem here that you may have other ways to change player's state (for example, by click on the player itself) and thus you will need to maintain the playing flag in all such a places to be in sync with real player state.

So, the better way will be to check the player itself for state (if the player has such an API). I assumed that player has the State property which is enum and this property represtnts the current state. In this case the code may be following. I do not know if the real player has such a property or not, so this is just a idea.

FFmpeg_Capture record = new FFmpeg_Capture();
private void btnRecord_Click(object sender, EventArgs e)
{
    if(record.State is CaptureState.Playing)
    {
        record.Stop();
        btnRecord.Text = "Play";
    }
    else
    {
        record.Start("Testing", 60);
        btnRecord.Text = "Stop";
    }
}

CodePudding user response:

Add a bool for the current button state.

if(button_state)
{
    FFmpeg_Capture record = new FFmpeg_Capture();
    record.Start("Testing", 60);
    button_state != button_state;
    btnRecord.Text = "Stop";
}
else
{
    record.Stop();
    btnRecord.Text = "Record"
    button_state != button_state;
}
  • Related