如何动态更改listview中的背景颜色

时间:2017-04-07 10:28:40

标签: c# winforms listview

我正在创建winforms应用程序,用于在我的网络中进行主机监控。我正在ping IP地址,ping的结果显示在listview中(主机IP地址,延迟时间,主机描述)。

当此设备为TIMEOUT时,如何动态更改列表视图中显示的设备颜色?

这是我的主要表格的代码:

public partial class MainFrm : Form
{
    private string XmlPath;
    private Checker Checker;
    private ResourceManager _rm;
    OpenFileDialog ofd = new OpenFileDialog();

    public MainFrm()
    {
        InitializeComponent();

        _rm = new ResourceManager("HostMonitor.Resources", System.Reflection.Assembly.GetExecutingAssembly());

        //assign events to dataset
        hosts.Groups.TableNewRow += new DataTableNewRowEventHandler(Groups_TableNewRow);
        hosts.Groups.GroupsRowChanged += new HostsData.GroupsRowChangeEventHandler(Groups_GroupsRowChanged);
        hosts.Groups.GroupsRowDeleted += new HostsData.GroupsRowChangeEventHandler(Groups_GroupsRowDeleted);

        hosts.Hosts.TableNewRow += new DataTableNewRowEventHandler(Hosts_TableNewRow);
        hosts.Hosts.HostsRowChanged += new HostsData.HostsRowChangeEventHandler(Hosts_HostsRowChanged);


        XmlPath = Path.GetDirectoryName(Path.GetDirectoryName(Application.ExecutablePath));
        XmlPath = Path.Combine(Path.GetDirectoryName(XmlPath), "hosts.xml");

        XmlPath=Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "hosts.xml");

        hosts.ReadXml(XmlPath);

        DataRelation rel = new DataRelation("HostsInGroup", hosts.Groups.Columns["GroupName"], hosts.Hosts.Columns["Group"]);
        hosts.Relations.Add(rel);

        LoadData();

        //start pinging
        Checker = new Checker(comps, this);
        Checker.Start();

    }

    void Hosts_HostsRowChanged(object sender, HostsData.HostsRowChangeEvent e)
    {
        HostsData.HostsRow row = (HostsData.HostsRow)e.Row;
        foreach (ListViewItem item in comps.Items)
        {                
            if (item.Tag == row)
            {
                item.Text = row.HostName;
                item.SubItems[2].Text = row.Description;
                if ((item.Group == null) || (item.Group.Header != row.Group))
                {
                    foreach (ListViewGroup gr in comps.Groups)
                    {
                        if (gr.Header == row.Group)
                        {
                            item.Group = gr;
                            break;
                        }

                    }
                }
                break;


            }
        }
    }

    void Hosts_TableNewRow(object sender, DataTableNewRowEventArgs e)
    {
        HostsData.HostsRow row = (HostsData.HostsRow)e.Row;
        ListViewGroup group = null;
        if (row.Group!="")
        {
            foreach (ListViewGroup gr in comps.Groups)
            {
                if (gr.Header == row.Group)
                {
                    group = gr;
                    break;
                }
            } 
        }

        ListViewItem item = new ListViewItem(group);
        item.Text = row.HostName;
        item.Tag = row;
        item.SubItems.Add("");
        item.SubItems.Add(row.Description);
        comps.Items.Add(item);
    }

    void Groups_GroupsRowDeleted(object sender, HostsData.GroupsRowChangeEvent e)
    {
        HostsData.GroupsRow row = (HostsData.GroupsRow)e.Row;
        foreach (ListViewGroup gr in comps.Groups)
        {
            if (gr.Tag == row)
            {
                comps.Groups.Remove(gr);
                return;
            }
        }
    }

    void Groups_GroupsRowChanged(object sender, HostsData.GroupsRowChangeEvent e)
    {
        HostsData.GroupsRow row = (HostsData.GroupsRow)e.Row;
        foreach (ListViewGroup gr in comps.Groups)
        {
            if (gr.Tag == row)
            {
                gr.Header = row.GroupName;
                return;
            }
        }
    }

    void Groups_TableNewRow(object sender, DataTableNewRowEventArgs e)
    {            
        ListViewGroup gr = new ListViewGroup();
        HostsData.GroupsRow row = (HostsData.GroupsRow)e.Row;
        gr.Header = row.GroupName;
        gr.Tag = row;
        comps.Groups.Add(gr);
    }

    private void LoadData()
    {
        comps.Items.Clear();
        comps.Groups.Clear();

        foreach (HostsData.GroupsRow group in hosts.Groups)
        {
            ListViewGroup gr = new ListViewGroup();
            gr.Header = group.GroupName;
            gr.Tag = group;
            comps.Groups.Add(gr);                
            foreach (HostsData.HostsRow host in group.GetChildRows("HostsInGroup"))
            {
                ListViewItem ht = new ListViewItem(gr);
                ht.Text = host.HostName;
                ht.SubItems.Add("---");
                ht.SubItems.Add(host.Description);
                ht.Tag = host;
                comps.Items.Add(ht);
            }
        }
    }

