效果下如图:
创建ActivateButton公用方法,代码如下:
private void ActivateButton(object senderBtn, Color color1, Color color2, Color color3) { if (senderBtn != null) { DisableButton(); //Button currentBtn = (IconButton)senderBtn; currentBtn.BackColor = Color.LightSlateGray; currentBtn.ForeColor = color1; currentBtn.IconColor = color2; currentBtn.ImageAlign = ContentAlignment.MiddleRight; currentBtn.ImageAlign = ContentAlignment.MiddleRight; currentBtn.TextImageRelation = TextImageRelation.TextBeforeImage; //Left border button leftBorderBtn.Location = new Point(0, currentBtn.Location.Y); leftBorderBtn.BackColor = color3; leftBorderBtn.Visible = true; leftBorderBtn.BringToFront(); } }
这段代码实现了按钮激活状态的样式变化。当按钮被点击时,会调用此方法,并传入当前按钮、颜色参数。方法会先调用DisableButton()方法,将之前激活的按钮恢复为默认状态。
然后将传入的当前按钮设为激活状态,改变背景色、前景色、图标颜色等,并将左边框按钮的位置移动到当前按钮的位置,改变其背景色,并将其置于最前面。
创建恢复按钮默认状态DisableButton公共方法,代码如下:
private void DisableButton() { if (currentBtn != null) { currentBtn.BackColor = Color.Gainsboro; currentBtn.ForeColor = Color.DimGray; currentBtn.IconColor = Color.SaddleBrown; currentBtn.ImageAlign = ContentAlignment.MiddleLeft; currentBtn.ImageAlign = ContentAlignment.MiddleLeft; currentBtn.TextImageRelation = TextImageRelation.ImageBeforeText; } }
声明必要类型字段,创建静态Color结构,构造函数,代码如下:
1 private IconButton currentBtn; 2 private Panel leftBorderBtn; 3 public Form1() 4 { 5 InitializeComponent(); 6 leftBorderBtn = new(); 7 leftBorderBtn.Size = new Size(7, 50); 8 panelMenu.Controls.Add(leftBorderBtn); 9 10 //Forms 11 this.Text = string.Empty; 12 this.ControlBox = false; 13 this.DoubleBuffered = true; 14 this.MaximizedBounds = 15 Screen.FromHandle(this.Handle).WorkingArea; 16 } 17 18 private struct RGBColor 19 { 20 public static Color color1 = Color.FromArgb(0, 0, 0); 21 public static Color color2 = Color.FromArgb(188, 143, 143); 22 public static Color color3 = Color.FromArgb(139, 69, 19); 23 }
1. `currentBtn` 和 `leftBorderBtn` 是私有变量,用于记录当前选中的按钮和左侧边框的位置。
2. 在构造函数中,创建一个新的 `Panel` 控件 `leftBorderBtn`,并设置其大小为 `(7, 50)`,然后将其添加到 `panelMenu` 控件中。
3. `RGBColor` 是一个结构体,用于存储颜色常量。
4. `Text` 属性设为空字符串,`ControlBox` 属性设为 `false`,`DoubleBuffered` 属性设为 `true`,`MaximizedBounds` 属性设为当前屏幕的工作区域,用于防止窗口最大化时超出屏幕边界。
按钮”监控“的后台代码如下:
private void iconButton2_Click(object sender, EventArgs e) { ActivateButton(sender, RGBColor.color1, RGBColor.color2, RGBColor.color3); }
标签:高亮,currentBtn,Color,leftBorderBtn,private,按钮,RGBColor,Winform,图标 From: https://www.cnblogs.com/davisdabing/p/17810565.html