Skip to content

Instantly share code, notes, and snippets.

@CamelCaseName
Created July 24, 2023 18:29
Show Gist options
  • Save CamelCaseName/e13f79cb8f43de032e65ffeafac40d27 to your computer and use it in GitHub Desktop.
Save CamelCaseName/e13f79cb8f43de032e65ffeafac40d27 to your computer and use it in GitHub Desktop.
c# TextBox for Search field, with search result counter embedded
using System;
using System.Drawing;
using System.Runtime.Versioning;
using System.Windows.Forms;
namespace CustomComponents
{
//see https://gist.github.com/CamelCaseName/84324c076342c050307af9779a224c3c for the base class
[SupportedOSPlatform("Windows")]
internal sealed class SearchTextBox : HighLightTextBox
{
internal SearchTextBox()
{
PlaceholderColor = SystemColors.GrayText;
}
public int TotalSearchResults
{
get
{
return _totalSearchResults;
}
set
{
if (value < 0)
{
throw new ArgumentOutOfRangeException(
nameof(TotalSearchResults),
$"{nameof(TotalSearchResults)} must not be negative");
}
else
{
_totalSearchResults = value;
_counter = string.Concat(_currentSearchResult.ToString(), "/", _totalSearchResults.ToString());
}
}
}
private int _totalSearchResults = 0;
public int CurrentSearchResult
{
get
{
return _currentSearchResult;
}
set
{
if (value >= 0 && value <= _totalSearchResults)
{
_currentSearchResult = value;
_counter = string.Concat(" ", _currentSearchResult.ToString(), "/", _totalSearchResults.ToString());
InvalidateCounter();
}
}
}
private int _currentSearchResult = 0;
private string _counter = "0/0";
public new string Text
{
get
{
return base.Text;
}
set
{
base.Text = value;
InvalidateCounter();
}
}
private void InvalidateCounter()
{
MeasureCounterText(out Size size, out Point pos);
Invalidate(new Rectangle(pos, size));
}
private void MeasureCounterText(out Size size, out Point pos)
{
size = TextRenderer.MeasureText(_counter, Font);
pos = new Point(
ClientRectangle.Right - size.Width,
(ClientRectangle.Height - size.Height) / 2);
}
protected override void OnPaint(PaintEventArgs e)
{
OnPaintOffset(e, new Point(2, 2));
if (_totalSearchResults > 0)
{
MeasureCounterText(out _, out Point pos);
TextRenderer.DrawText(e.Graphics, _counter, Font, pos, PlaceholderColor, BackColor);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment