C#實現(xiàn)UI控件輸出日志的方法詳解
文章描述
一般情況下,我們的日志文件是用來記錄一些關(guān)鍵操作或者異常,并且是后臺存儲,并不對外開放的;但是也有些時候,特別是做一些小工具程序,需要將一些操作步驟、記錄等直接顯示在窗體上。以便于使用者能夠知道執(zhí)行進(jìn)度等情況。
所以,我們可以簡單封裝一下,寫個專門用來輸出日志的控件;并且以不同的顏色表示不同的狀態(tài),讓日志更直觀明了。
如果將以下自定義控件放到控件庫中(即在新建項目的時候選擇Windows窗體控件庫),在其他程序中使用起來就很方便了,只要將這個dll拖到工具箱面板中,就可以在工具箱中看到這個控件。使用的時候直接從工具箱中拖出來就可以了。

開發(fā)環(huán)境
.NET Framework版本:4.5
開發(fā)工具
Visual Studio 2013
實現(xiàn)代碼
public partial class ui_log : ListBox
{
public ui_log()
{
InitializeComponent();
this.DrawMode = DrawMode.OwnerDrawFixed;
this.BackColor = Color.Black;
this.Font = new Font("黑體", 12);
}
protected override void OnPaint(PaintEventArgs pe)
{
base.OnPaint(pe);
}
protected override void OnDrawItem(DrawItemEventArgs e)
{
base.OnDrawItem(e);
if (e.Index >= 0 && this.Items.Count>0)
{
dynamic item = this.Items[e.Index];
Brush brush = new SolidBrush(item.Color);
e.Graphics.DrawString(item.Text, e.Font, brush, e.Bounds, StringFormat.GenericDefault);
}
}
public void Log(string text, Color color)
{
if (this.InvokeRequired)
{
this.Invoke(new Action(() => { Log(text, color); }));
return;
}
this.Items.Add(new { Color = color, Text = text });
this.SelectedIndex = this.Items.Count - 1;
}
public void LogInfo(string text)
{
Log(text, Color.Green);
}
public void LogError(string text)
{
Log(text, Color.Red);
}
public void LogWarinig(string text)
{
Log(text, Color.Yellow);
}
public void ClearLog()
{
this.Items.Clear();
}
}private void button1_Click(object sender, EventArgs e)
{
ui_log1.LogInfo("Info");
Thread.Sleep(300);
ui_log1.LogError("Error");
Thread.Sleep(300);
ui_log1.LogWarinig("Warinig");
Thread.Sleep(300);
ui_log1.Log("White", Color.White);
}
private void button2_Click(object sender, EventArgs e)
{
ui_log1.ClearLog();
}實現(xiàn)效果

代碼解析:首先是寫了一個自定義控件,繼承自ListBox;然后設(shè)置下DrawMode屬性,這個很重要,否則不會觸發(fā)DrawItem;最后在DrawItem事件中,對數(shù)據(jù)進(jìn)行重繪。
做完上述處理后,就不要直接使用Items.Add了,需要對Items.Add也進(jìn)行一次封裝,將顏色也傳進(jìn)去,即:this.Items.Add(new { Color = color, Text = text });
到此這篇關(guān)于C#實現(xiàn)UI控件輸出日志的方法詳解的文章就介紹到這了,更多相關(guān)C# UI控件輸出日志內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
自定義實現(xiàn)Json字符串向C#對象轉(zhuǎn)變的方法
自定義實現(xiàn)Json字符串向C#對象轉(zhuǎn)變的方法,需要的朋友可以參考一下2013-03-03
C# 實現(xiàn)把double 存成兩位精度小數(shù)
這篇文章主要介紹了C# 實現(xiàn)把double 存成兩位精度小數(shù),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-12-12
深入多線程之:解析線程的交會(Thread Rendezvous)詳解
本篇文章是對線程的交會(Thread Rendezvous)進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-05-05

