WinForm重繪Combobox控件無邊框樣式


起因

其他文章大多介紹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);
    }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM