在Winforms中绘制一条线

时间:2009-07-03 07:13:23

标签: c# .net winforms system.drawing

我在以简单的窗体形式在组框中绘制一条线时遇到了麻烦。

这是我的代码:

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

请建议。

5 个答案:

答案 0 :(得分:24)

快速&脏:

如何创建宽度为1像素的面板并为其指定背景颜色?

答案 1 :(得分:4)

Paint的{​​{1}}事件挂钩事件处理程序,并从该事件处理程序中调用GroupBox。然后,您应该使用事件参数提供的DrawLShapeLine对象:

Graphics

现在你的代码看起来会在表单需要绘画时尝试在private void groupBox1_Paint(object sender, PaintEventArgs e) { DrawLShapeLine(e.Graphics, 10, 10, 20, 40); } 中绘画。组合框可以在任何其他场合绘制,这样你画的线就会消失。

答案 2 :(得分: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控件,请右键单击“工具箱”,然后在上下文菜单中选择“全部显示”。

答案 3 :(得分:1)

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

答案 4 :(得分:0)

我不确定是否有其他事情发生,但你应该在GroupBox的Paint事件上绘制一行,而不是Form

相关问题