如何为标准的ListBox添加ItemClick事件

今天在项目中遇到了一个小问题,需要给ListBox添加ItemClick事件,很简单:

 public class MyListBox:ListBox
    {
        private static readonly object EventItemClick = new object();
        public event EventHandler<ListBoxItemEventArgs> ItemClick
        {
            add
            {
                Events.AddHandler(EventItemClick, value);
            }
            remove
            {
                Events.RemoveHandler(EventItemClick, value);
            }
        }      
      
       
        protected virtual void OnItemClick(ListBoxItemEventArgs e)
        {
            EventHandler<ListBoxItemEventArgs> handler = (EventHandler<ListBoxItemEventArgs>)this.Events[EventItemClick];
            if (handler != null)
            {
                handler(this, e);
            }
        }

        protected override void OnClick(EventArgs e)
        {
            base.OnClick(e);
            for (int i = 0; i < this.Items.Count; i++)
            {
                bool flag = this.GetItemRectangle(i).Contains(this.PointToClient(Control.MousePosition));
                if (flag)
                {
                    ListBoxItemEventArgs args = new ListBoxItemEventArgs(i);
                    OnItemClick(args);
                    break;
                }
            }
        }
    }

    public class ListBoxItemEventArgs : EventArgs
    {
        private int _listBoxItem;

        public ListBoxItemEventArgs(int listBoxItem)
        {
            _listBoxItem = listBoxItem;
        }

        public int ListBoxItem
        {
            get
            {
                return _listBoxItem;
            }
        }
    }

原文地址:https://www.cnblogs.com/xixifusigao/p/1518530.html