我有一個函數每10秒獲取運行的應用程序,將它們放在一個列表框中,並將它們發送到另一個窗口,如果您單擊發送按鈕。現在,問題是每當我嘗試打開然後立即關閉一個應用程序,它會發送一個指向我的列表的錯誤。 我不確定這裏要做什麼。索引超出範圍wpf c#
Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index.
這裏是我的代碼,如果在情況下,它帶來任何幫助:
private List<int> listedProcesses = new List<int>();
private void SendData()
{
String processID = "";
String processName = "";
String processFileName = "";
String processPath = "";
string hostName = System.Net.Dns.GetHostName();
listBox1.BeginUpdate();
try
{
for (int i = 0; i < listBox1.Items.Count; i++)
{
piis = GetAllProcessInfos();
try
{
if (!listedProcesses.Contains(piis[i].Id)) //place this on a list to avoid redundancy
{
listedProcesses.Add(piis[i].Id);
processID = piis[i].Id.ToString();
processName = piis[i].Name.ToString();
processFileName = piis[i].FileName.ToString();
processPath = piis[i].Path.ToString();
output.Text += "\n\nSENT DATA : \n\t" + processID + "\n\t" + processName + "\n\t" + processFileName + "\n\t" + processPath + "\n";
}
}
catch (Exception ex)
{
wait.Abort();
output.Text += "Error..... " + ex.StackTrace;
}
NetworkStream ns = tcpclnt.GetStream();
String data = "";
data = "--++" + " " + processID + " " + processPath + " " + processFileName + " " + hostName;
if (ns.CanWrite)
{
byte[] bf = new ASCIIEncoding().GetBytes(data);
ns.Write(bf, 0, bf.Length);
ns.Flush();
}
}
}
finally
{
listBox1.EndUpdate();
}
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
ProcessInfoItem pii = piis.FirstOrDefault(x => x.Id == (int)(sender as ListBox).SelectedValue); //setting value for list box
if (pii != null)
{
string hostName = System.Net.Dns.GetHostName();
textBox4.Text = listBox1.SelectedValue.ToString();
textBox5.Text = (pii.FileName);
textBox6.Text = (pii.Path);
textBox7.Text = hostName;
}
}
private List<ProcessInfoItem> piis = new List<ProcessInfoItem>();
private void Form1_Load(object sender, EventArgs e)
{
piis = GetAllProcessInfos();
listBox1.DisplayMember = "Name";
listBox1.ValueMember = "Id";
listBox1.DataSource = piis;
textBox1.Text = GetIpAdd().ToString();
}
private List<ProcessInfoItem> GetAllProcessInfos()
{
List<ProcessInfoItem> result = new List<ProcessInfoItem>();
Process currentProcess = Process.GetCurrentProcess();
Process[] processes = Process.GetProcesses();
foreach (Process p in processes)
{
if (!String.IsNullOrEmpty(p.MainWindowTitle))
{
ProcessInfoItem pii = new ProcessInfoItem(p.Id,p.MainModule.ModuleName, p.MainWindowTitle, p.MainModule.FileName);
result.Add(pii);
}
}
return result;
}
public class ProcessInfoItem
{
public int Id { get; set; }
public string Name { get; set; }
public string FileName { get; set; }
public string Path { get; set; }
public ProcessInfoItem(int id, string name, string filename, string path)
{
this.Id = id;
this.Name = name;
this.FileName = filename;
this.Path = path;
}
}
它應該是 「listBox1.Items.Count - 1」 在你的for循環 –
@KarthikGanesan OP使用'<'所以'計數'沒問題。 –
爲什麼你認爲'piis'的上限不會大於'listBox1.Items.Count' –