2017-04-05 43 views
0

我目前正在开发一个聊天程序,想法是让它成为一个秘密(有点像Facebook有秘密聊天功能)。随着时间的推移从列表框中删除项目 - C#;

我的邮件被发送到listBox组件,我希望每10或'n'秒钟最旧的邮件将被删除。我 试图用索引标记每条消息,但不太明白这是如何工作的。

我在问,也许你们知道一个功能,或者可以帮助我写一个能够做到这一点的功能。我正在使用Visual Studio 2015 Windows窗体,C#。

+1

你到目前为止尝试过什么?请提供一些代码,然后我们可以尝试帮助您改进它。 –

+0

请添加winform标签。 – qxg

回答

0

那么,当你有一个ListBox,这些项目都是索引的,因为它是一个对象集合(一个对象数组)。从0开始并向上搜索新条目。

所以我们可以说,我们增加3项我们ListBox

listBox1.Items.Add("Item 1"); //Index 0 
listBox1.Items.Add("Item 2"); //Index 1 
listBox1.Items.Add("Item 3"); //Index 2 

所有你必须做的,是建立在,在指数0(最老的条目),每个删除的项目后台运行一个线程时间。

new Thread(() => 
{ 
    while(true) 
    { 
     if(listBox1.Items.Count > 0) //Can't remove any items if we don't have any. 
     { 
      Invoke(new MethodInvoker(() => listBox1.Items.RemoveAt(0))); //Remove item at index 0. 
      //Needs invoking since we're accessing 'listBox1' from a separate thread. 
     } 
     Thread.Sleep(10000); //Wait 10 seconds. 
    } 
}).Start(); //Spawn our thread that runs in the background. 
1

在C#中的WinForms一个ListBox包含ListBoxItems这是一个ObjectCollection(msdn-link

所以,你可以添加任何你喜欢的对象,这将显示来自将DisplayMember

所以对于消息示例

public class MyMessage { 
    public DateTime Received { get; set; } 
    public string Message { get; set; } 
    public string DisplayString 
    { 
     get { return this.ToString(); } 
    } 
    public string ToString() { 
     return "[" + Received.ToShortTimeString() + "] " + Message; 
    } 
} 

可以作为ListBoxItem添加。

将DisplayMember设置为"DisplayString"more here)会为您提供正确的输出。

现在您可以遍历ListBoxItems,将它们转换为MyMessage并检查它们的接收时间。

0

我不知道你是否想过这个,但是这里有一种方法可以实现这个任务。

首先创建一个Liststrings

List<string> list1 = new List<string>(); 

要使用列表功能,你将不得不在表单中

using System.Collections; 

收藏现在到了棘手的部分。

首先在全局声明一个静态整数变量,即在所有类之外。

static int a; 

每当你收到一条消息(考虑您的邮件将在字符串格式),你已经到字符串添加到您创建list1

list1.Add("the received message");  

现在你已经声明了一个计时器(如果你是新手,请看看计时器是如何工作的)。Windows窗体已经有了定时器,使用它会更好。 计时器在所需的时间后发送一个Tick事件。

private void timer1_Tick(object sender, EventArgs e) 
    { 
     a = list1.Count() - 1; //Count will return the number of items in the list, you subtract 1 because the indexes start from 0 
     list1.RemoveAt(a); 
     listBox.Items.Clear(); 
     foreach(string x in list1) 
     { 
       listBox.Items.Add(x); 
     } 
    } 

这段代码要做的是,在timer的每Tick event这将刷新列表框,从数组中删除最后一个元素,并补充,其余的列表框中。

要使用计时器只需将其拖放到窗体上即可。这都是基于GUI的,很容易理解。

让我知道你是否怀疑。

提示:尽量使用try{} & catch{}块以避免应用程序崩溃。

+0

根据'listBox'中项目的顺序,你可能想要使用'listBox.Items.Append'或'.Insert'。与foreach相比,节省了一些时间,重新创建了整个列表。 –

+0

@MarkusDeibel它可以节省时间,但这不是要求。列表框需要被清除,然后在没有最后一条消息的情况下重新填充。你的意思是别的吗? –

+0

您是否可以不删除'Items'中的最后一个项目,并且列表框会反映更改?你真的需要重新填写物品清单以便重新绘制吗? –