7

我无法在简单的 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 方法附加到按钮单击事件,它可以正常绘制,但不会在加载表单时绘制。

请指教。

4

6 回答 6

26

又快又脏:

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

于 2009-07-03T07:30:20.637 回答
4

Paint为 the 的事件连接一个事件处理程序,并从该事件处理程序中GroupBox调用。DrawLShapeLine然后,您应该使用Graphics事件参数提供的对象:

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

正如您的代码现在看起来的那样,它将尝试在GroupBox表单需要绘画时进行绘画。组框可以在任何其他场合绘制,这将使您绘制的线条消失。

于 2009-07-03T07:22:59.540 回答
4

另一种选择是使用 Visual Basic Power Packs 中可用的行控件。

http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/d9e082c8-5386-4481-a744-1c9029805696/

如果您有 Visual Studio 2008 SP1 或 Visual Studio 2010,则无需下载任何内容。

如果在工具箱中没有看到 Visual Basic PowerPacks 控件,请在工具箱中单击鼠标右键,然后在上下文菜单中选择“全部显示”。

于 2012-04-05T22:47:43.727 回答
2

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

于 2013-01-18T21:45:28.980 回答
0

我不确定是否发生了其他事情,但你应该在GroupBox's Paint 事件上画线,而不是Form's.

于 2009-07-03T07:24:09.320 回答
0

System.Drawing.Pen可用于在 Windows 窗体中绘制线条。

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

在此处输入图像描述

于 2021-10-29T14:11:50.897 回答