私はwinboxカスタムコントロールを作成しました。このコントロールには、同じバインディングソースを共有するテキストボックスとリストボックスがあり、リストボックスをテキストボックス入力でフィルタリングできるようになっています。winform listbox drawitem changeサブストリングの色
フィルタリングされたアイテムが部分文字列としてテキストを検索して異なる色または強調表示されるように、lisboxドローアイテムをオーバーライドする必要があります。 (例:)以下のサンプル画像のような黄色のハイライトが必要です。
私は
private void DrawItemHandler(object sender, DrawItemEventArgs e)
{
this.Invoke((MethodInvoker)delegate
{
e.DrawBackground();
e.DrawFocusRectangle();
string MyString = listBox.GetItemText(listBox.Items[e.Index]);
string stringToFind = searchInput.Text ;
if (!string.IsNullOrEmpty(stringToFind))
{
List<int> positions = new List<int>();
int pos = 0;
while ((pos < MyString.Length) && (pos = MyString.IndexOf(stringToFind, pos, StringComparison.InvariantCultureIgnoreCase)) != -1)
{
positions.Add(pos);
pos += stringToFind.Length;
}
int c = 0, nLen = 0, width = 0;
Rectangle rect = e.Bounds;
rect.X = width;
do
{
if (positions.Contains(c))
{
//int opacity = 128;
e.Graphics.DrawString(MyString.Substring(c, stringToFind.Length),
e.Font,
//new SolidBrush(Color.FromArgb(opacity, Color.LightYellow)),
new SolidBrush(Color.LightYellow),
rect);
nLen = MyString.Substring(c, stringToFind.Length).Length;
width += nLen;
}
else
{
e.Graphics.DrawString(MyString[c].ToString(),
e.Font,
new SolidBrush(listBox.ForeColor),
rect);
nLen = MyString[c].ToString().Length;
width += nLen;
}
rect.X = width;
}
while ((c += nLen) < MyString.Length);
}
else
{
e.Graphics.DrawString(MyString,
e.Font,
new SolidBrush(listBox.ForeColor),
e.Bounds);
}
});
}
以下のように行なったし、結果は上書き文字という項目のテキストでした。
私はエラー部分を特定することはできません、それは矩形の境界や巾着部分です。また、項目の背景色とは別に、項目テキストの部分文字列の背景を変更する方法もあります。これで私を助けてください。
ストリングのその背景を変更するには、私はあなたが最初FillRectangleを使用する必要があります容疑者と、カスタムのBackColor使用を使用するには、その長方形 – Pikoh
上巾着DrawStringではなくTextRenderer! rectangle.Xを進める方法は、ピクセルではなく文字列で文字列の長さを使用しています。 Graphics.MeasureString(... Typographics)を使用して、強調表示されている部分の幅を調べます。 – TaW
FillRectangleの提案でMeasureStringを試してみましたが、私はその違いを見ることができますが、微調整はまだ必要ありません。みんなありがとう。 – madmonk88