在Winforms中画一条线

8

我遇到了在简单的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方法附加到按钮单击事件,它可以正常绘制,但是在窗体加载时却无法绘制。请给予建议。
6个回答

29

简易方法:

创建一个宽度为1像素的面板,并给它设置背景颜色如何?


这个不能画对角线。 - lc.
5
如果您不希望出现对角线并想避免使用GDI+,这是一个不错的提示。 - Neil Barnwell
1
或者给它一个固定的单一边框。 - argyle

4

GroupBoxPaint事件挂接一个事件处理程序,并从该事件处理程序中调用DrawLShapeLine。您应该使用事件参数中提供的Graphics对象:

private void groupBox1_Paint(object sender, PaintEventArgs e)
{
    DrawLShapeLine(e.Graphics, 10, 10, 20, 40);
}

您当前的代码会在表单需要绘制时尝试在GroupBox中绘制。组框可能会在任何其他场合被绘制,这将使您绘制的线条消失。


4

2
在没有文本的情况下添加一个带有3D边框和高度为2的标签(您必须在属性页面中设置高度,而不是使用GUI)。

0

System.Drawing.Pen 可以用于在 Windows Form 中绘制线条。

 Graphics surface = CreateGraphics();
 Pen pen1 = new Pen(Color.Black, 2);
 surface.DrawLine(pen1, this.Width / 2, 0, this.Width / 2, this.Height);

enter image description here


0

我不确定是否还有其他问题,但你应该在GroupBox的Paint事件中画线,而不是在Form中。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接