简体   繁体   English

每隔几秒钟刷新一次ListBox项C#

[英]Refreshing ListBox items every few seconds C#

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

private void Form1_Load(object sender, EventArgs e)
{
    Process[] processes = Process.GetProcesses();

    foreach (var proc in processes)
    {
        if (!string.IsNullOrEmpty(proc.ProcessName))
            listbox.Add(proc.ProcessName);
    }
    listBox1.DataSource = listbox;
}

While using that code, I get a ListBox (listBox1) which shows all of the currently running processes, but what can I adjust of this code/add to make it refresh the ListBox every 5 seconds, since it only shows the programs that were open when the application was opened, and if an application is closed/opened while it is opened, it won't be added to the ListBox, hence why I want it to refresh every 5 seconds or so. 使用该代码时,我得到一个ListBox(listBox1),该列表显示了所有当前正在运行的进程,但是我可以如何调整此代码/添加以使其每5秒刷新一次ListBox,因为它仅显示打开的程序当打开应用程序时,并且如果在打开时关闭/打开了应用程序,则不会将其添加到ListBox中,因此为什么我希望每隔5秒钟刷新一次。

You can use a Timer like this: 您可以使用如下Timer

private Timer m_Timer;

private void Form1_Load(object sender, EventArgs e)
{
    RefreshProcesses();

    m_Timer = new Timer();

    m_Timer.Interval = 5000;
    m_Timer.Tick += timer_Tick;
    m_Timer.Start();
}

void timer_Tick(object sender, EventArgs e)
{
    RefreshProcesses();
}

private void RefreshProcesses()
{
    List<string> listbox = new List<string>();

    Process[] processes = Process.GetProcesses();

    foreach (var proc in processes)
    {
        if (!string.IsNullOrEmpty(proc.ProcessName))
            listbox.Add(proc.ProcessName);
    }
    listBox1.DataSource = listbox;
}

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

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