大家好,我对Multi Thread和ListView Update有一些问题: 我想在Listview中按名称列出正在运行的进程,并在此进程关闭时删除。但是我的代码只是添加了一个新进程,并且在进程关闭时不会删除。我是C#的初学者用户。谢谢。 ***我不想使用listview.Clear()因为我要用多客户端制作一个机器人
这是我的代码:
bool status = true;
int[] PID = new int[10];
Memory Mem = new Memory();
private void startChecking()
{
while (status)
{
try
{
int count = 0;
Process[] processes = Process.GetProcessesByName("notepad");
if (processes.Length > 0)
{
if (listAccount.Items.Count < processes.Length)
{
foreach (Process process in processes)
{
if (listAccount.Items.Count < processes.Length && PID[count] != process.Id)
{
Mem.SetTitle(process.MainWindowHandle, "Cyber Auto - " + count.ToString());
AddItemNew(process.MainWindowTitle);
PID[count] = process.Id;
}
count++;
}
}
else if (listAccount.Items.Count < processes.Length)
{
}
}
Thread.Sleep(1000);
}
catch (Exception ex)
{
MessageBox.Show("Somethine went wrong : " + ex.ToString());
}
}
}
这是我的AddItemNew / RemoveItem方法:
private delegate void dlgAddItemNew(string i);
private void AddItemNew(string i)
{
if (this.listAccount.InvokeRequired)
{
this.Invoke(new dlgAddItemNew(AddItemNew), i);
}
else
{
ListViewItem accountAdd = new ListViewItem(i);
accountAdd.SubItems.Add("0");
accountAdd.SubItems.Add("0");
accountAdd.SubItems.Add("0");
accountAdd.SubItems.Add("0");
this.listAccount.Items.Add(accountAdd);
}
}
private delegate void dlgRemoveItem(int i);
private void RemoveItem(int i)
{
if (this.listAccount.InvokeRequired)
{
this.Invoke(new dlgRemoveItem(RemoveItem), i);
}
else
{
this.listAccount.Items[i].Remove();
}
}
P / S:抱歉,如果我的英语不好......
答案 0 :(得分:2)
如果要定期检查,则可以在再次填充之前清除ListView。 (这就是Captain0在上面的评论中的意思)
我稍微修改了你的代码,当我打开/关闭记事本的实例时,我可以看到它正常工作,它会更新计数,不需要单独的添加/删除项目(除非你在打开和关闭时不得不做些不同的事情)记事本过程)
private void startChecking()
{
while (status)
{
try
{
Process[] processes = Process.GetProcessesByName("notepad");
UpdateListView(processes.Count());
Thread.Sleep(2000);
}
catch (Exception ex)
{
MessageBox.Show("Somethine went wrong : " + ex.ToString());
status = false;
}
}
}
private void UpdateListView(int processCount)
{
if (listView1.InvokeRequired)
{
Action action = () => UpdateListView(processCount);
Invoke(action);
}
else
{
listView1.Items.Clear(); // Clearing the List view before adding them again
for (int i = 0; i < processCount; i++)
{
ListViewItem accountAdd = new ListViewItem(i.ToString());
listView1.Items.Add(accountAdd);
}
}
}