【发布时间】:2016-03-23 15:15:29
【问题描述】:
这个网站上的其他解决方案对我不起作用,所以我试图找出我做错了什么:
这是 WinForm 应用程序
private void dk_buff_box_Paint(object sender, PaintEventArgs e)
{
Console.WriteLine("INSIDE!!");
ControlPaint.DrawBorder(e.Graphics, this.ClientRectangle, Color.Red, ButtonBorderStyle.Solid);
GroupBox box = sender as GroupBox;
DrawGroupBox(box, e.Graphics, Color.Red, Color.Black);
}
private void DrawGroupBox(GroupBox box, Graphics g, Color textColor, Color borderColor)
{
if (box != null)
{
Brush textBrush = new SolidBrush(textColor);
Brush borderBrush = new SolidBrush(borderColor);
Pen borderPen = new Pen(borderBrush);
SizeF strSize = g.MeasureString(box.Text, box.Font);
Rectangle rect = new Rectangle(box.ClientRectangle.X,
box.ClientRectangle.Y + (int)(strSize.Height / 2),
box.ClientRectangle.Width - 1,
box.ClientRectangle.Height - (int)(strSize.Height / 2) - 1);
// Clear text and border
g.Clear(this.BackColor);
// Draw text
g.DrawString(box.Text, box.Font, textBrush, box.Padding.Left, 0);
// Drawing Border
//Left
g.DrawLine(borderPen, rect.Location, new Point(rect.X, rect.Y + rect.Height));
//Right
g.DrawLine(borderPen, new Point(rect.X + rect.Width, rect.Y), new Point(rect.X + rect.Width, rect.Y + rect.Height));
//Bottom
g.DrawLine(borderPen, new Point(rect.X, rect.Y + rect.Height), new Point(rect.X + rect.Width, rect.Y + rect.Height));
//Top1
g.DrawLine(borderPen, new Point(rect.X, rect.Y), new Point(rect.X + box.Padding.Left, rect.Y));
//Top2
g.DrawLine(borderPen, new Point(rect.X + box.Padding.Left + (int)(strSize.Width), rect.Y), new Point(rect.X + rect.Width, rect.Y));
}
}
此代码不会触发“INSIDE!!”到我的控制台输出,并且 groupbox 周围的边框(称为 dk_buff_box)始终是灰色且非常轻的。 (我假设这是默认的??)
我需要做什么才能让这个边框改变颜色? 我有几个一起工作的 .cs 文件(控件) 主要的 .cs 文件是 form1.cs。上面的代码位于一个名为 darkknightinfo.cs 的单独 .cs 文件中
代码应该在主窗体上吗?还是应该在具有实际分组框的 .cs 文件上?
我需要做什么才能让 _Paint() 正确激活并运行代码以更改组框边框颜色?
【问题讨论】:
-
为什么不在 WPF XAML 中添加边框?
-
它是 WPF 还是 WinForm 应用程序?请澄清。
-
我用的是WinForm App
-
你在哪里订阅
dk_buff_box_Paint的东西?在设计师?如果您确实订阅了此事件处理程序,请检查form.Designer.cs文件。如果您在其他地方覆盖OnPaint(例如自定义控件),请确保在那里调用base.OnPaint,否则永远不会触发Paintevent。 -
将
dk_buff_box_Paint.Paint += dk_buff_box_Paint_Paint;放入表单的构造函数中。您的 DrawBorder 不起作用,因为您正试图在表单的客户端空间上绘图,但您的图形仅适用于 GroupBox。