The best thing to do is to override the ProcessCmdKey method in the sub-class. You can then run your search only when the user hits the Enter key (and maybe the tab key) within the textbox. Here's some sample code:
public class SearchTextBox
: TextBox
{
public SearchTextBox() : base() { }
/// <summary>
/// Run search if enter is pressed while in the textbox.
/// </summary>
protected override bool ProcessCmdKey( ref Message msg, Keys keyData )
{
//-- You could also define other keys, such as the tab key here.
if (keyData == Keys.Enter)
{
//-- Run the search
if (this.SearchFunction != null)
{
int count = this.SearchFunction( this.Text );
MessageBox.Show( string.Format( "{0} items found" );
}
else
{
//-- Notify develper that they haven't setup a search function.
MessageBox.Show( string.Format( "No search function defined. Search term is '{0}'", this.Text ) );
}
}
//-- Whatever key is used to run the search
// should also just do whatever it normally does.
return base.ProcessCmdKey( ref msg, keyData );
}
/// <summary>
/// Define the function that runs the search. This
/// function accepts a string search term and return
/// number of items found. You could also use a
/// normal delegate, so you don't have to have a return
/// value.
/// </summary>
public Func<string, int> SearchFunction { get; set; }
/// <summary>
/// Override to always return a string (and never null).
/// </summary>
public override string Text
{
get
{
string text = string.Empty;
if (!string.IsNullOrEmpty( base.Text ))
{
text = base.Text;
}
return text;
}
set
{
base.Text = value;
}
}
}