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

開發(fā)環(huán)境
.NET Framework版本:4.5
開發(fā)工具
Visual Studio 2013
實(shí)現(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();
}實(shí)現(xiàn)效果

代碼解析:首先是寫了一個(gè)自定義控件,繼承自ListBox;然后設(shè)置下DrawMode屬性,這個(gè)很重要,否則不會(huì)觸發(fā)DrawItem;最后在DrawItem事件中,對(duì)數(shù)據(jù)進(jìn)行重繪。
做完上述處理后,就不要直接使用Items.Add了,需要對(duì)Items.Add也進(jìn)行一次封裝,將顏色也傳進(jìn)去,即:this.Items.Add(new { Color = color, Text = text });
到此這篇關(guān)于C#實(shí)現(xiàn)UI控件輸出日志的方法詳解的文章就介紹到這了,更多相關(guān)C# UI控件輸出日志內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C#中創(chuàng)建統(tǒng)一API接口的實(shí)現(xiàn)方案
在 C# 中創(chuàng)建統(tǒng)一 API 接口需要從架構(gòu)設(shè)計(jì)、技術(shù)選型和代碼實(shí)現(xiàn)等多個(gè)層面進(jìn)行規(guī)劃,本文給大家詳細(xì)介紹了實(shí)現(xiàn)方案和完整示例代碼,對(duì)大家的學(xué)習(xí)或工作有一定的幫助,需要的朋友可以參考下2025-04-04
C#使用WebSocket與網(wǎng)頁(yè)實(shí)時(shí)通信的實(shí)現(xiàn)示例
本文主要介紹了C#使用WebSocket與網(wǎng)頁(yè)實(shí)時(shí)通信的實(shí)現(xiàn)示例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-08-08

