//傳回hWnd參數所指定的視窗的裝置環境。
[System.Runtime.InteropServices.DllImport("user32.dll")]
static extern IntPtr GetWindowDC(IntPtr hWnd);
[System.Runtime.InteropServices.DllImport("user32.dll")]
//函數釋放裝置上下文環境(DC)
static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC);
int WM_PAINT = 0xf; //要求一個視窗重畫自己,即Paint事件時
/// <summary>
///
/// </summary>
/// <param name="m"></param>
protected override void WndProc(ref Message m)
{
base.WndProc(ref m);
if (m.Msg == WM_PAINT)
{
IntPtr hDC = GetWindowDC(m.HWnd);
if (hDC.ToInt32() == 0) //如果取裝置上下文失敗則傳回
{
return;
}
PaintComboBox(Graphics.FromHdc(hDC));
ReleaseDC(m.HWnd, hDC);
}
}
private void PaintComboBox(Graphics g)
{
g.SmoothingMode = SmoothingMode.HighQuality;
g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
int iDropDownButtonWidth = 17;
int iDropDownButtonHeight = this.Height;
int iDropDownButtonLocatinX = 17;
int iDropDownButtonLocatinY = 0;
if (!Util.PublicFunction.IsHigherWinXP())
{
iDropDownButtonWidth = 17;
iDropDownButtonHeight = this.Height-2;
iDropDownButtonLocatinX = 19;
iDropDownButtonLocatinY = 1;
}
//下拉按鈕
Rectangle dropDownRectangle = new Rectangle(ClientRectangle.Width - iDropDownButtonLocatinX, iDropDownButtonLocatinY, iDropDownButtonWidth, iDropDownButtonHeight);
//背景色刷
Brush bkgBrush;
//字型色刷
Brush fcBrush;
//設定背景色和字型色
bkgBrush = new SolidBrush(this._backColor);
fcBrush = new SolidBrush(this._foreColor);
//畫3D邊框
//ControlPaint.DrawBorder3D(g, new Rectangle(0, 0, this.Width, this.Height), Border3DStyle.SunkenInner, Border3DSide.All);
int iBackColorX = 0;
//為了字型正常,Enable時隻是重畫按鈕區域
if (this.Enabled)
{
iBackColorX = this.Width - 20;
}
//畫背景
g.FillRectangle(bkgBrush, iBackColorX, 0, ClientRectangle.Width, ClientRectangle.Height);
//為了字型正常,Disable時才重畫文本
if (!this.Enabled)
{
//畫文本
g.DrawString(base.Text, this.Font, fcBrush, 2, this.ClientSize.Height / 2, new StringFormat() { LineAlignment = StringAlignment.Center });
}
//畫邊框
//g.DrawRectangle(_BorderPen, new Rectangle(0, 0, this.Width, this.Height));
ControlPaint.DrawBorder(g, new Rectangle(0, 0, this.Width, this.Height), borderColor, ButtonBorderStyle.Solid);
//畫下拉按鈕
if (Util.PublicFunction.IsHigherWinXP())
{
ControlPaint.DrawComboButton(g, dropDownRectangle, this.Enabled ? System.Windows.Forms.ButtonState.Flat : System.Windows.Forms.ButtonState.All);
}
else
{
ComboBoxRenderer.DrawDropDownButton(g, dropDownRectangle, this.Enabled ? ComboBoxState.Normal : ComboBoxState.Disabled);
}
g.Dispose();
bkgBrush.Dispose();
fcBrush.Dispose();
}