C#控件开发之ListBox的项变动消息及可以衍生的事件

ListBox控件项目变动的时候是没有事件的,只能自定义一套

不废话,直接上代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;

namespace Test.Controls
{
    public class ListBoxEx:ListBox
    {

        #region 定义消息常数
        /// <summary>【缓存变量】ListBox添加消息</summary>
        private const int LB_ADDSTRING = 0x180;
        /// <summary>【缓存变量】ListBox插入消息</summary>
        private const int LB_INSERTSTRING = 0x181;
        /// <summary>【缓存变量】ListBox移除消息</summary>
        private const int LB_DELETESTRING = 0x182;
        #endregion

        #region 定义事件
        public event EventHandler<ListItemChangedEventArgs> ItemAdded;
        public event EventHandler<ListItemChangedEventArgs> ItemInserted;
        public event EventHandler<ListItemChangedEventArgs> ItemRemoved;
        #endregion

        #region 唤起事件的过程
        protected void OnItemAdded(ListItemChangedEventArgs e)
        {
            if (ItemAdded == null)
                return;
            ItemAdded(this, e);
        }

        protected void OnItemInserted(ListItemChangedEventArgs e)
        {
            if (ItemInserted == null)
                return;
            ItemInserted(this, e);
        }
        protected void OnItemRemoved(ListItemChangedEventArgs e)
        {
            if (ItemRemoved == null)
                return;
            ItemRemoved(this, e);
        }

        #endregion

        #region 监控系统消息
        protected override void WndProc(ref Message m)
        {
            var itemIndex = 0;
            var itemValue = string.Empty;
            switch (m.Msg)
            {
                case LB_ADDSTRING:
                    itemValue = Marshal.PtrToStringUni(m.LParam);
                    OnItemAdded(new ListItemChangedEventArgs(this.Items.Count-1,itemValue));
                    break;
                case LB_INSERTSTRING:
                    itemIndex = (int)m.WParam;
                    itemValue = Marshal.PtrToStringUni(m.LParam);
                    OnItemInserted(new ListItemChangedEventArgs(itemIndex,itemValue));
                    break;
                case LB_DELETESTRING:
                    itemIndex = (int)m.WParam;
                    itemValue = Marshal.PtrToStringUni(m.LParam);
                    OnItemRemoved(new ListItemChangedEventArgs(itemIndex, itemValue));
                    break;
                default:
                    break;
            }
            base.WndProc(ref m);
        }
        #endregion



    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值