如何设置或获取按钮背景图像(甚至按钮图像)?

时间:2017-04-25 10:49:37

标签: c# winforms

我的winform上有Play button名为btnplay。我通过图像(play.png)设置背景图像。我想在点击btnplay时将其背景图像更改为另一个图像(pause.png)。我写这个条件代码,但它不起作用!

string customPath = "../img/";
string playImageFilename = "play.png";
if (btnplay.BackgroundImage == Image.FromFile(Path.Combine(customPath, playImageFilename)))
        {...}

2 个答案:

答案 0 :(得分:1)

我建议您使用Button Tag属性。因此,当您加载“播放”背景图片时,请将Tag属性设置为“播放”,当您将其更改为暂停时,将Tag设置为“暂停”

因此,在按钮点击事件中,您可以执行以下操作:

string customPath = "../img/";
string playImageFilename = "play.png";
string pauseImageFilename = "pause.png";

if (btnplay.Tag.ToString() == "pause")
{
     btnplay.BackgroundImage = Image.FromFile(Path.Combine(customPath, playImageFilename);
     btnplay.Tag= "play";
}
else
{
     btnplay.BackgroundImage = Image.FromFile(Path.Combine(customPath, pauseImageFilename);
     btnplay.Tag= "pause";
}

答案 1 :(得分:0)

btnPlay点击事件处理程序之外声明一个变量。

private bool playing = false;
private void btnPlay_Click(object sender, System.EventArgs e)
{
   if (playing)
   {
       // set play image
   }
   else
   {
      // set pause image
   }
   playing = !playing;
}