按钮背景图像检查

本文关键字:检查 图像 背景 按钮 | 更新日期: 2023-09-27 18:21:54

请检查按钮的背景图像时遇到问题。如果按钮的图像与资源文件夹中的图像匹配,我想删除该按钮。我试过

    private void DeleteCard(Button btn)
    {
        if (btn.BackgroundImage.Equals( FunWaysInc.Properties.Resources.Card_1))
        {
            playersCards.Remove(Properties.Resources.Card_1);
            MessageBox.Show(playersCards.Count.ToString());
        }
        else
        {
            MessageBox.Show("NO");
        }
    }
    private void frmQuickSpark_Load(object sender, EventArgs e)
    {
        Button tstbtn = new Button();
        tstbtn.BackgroundImage = Properties.Resources.Card_1;
        DeleteCard(tstbtn);
    }

但显示的消息框显示"否"。。

请问发生了什么事????

按钮背景图像检查

添加按钮时

button.Tag = "ToDelete";

然后是

foreach (Button b in this.Controls.OfType<Button>())
{
    if(b.Tag == "ToDelete")
    {
        //delete
    }
}

这里是你必须做的。你需要枚举所有的图像,并将指针存储在按钮的Tag属性中。

private Dictionary<string, Image> _table = new Dictionary<string, Image>();
private void frmQuickSpark_Load(object sender, EventArgs e)
    {
        _table.Add("Image1", Properties.Resources.Card_1);
        _table.Add("Image2", Properties.Resources.Card_2);
        Button btn = new Button();
        SetButtonImage(btn);
        DeleteCard(btn);
    }
 private void SetButtonImage(Button button)
    {
        button.BackgroundImage = _table["Image1"];
        button.BackgroundImage.Tag = "Image1";
    }
    private void DeleteCard(Button btn)
    {
         if (btn.BackgroundImage.Tag == "Image1") 
         {
             playersCards.Remove(btn); // not sure what your logic of removal
             MessageBox.Show(playersCards.Count.ToString());
         }
         else
         {
             MessageBox.Show("NO");
         }
     }

我已经找到了问题的答案。。我刚刚修改了我的代码

private void DeleteCard(Image img)
{
    playersCards.Add(Properties.Resources.Card_1);
    if (img == playersCards[0])
    {
        playersCards.Remove(Properties.Resources.Card_1);
        MessageBox.Show(playersCards.Count.ToString());
    }
    else
    {
        MessageBox.Show("NO");
    }
}
private void frmQuickSpark_Load(object sender, EventArgs e)
{
    Button tstbtn = new Button();
    tstbtn.BackgroundImage = Properties.Resources.Card_1;
    Image img = tstbtn.BackgroundImage;
    DeleteCard(img);
}

它工作得很好。