我在以简单的Windows窗体在组框中绘制一条线时遇到麻烦。
这是我的代码:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
DrawLShapeLine(groupBox1.CreateGraphics(), 10, 10, 20, 40);
}
public void DrawLShapeLine(System.Drawing.Graphics g, int intMarginLeft, int intMarginTop, int intWidth, int intHeight)
{
Pen myPen = new Pen(Color.Black);
myPen.Width = 2;
// Create array of points that define lines to draw.
int marginleft = intMarginLeft;
int marginTop = intMarginTop;
int width = intWidth;
int height = intHeight;
int arrowSize = 3;
Point[] points =
{
new Point(marginleft, marginTop),
new Point(marginleft, height + marginTop),
new Point(marginleft + width, marginTop + height),
// Arrow
new Point(marginleft + width - arrowSize, marginTop + height - arrowSize),
new Point(marginleft + width - arrowSize, marginTop + height + arrowSize),
new Point(marginleft + width, marginTop + height)
};
g.DrawLines(myPen, points);
}
}
如果我将DrawLShapeLine方法附加到按钮单击事件,它将很好地绘制,但不会在加载窗体时绘制。
请指教。
最佳答案
Hook Paint
的GroupBox
事件的事件处理程序,并从该事件处理程序中调用DrawLShapeLine
。然后,您应该使用事件参数中提供的Graphics
对象:
private void groupBox1_Paint(object sender, PaintEventArgs e)
{
DrawLShapeLine(e.Graphics, 10, 10, 20, 40);
}
如您的代码所示,当表单需要绘画时,它将尝试在
GroupBox
中绘画。在任何其他情况下都可能会绘制组框,这将使您绘制的线条消失。关于c# - 在Winforms中画一条线,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/1078137/