[英]C# winforms button with solid border, like 3d
如何在 C# winforms 上創建帶有實心邊框(3d)的按鈕,如下圖所示?
Panel BorderStyle
可以設置為Fixed3D
,但按鈕BorderStyle
不能設置為Fixed3D
。
我也已經嘗試過FlatAppearance
,它實際上是平面樣式。
您可以通過這種方式自定義具有粗 3d 邊框的Button
控件:
FlatStyle
設置為Flat
FlatApperanace
設置BorderSize
至0
FlatApperanace
中將MouseOverBackColor
設置為ControlLight
然后處理Paint
事件並使用ControlPaint.DrawBorder
繪制一個粗的 3d 邊框:
private void button1_Paint(object sender, PaintEventArgs e)
{
ControlPaint.DrawBorder(e.Graphics, button1.ClientRectangle,
SystemColors.ControlLightLight, 5, ButtonBorderStyle.Outset,
SystemColors.ControlLightLight, 5, ButtonBorderStyle.Outset,
SystemColors.ControlLightLight, 5, ButtonBorderStyle.Outset,
SystemColors.ControlLightLight, 5, ButtonBorderStyle.Outset);
}
結果如下:
添加到 Reza 的帖子中(感謝 Reza!)......當按鈕按下時,您可以變得更漂亮並反轉 3D 效果:
private bool blnButtonDown = false;
private void button_Paint(object sender, PaintEventArgs e)
{
if (blnButtonDown == false)
{
ControlPaint.DrawBorder(e.Graphics, (sender as System.Windows.Forms.Button).ClientRectangle,
System.Drawing.SystemColors.ControlLightLight, 2, ButtonBorderStyle.Outset,
System.Drawing.SystemColors.ControlLightLight, 2, ButtonBorderStyle.Outset,
System.Drawing.SystemColors.ControlLightLight, 2, ButtonBorderStyle.Outset,
System.Drawing.SystemColors.ControlLightLight, 2, ButtonBorderStyle.Outset);
}
else
{
ControlPaint.DrawBorder(e.Graphics, (sender as System.Windows.Forms.Button).ClientRectangle,
System.Drawing.SystemColors.ControlLightLight, 2, ButtonBorderStyle.Inset,
System.Drawing.SystemColors.ControlLightLight, 2, ButtonBorderStyle.Inset,
System.Drawing.SystemColors.ControlLightLight, 2, ButtonBorderStyle.Inset,
System.Drawing.SystemColors.ControlLightLight, 2, ButtonBorderStyle.Inset);
}
}
private void button_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
{
blnButtonDown = true;
(sender as System.Windows.Forms.Button).Invalidate();
}
private void button_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
{
blnButtonDown = false;
(sender as System.Windows.Forms.Button).Invalidate();
}
如果你不在乎邊框有多粗,可以使用下面的代碼。 (我選擇我的復選框的外觀作為按鈕,我喜歡它不選中時凸起,選中時凹陷)
private void checkbox_paint(object sender, PaintEventArgs e)
{
CheckBox myCheckbox = (CheckBox)sender;
Rectangle borderRectangle = myCheckbox.ClientRectangle;
if (myCheckbox.Checked)
{
ControlPaint.DrawBorder3D(e.Graphics, borderRectangle,
Border3DStyle.Sunken);
}
else
{
ControlPaint.DrawBorder3D(e.Graphics, borderRectangle,
Border3DStyle.Raised);
}
}
以防萬一您不知道如何使用此代碼:您需要做的就是在設計器中選擇按鈕/復選框,然后轉到“屬性”窗口並選擇“事件”選項卡(單擊 Thunderbolt)。 找到名為 Paint 的事件,然后在旁邊的框中鍵入不帶括號的事件處理程序名稱(例如 checkbox_paint)。 在隨后彈出的代碼窗口中填寫您的代碼。 那么你都准備好了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.