Skip to content

Instantly share code, notes, and snippets.

@RonenNess
Last active March 20, 2022 22:33
Show Gist options
  • Save RonenNess/025becfbe3df5113528157d1144cb872 to your computer and use it in GitHub Desktop.
Save RonenNess/025becfbe3df5113528157d1144cb872 to your computer and use it in GitHub Desktop.
Snippet to turn a ListBox into a colored logs renderer
public Form1()
{
InitializeComponent();
// set custom draw method
List_EventsLog.DrawMode = DrawMode.OwnerDrawVariable;
List_EventsLog.DrawItem += List_EventsLog_DrawItem;
}
/// <summary>
/// Draw an item in the events list.
/// Implements color based on log level.
/// </summary>
private void List_EventsLog_DrawItem(object sender, DrawItemEventArgs e)
{
e.DrawBackground();
if (e.Index == -1) { return; }
Graphics g = e.Graphics;
string text = List_EventsLog.Items[e.Index].ToString() ?? "";
var fontBrush = new SolidBrush(e.ForeColor);
var selected = (e.State.HasFlag(DrawItemState.Focus) || e.State.HasFlag(DrawItemState.Selected));
if (text.StartsWith(LogLevels.Notice.ToString()))
{
if (selected)
{
g.FillRectangle(new SolidBrush(Color.LightGreen), e.Bounds);
fontBrush = new SolidBrush(Color.Black);
}
else
{
g.FillRectangle(new SolidBrush(Color.Green), e.Bounds);
fontBrush = new SolidBrush(Color.White);
}
}
else if (text.StartsWith(LogLevels.Warn.ToString()))
{
if (selected) { fontBrush = new SolidBrush(Color.Red); }
g.FillRectangle(new SolidBrush(Color.Yellow), e.Bounds);
}
else if (text.StartsWith(LogLevels.Error.ToString()))
{
if (selected) { fontBrush = new SolidBrush(Color.Red); }
g.FillRectangle(new SolidBrush(Color.Pink), e.Bounds);
}
else if (text.StartsWith(LogLevels.Debug.ToString()))
{
fontBrush = selected ? new SolidBrush(Color.White) : new SolidBrush(Color.Gray);
}
else if (text.StartsWith(LogLevels.Assert.ToString()))
{
g.FillRectangle(new SolidBrush(Color.DarkRed), e.Bounds);
fontBrush = new SolidBrush(Color.White);
}
g.DrawString(text, e.Font, fontBrush, new PointF(e.Bounds.X, e.Bounds.Y));
e.DrawFocusRectangle();
}
/// <summary>
/// Write a message to events log.
/// </summary>
void WriteEventLog(string message, LogLevels logLevel)
{
// get formatted text
var msgText = string.Format("{0,-6} | {1,-5} | {2, -16}",
logLevel.ToString(),
DateTime.Now.ToShortTimeString(),
message);
// add to log list
if (logLevel != LogLevels.Trace)
{
List_EventsLog.Invoke((MethodInvoker)(() =>
{
List_EventsLog.Items.Add(msgText);
if (List_EventsLog.SelectedIndex == List_EventsLog.Items.Count - 2)
{
List_EventsLog.SelectedIndex = List_EventsLog.Items.Count - 1;
}
}));
}
}
/// <summary>
/// Log levels for event logs.
/// </summary>
public enum LogLevels
{
Trace,
Debug,
Info,
Notice,
Warn,
Error,
Assert
}
@RonenNess
Copy link
Author

Usage example:

WriteEventLog("Oh no!", LogLevels.Warn);

Note: works best with monospace font.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment