我需要在同一个按钮点击事件中实现MP3播放器的Pause和Resume事件。以下是我试过的代码,它不起作用,任何人都可以给我解决方案
private void button3_Click(object sender, EventArgs e)
{
if (button3.Text == "Pause")
{
CommandString = "pause mp3file";
mciSendString(CommandString, null, 0, 0);
Status = true;
button3.Text = "Resume";
}
if (button3.Text == "Resume")
{
CommandString = "resume mp3file";
mciSendString(CommandString, null, 0, 0);
}
}
答案 0 :(得分:5)
您正在更改第一个if语句中的button3.Text属性。 当第二个if语句被测试时,它是真的(当Text属性为“Pause”时,两个if语句都在单击每个按钮时运行)
使用if,else来运行一个或另一个代码块。
如果您希望在第二个代码块上运行测试,请使用if,else if语句。
您还应该考虑这两种情况都不正确的可能性。
if (button3.Text == "Pause")
{
CommandString = "pause mp3file";
mciSendString(CommandString, null, 0, 0);
Status = true;
button3.Text = "Resume";
}
else if(button3.Text == "Resume")
{
CommandString = "resume mp3file";
mciSendString(CommandString, null, 0, 0);
button3.Text = "Pause";
}
答案 1 :(得分:4)
if (button3.Text == "Resume")
{
CommandString = "resume mp3file";
mciSendString(CommandString, null, 0, 0);
}
你错过了这条线:
button3.Text = "Pause";
实际上,通过text属性检查按钮状态并不是一个好主意。作为一个简单的解决方案,您需要有一个布尔标志来检查它。
答案 2 :(得分:1)
如果连续的if语句有两个。你只需要一个if / else语句。
将您的代码更改为:
if (button3.Text == "Pause")
{
CommandString = "pause mp3file";
mciSendString(CommandString, null, 0, 0);
Status = true;
button3.Text = "Resume";
}
else if (button3.Text == "Resume")
{
CommandString = "resume mp3file";
mciSendString(CommandString, null, 0, 0);
}
答案 3 :(得分:0)
问题是:
当你到达第二个if语句时,你已经改变了按钮的文本,因此两个语句都在运行......
这是一个快速测试:
if (button1.Text == "Pause")
{
label1.Text = label1.Text + " saw pause ";
button1.Text = "Resume";
}
if (button1.Text == "Resume")
{
label1.Text = label1.Text + " saw resume ";
button1.Text = "Pause";
}
返回:label1看到暂停看到恢复。
有两种方法可以解决这个问题:
您可以插入'return;'每个if语句中的语句:
private void button3_Click(object sender, EventArgs e)
{
if (button3.Text == "Pause")
{
CommandString = "pause mp3file";
mciSendString(CommandString, null, 0, 0);
Status = true;
button3.Text = "Resume";
return;
}
if (button3.Text == "Resume")
{
CommandString = "resume mp3file";
mciSendString(CommandString, null, 0, 0);
button3.Text = "Pause";
return;
}
}
或者其次,您可以捕获按钮文本的值一次:
private void button3_Click(object sender, EventArgs e)
{
String value = button3.Text;
if (value == "Pause")
{
CommandString = "pause mp3file";
mciSendString(CommandString, null, 0, 0);
Status = true;
button3.Text = "Resume";
}
if (value == "Resume")
{
CommandString = "resume mp3file";
mciSendString(CommandString, null, 0, 0);
buton3.Text = "Pause"; // As mentioned before, this is required too.
}
}
希望有所帮助。
史蒂夫