private void listBox1_DrawItem(object sender, DrawItemEventArgs e) { if (e.Index >= 0) { e.DrawBackground(); if ((e.State & DrawItemState.Selected) == DrawItemState.Selected) { e.DrawFocusRectangle(); } e.Graphics.DrawString(listBox1.Items[e.Index].ToString(), this.Font, Brushes.Black, e.Bounds); } }
protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); Graphics graphics = e.Graphics; Rectangle rect = new Rectangle(10, 10, 100, 50); using (SolidBrush brush = new SolidBrush(Color.FromArgb(255, 255, 0, 0))) { graphics.FillRectangle(brush, rect); } DrawItemEventArgs args = new DrawItemEventArgs(graphics, this.Font, rect, 0, DrawItemState.None, this.ForeColor, this.BackColor); args.DrawFocusRectangle(); }In both examples, the DrawFocusRectangle method is used to draw a rectangle around a specified item (selected item in a ListBox or a custom area in a control) to indicate it has focus. The DrawItemEventArgs class is part of the System.Windows.Forms package library.