WinForm重繪Combobox控制元件無邊框樣式
阿新 • • 發佈:2020-09-07
起因
其他文章大多介紹combobox控制元件下拉框的重繪,現在主要用途就是重繪DropDownList樣式下的Combobox控制元件,使BackColor屬性有效。
程式碼如下:
/// <summary> /// 主要為DropDownList樣式重繪(特定性較強) /// </summary> public partial class ComboboxEx : ComboBox { public ComboboxEx() { InitializeComponent(); this.DropDownStyle = ComboBoxStyle.DropDownList } public Color BoardColor { get; set; } = Color.White; protected override void WndProc(ref Message m) { base.WndProc(ref m); //WM_PAINT = 0xf; 要求一個視窗重畫自己,即Paint事件時 //WM_CTLCOLOREDIT = 0x133;當一個編輯型控制元件將要被繪製時傳送此訊息給它的父視窗; //通過響應這條訊息,所有者視窗可以通過使用給定的相關顯示裝置的控制代碼來設定編輯框的文字和背景顏色 //windows訊息值表,可參考: if (m.Msg == 0xf || m.Msg == 0x133) { IntPtr hDC = GetWindowDC(m.HWnd); if (hDC.ToInt32() == 0) //如果取裝置上下文失敗則返回 { return; } //建立Graphics對像 Graphics g = Graphics.FromHdc(hDC); g.FillRectangle(new SolidBrush(BackColor), new Rectangle(0, 0, Width, Height)); //畫邊框的 //ControlPaint.DrawBorder(g, new Rectangle(0, 0, Width, Height), BoardColor, ButtonBorderStyle.Solid); //畫堅線 //ControlPaint.DrawBorder(g, new Rectangle(Width - Height, 0, Height, Height), Color.Red, ButtonBorderStyle.Solid); Point pA = new Point(Width - 20, Height / 2 - 3); Point pB = pA + new Size(6, 6); Point pC = pA + new Size(12, 0); g.DrawLine(new Pen(Color.White,2), pA, pB); g.DrawLine(new Pen(Color.White,2), pB, pC); if (this.SelectedIndex > -1) { string text = SelectedItem.ToString(); Size strSize = Size.Ceiling(g.MeasureString(text, this.Font)); g.DrawString(text, Font, new SolidBrush(ForeColor), 5, (Height - strSize.Height) / 2); } //g.DrawLine(new Pen(Brushes.Blue, 2), new PointF(this.Width - this.Height, 0), new PointF(this.Width - this.Height, this.Height)); //釋放DC ReleaseDC(m.HWnd, hDC); } } [DllImport("User32.dll")] public static extern IntPtr GetWindowDC(IntPtr hwnd); [DllImport("User32.dll")] public static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC); }