I would like to draw a rectangle around the selected item in a ListView, due to reading somewhere that Microsoft recommends against changing the \'highlighted colour\' of said i
Here is a very basic version for an owner-drawn ListView
. Set the OwnerDraw
property to true and code the DrawItem
event, maybe like this:
private void listView1_DrawItem(object sender, DrawListViewItemEventArgs e)
{
e.DrawBackground();
e.DrawText();
if (e.Item.Selected)
{
Rectangle R = e.Bounds;
R.Inflate(-1, -1);
using (Pen pen = new Pen(Color.Red, 1.5f))
e.Graphics.DrawRectangle(pen, R);
}
}
I make the rectangle a little smaller for it to work in Details View
, but you should play around to make it suit your needs and fancy..!
Note: If you have ColumnHeaders you also need to code the DrawColumnHeader
event, in its simplest form like this:
private void listView1_DrawColumnHeader(object sender,
DrawListViewColumnHeaderEventArgs e)
{
e.DrawDefault = true;
}
And if you have SubItems you need to have a DrawSubItem
event, again at least like this:
private void listView1_DrawSubItem(object sender, DrawListViewSubItemEventArgs e)
{
e.DrawDefault = true;
}
Obviously you need to write more code to this event, if you want your rectangle to be drawn here as well. But the default function of DrawBackground
and DrawText
are available here as well.