/// <summary>
/// Summary description for ListBoxExtender.
/// </summary>
public class ListBoxExtender
{
private ListBox listBox;
private IntPtr handle;
public ListBoxExtender(ListBox listBox)
{
this.listBox = listBox;
// Get native handle
this.listBox.Capture = true;
this.handle = GetCapture();
this.listBox.Capture = false;
}
/// <summary>
/// Searches an item in the ListBox by the specified item value.
/// </summary>
/// <param name="item">Item to search.</param>
/// <returns>The index of the found item.</returns>
public int Search(string item)
{
return Search(item, -1, true);
}
/// <summary>
/// Searches an item in the ListBox by the specified item value.
/// </summary>
/// <param name="item">Item to search.</param>
/// <param name="startIndex">The zero-based index of the item before the first item to be searched.</param>
/// <returns>The index of the found item.</returns>
public int Search(string item, int startIndex)
{
return Search(item, startIndex, true);
}
/// <summary>
/// Searches an item in the ListBox by the specified item value.
/// </summary>
/// <param name="item">Item to search.</param>
/// <param name="startIndex">The zero-based index of the item before the first item to be searched.</param>
/// <param name="exact">Specifies whether the exact or partial search is performed.</param>
/// <returns>The index of the found item.</returns>
public int Search(string item, int startIndex, bool exact)
{
int result = -1;
if (exact)
{
result = SendMessage(handle, LB_FINDSTRINGEXACT, startIndex, item);
}
else
{
result = SendMessage(handle, LB_FINDSTRING, startIndex, item);
}
return result;
}
#region P/Invokes
const int LB_FINDSTRING = 0x018F;
const int LB_FINDSTRINGEXACT = 0x01A2;
[DllImport("coredll.dll")]
static extern IntPtr GetCapture();
[DllImport("coredll.dll")]
static extern int SendMessage(IntPtr hwnd, int msg, int wParam, string lParam);
#endregion
}
The usage of this class should be obviouse:
listBoxEx = new ListBoxExtender(listBox1);
...
listBox1.SelectedIndex = listBoxEx.Search("Some Item");