这是我班级Checker的代码:

public class Checker
{
    private class CheckHostEventArgs:EventArgs
    {
        private string _hostname;            
        private ListViewItem _item;            

        public string HostName
        {
            get { return _hostname;}
        }           

        public ListViewItem Item
        {
            get { return _item;}               
        }


        public CheckHostEventArgs(string HostName, ListViewItem item)
        {
            _hostname=HostName;
            _item=item;
        }
    }

    private delegate PingReply CheckHost(CheckHostEventArgs e);
    private delegate ListViewItem[] GetCompsDelegate();

    private ListView _list;
    private MainFrm _frm;
    private int AsyncCount = 0;
    private Thread _thread;
    private ResourceManager _rm;

    public Checker(ListView list,MainFrm form)
    {
        _rm = new ResourceManager("HostMonitor.Resources", System.Reflection.Assembly.GetExecutingAssembly());
        _list = list;
        _frm = form;
    }

    public void Start()
    {
        _thread = new Thread(Main);
        _thread.Start();
    }


    private void Main()
    {
        try
        {
            while (true)
            {
                OneLoop();
                Int64 time = Environment.TickCount + Config.Interval;
                while (Environment.TickCount < time)
                {
                    Thread.Sleep(100);
                }
            }
        }
        catch (ThreadAbortException)
        {
            return;                
        }
    }

    private void OneLoop()
    {
        foreach (ListViewItem item in GetComps())
        {
            HostsData.HostsRow host = (HostsData.HostsRow)item.Tag;

            //eliminujemy nieaktywne hosty
            if (host.HostName == "")
            {

                continue;
            }
            if (!host.Active)
            {
                continue;
            }
            HostsData.GroupsRow group = (HostsData.GroupsRow)item.Group.Tag;
            if (!group.Active)
            {
                continue;
            }

            //sprawdzamy aktywne hosty
            lock (this)
            {
                if (AsyncCount < Config.MaxAsyncPings)
                {
                    AsyncCount++;
                    CheckHost del = new CheckHost(Check);
                    CheckHostEventArgs e = new CheckHostEventArgs(host.HostName, item);
                    del.BeginInvoke(e, new AsyncCallback(CheckCallback), item);
                }
            }
        }
    }

    private PingReply Check(CheckHostEventArgs e)
    {
        Ping p = new Ping();
        try
        {
            return p.Send(e.HostName, Config.Timeout);
        }
        catch
        {

            return null;
        }


    }

    private void CheckCallback(IAsyncResult asResult)
    {
        if (asResult.IsCompleted)
        {
            if (_frm.InvokeRequired)
            {
                AsyncCallback del = new AsyncCallback(CheckCallback);
                _frm.Invoke(del, asResult);
            }
            else
            {
                try
                {
                    AsyncResult ar = (AsyncResult)asResult;
                    CheckHost del = (CheckHost)ar.AsyncDelegate;
                    PingReply r = del.EndInvoke(asResult);
                    ListViewItem item = (ListViewItem)ar.AsyncState;
                    if (r != null)
                    {                            
                        switch (r.Status)
                        {
                            case IPStatus.Success:
                                item.SubItems[1].Text = String.Format("{0}", r.RoundtripTime);
                                break;
                            default:
                                item.SubItems[1].Text = r.Status.ToString();
                                break;
                        }
                    }
                    else
                    {
                        item.SubItems[1].Text = _rm.GetString("CheckerErrorOccured");
                    }
                }
                catch
                {}
                lock (this)
                {
                    AsyncCount--;
                }                    
            }                
        }
    }

    private ListViewItem[] GetComps()
    {
        if (_frm.InvokeRequired)
        {
            GetCompsDelegate d = new GetCompsDelegate(GetComps);
            return (ListViewItem[])_frm.Invoke(d);
        }
        else
        {
            ListViewItem[] result=new ListViewItem[_list.Items.Count];
            _list.Items.CopyTo(result, 0);
            return result;
        }
    }

    public void Stop()
    {
        _thread.Abort();
    }
}

1 个答案:

答案 0 :(得分:0)

使用以下代码更改列表视图中项目的背景颜色:

        if (timedout)
            listview1.Items[row].BackColor = Color.LightCoral;
        else //reset the color
            listview1.Items[row].BackColor = listview1.BackColor;

此外,由于您的检查程序运行在与主窗体不同的线程上,因此您必须将此代码放在单独的函数中并使用调用来调用它。