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
}
}