日期:2014-05-18  浏览次数:20747 次

winfrom drawLine 问题
点一下button 动态增加一个Panel并且 可以连续点Button 生成N个Panel,Panel跟button生成直线并连接,问题:我点别的菜单、在进入此界面 直线不在了,生成Panel还在、线条怎么不在了呢 请教高手 是不是做的有问题! 此界面只有一个按钮跟按钮事件
代码如下:
C# code

static int x, y = 0;
        private Panel controlsPanel()
        {
            #region Panel
            Panel p1 = new Panel(); //p1最外层
            //p1.BackColor = System.Drawing.SystemColors.ActiveCaption;
            p1.Width = 90;
            p1.Height = 90;
            p1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            p1.Location = new System.Drawing.Point(x, y);

           
            #endregion

            #region Button
            Button btn1 = new Button();
            btn1.Text = "温湿度";
            btn1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            btn1.Width = 90;
            btn1.Height = 90;
            btn1.Image = global::Platform.Client.Properties.Resources.l1_bg;
            p1.Controls.Add(btn1);
            
            #endregion

            x += p1.Width + 2;
            if (x + p1.Width > this.panel1.ClientRectangle.Width)
            {
                x = 0;
                y += panel1.Height-p1.Height;
            }
            
            drawLine(x - (p1.Width / 2), y + p1.Height, 393, 228);            
            return p1;

        }

        private void drawLine(int x1,int y1,int x2,int y2)
        {
            
            IntPtr hwnd = new IntPtr();
            hwnd = this.panel1.Handle;
            Graphics newGraphics = Graphics.FromHwnd(hwnd);

            Point myStartPoint = new Point(x1, y1);
            Point myEndPoint = new Point(x2, y2);
            newGraphics.DrawLine(new Pen(Color.Red, 3), myStartPoint, myEndPoint);
            newGraphics.Dispose();

        }
        private void button1_Click(object sender, EventArgs e)
        {
            this.panel1.Controls.Add(controlsPanel());
        }



------解决方案--------------------


你的panel有很多个,互相之间连线,怎么可能会在某一个panel的paint里画线呢?你是把鸡蛋装在篮子里,不是把篮子装在鸡蛋里。。。
------解决方案--------------------
探讨
引用:
static int x, y = 0;
List<int[]> points = new List<int[]>();
private Panel controlsPanel()
{
#region Panel
Panel p1 = new Panel(); //p1最外层
//p1.BackColor = System.Drawing.SystemColo……