今天学习C#,想在FORM中画一横线,但是却不能显示,不知为何,求达人指教。
代码如下:
        private void Form1_Load(object sender, EventArgs e)
        {
            //this.Location = new Point(2 * this.Location.X - 100, 100);
            Graphics g = this.CreateGraphics();
            Pen myPen = new Pen(Color.Black, 100);
            Point startPoint = new Point(0, this.Height / 3 * 2);
            Point endPoint = new Point(this.Width, this.Height / 3 * 2);
            g.DrawLine(myPen, startPoint, endPoint);
        }
    }

解决方案 »

  1.   

    我这样认为:
    你的代码没有问题,可是放错了地方,
    Load的时候,界面还没有被绘制,
    把你的代码移到Paint事件中试试看,就像这样:
    private void Form1_Paint(object sender, PaintEventArgs e) {
        Graphics g = this.CreateGraphics();//或者:Graphics g= e.Graphics;
        Pen myPen = new Pen(Color.Black, 100);
        Point startPoint = new Point(0, 0);
        Point endPoint = new Point(this.Width, this.Height);
        g.DrawLine(myPen, startPoint, endPoint);
        }
      

  2.   

    把代码放到Paint事件里去就可以了,控件需要重新绘制时触发该事件、
      

  3.   


    private void Form1_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
      {
     Graphics g = this.CreateGraphics();
      Pen myPen = new Pen(Color.Black, 100);
      Point startPoint = new Point(0, this.Height / 3 * 2);
      Point endPoint = new Point(this.Width, this.Height / 3 * 2);
      g.DrawLine(myPen, startPoint, endPoint);
      }public Form1()
      {
      InitializeComponent();
      this.Paint += new System.Windows.Forms.PaintEventHandler(this.Form1_Paint);
      }
      

  4.   

    确实,放在load里面是不能画图的,必须有个东西触发,比如button之类的
      

  5.   

    把代码放到Paint事件里去,控件需要重新绘制时触发该事件