繁体   English   中英

更新时,如何检查listBox中的项目是否已经存在?

[英]How can i check if items in the listBox already exist when i update it?

这是我刷新和更新listBox列表的方式:

private void RefreshWindowsList()
        {
            ClearGraphics = true;
            this.listBoxSnap.Items.Clear();
            this.pictureBoxSnap.Image = null;
            buttonSnap.Enabled = false;
            this.listBoxSnap.Items.AddRange(WindowSnap.GetAllWindows(true, true).ToArray());
            buttonSnap.Enabled = true;
            for (int i = listBoxSnap.Items.Count - 1; i >= 0; i--)
            {
                string tt = listBoxSnap.Items[i].ToString();
                if (tt.Contains(" ,"))
                {
                    listBoxSnap.Items.RemoveAt(i);
                }
            }
            rectangles = new Rectangle[listBoxSnap.Items.Count];
            textBoxIndex.Text = listBoxSnap.Items.Count.ToString();
            if (this.listBoxSnap.Items.Count > 0)
                this.listBoxSnap.SetSelected(0, true);
            listBoxSnap.Select();
        }

我正在清除列表框,正在清除图片框,然后将项目再次添加到列表框中:

this.listBoxSnap.Items.AddRange(WindowSnap.GetAllWindows(true, true).ToArray());

我在form1构造函数中然后在其他两个地方调用此方法一次:单击按钮事件和倒计时的计时器滴答事件。

相反,我想更改此方法,以便它将检查是否有任何新项目或从中删除的项目:

WindowSnap.GetAllWindows(true, true).ToArray()

如果有新的窗口(项目),如果上次删除了某些项目,则将它们添加到listBox中,然后将它们从listBox中删除而不清除listBox和pictureBox只是根据WindowSnap.GetAllWindows(true)的方式添加/删除项目。 ,true).ToArray()已更改。

所以我以后可以删除/删除这两行:

this.listBoxSnap.Items.Clear();
this.pictureBoxSnap.Image = null;

编辑:

另一个问题是,例如,如果我删除一个窗口,例如,我打开了一个新的Chrome窗口(不是选项卡,而是窗口),则listBox已更新,我单击了该项目并看到了它的快照,但是如果我关闭了该窗口怎么办? 现在如何知道其中包含图像的pictureBox不显示它? 我不想做:

this.listBoxSnap.Items.Clear();
this.pictureBoxSnap.Image = null;

因为它正在眨眼。 我想以其他方式根据WindowSnap.GetAllWindows(true,true).ToArray()的更新来更新listBox和pictureBoxSnap

删除旧的:

IEnumerable<TypeIDontKnow> someCollection = WindowSnap.GetAllWindows(true, true).ToArray();
foreach (var item in listBoxSnap.Items)
{
     if (!someCollection.Contains(item))
          listBoxSnap.Items.Remove(item);
}

添加新的:

listBoxSnap.Items.AddRange(someCollection.Where(x => !listBoxSnap.Contains(x))

我把这个写出来了-我不确定演员表是否还好等

您可以搜索该项目是否存在并替换。

// Set the search string:
string myString = "ITEM NAME";
// Search starting from index -1:
int index = listBox1.FindString(myString, -1);
if (index != -1)
{
    // Select the found item:
    listBox1.SetSelected(index, true);
    // Send a success message:
    MessageBox.Show("Found the item \"" + myString + "\" at index: " + index);
}
else
{
    MessageBox.Show("Item not found.");
}

资源

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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