方法一、MouseClick事件
private void ListBox_MouseClick(object sender, MouseEventArgs e)
{
int index = base.IndexFromPoint(e.X, e.Y);
base.SelectedIndex = index;
if (base.SelectedIndex != -1)
{
//逻辑代码
}
}
方法二、MouseDown事件
private void PopUpListBox_MouseDown(object sender, MouseEventArgs e)
{
if (SelectItem != null)
{
GetItemAt(this, e.X,e.Y);
//逻辑代码
}
}
private object GetItemAt(ListBox listBox, int X, int Y)
{
try
{
object res = null;
for (int i = 0; i < listBox.Items.Count; i++)
{
System.Drawing.Rectangle r = listBox.GetItemRectangle(i);
if (r.Contains(new Point(X, Y)))
{
res = listBox.Items[i];
base.SelectedItem = listBox.Items[i];
break;
}
}
return res;
}
catch (Exception ex)
{
throw ex;
}
}
总结:方法一更方便些