廢話少說,直接上碼:
namespace csPublish { [ToolboxItem(true)] class textProgressBar : System.Windows.Forms.ProgressBar { [System.Runtime.InteropServices.DllImport("user32.dll ")] static extern IntPtr GetWindowDC(IntPtr hWnd); [System.Runtime.InteropServices.DllImport("user32.dll ")] static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC); private System.Drawing.Color _TextColor = System.Drawing.Color.Black; private System.Drawing.Font _TextFont = new System.Drawing.Font("SimSun ", 12); public System.Drawing.Color TextColor { get { return _TextColor; } set { _TextColor = value; this.Invalidate(); } } public System.Drawing.Font TextFont { get { return _TextFont; } set { _TextFont = value; this.Invalidate(); } } protected override void WndProc(ref Message m) { base.WndProc(ref m); if (m.Msg == 0xf || m.Msg == 0x133) { //攔截系統消息,獲得當前控件進程以便重繪。 //一些控件(如TextBox、Button等)是由系統進程繪制,重載OnPaint方法將不起作用. //所有這里並沒有使用重載OnPaint方法繪制TextBox邊框。 // //MSDN:重寫 OnPaint 將禁止修改所有控件的外觀。 //那些由 Windows 完成其所有繪圖的控件(例如 Textbox)從不調用它們的 OnPaint 方法, //因此將永遠不會使用自定義代碼。請參見您要修改的特定控件的文檔, //查看 OnPaint 方法是否可用。如果某個控件未將 OnPaint 作為成員方法列出, //則您無法通過重寫此方法改變其外觀。 // //MSDN:要了解可用的 Message.Msg、Message.LParam 和 Message.WParam 值, //請參考位於 MSDN Library 中的 Platform SDK 文檔參考。可在 Platform SDK(“Core SDK”一節) //下載中包含的 windows.h 頭文件中找到實際常數值,該文件也可在 MSDN 上找到。 IntPtr hDC = GetWindowDC(m.HWnd); if (hDC.ToInt32() == 0) { return; } //base.OnPaint(e); System.Drawing.Graphics g = Graphics.FromHdc(hDC); SolidBrush brush = new SolidBrush(_TextColor); string s = string.Format("{0}%", this.Value * 100 / this.Maximum); SizeF size = g.MeasureString(s, _TextFont); float x = (this.Width - size.Width) / 2; float y = (this.Height - size.Height) / 2; g.DrawString(s, _TextFont, brush, x, y); //返回結果 m.Result = IntPtr.Zero; //釋放 ReleaseDC(m.HWnd, hDC); } } } }
引文鏈接:
c#在WinForm中重寫ProgressBar控件(帶%的顯示)
http://www.codeproject.com/Articles/29457/TSmartProgressBar-A-Smart-C-ProgressBar-with-Perce。
下載鏈接:http://yun.baidu.com/share/link?shareid=2240439027&uk=3221713554
http://stackoverflow.com/questions/3529928/how-do-i-put-text-on-progressbar
http://stackoverflow.com/questions/8259157/text-on-progressbar-in-c-sharp/8259258