点一下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()); }
------解决方案--------------------------------------------------------
需要在控件的Paint事件里绘制
------解决方案--------------------------------------------------------
drawLine代码写到 panel1的OnPaint事件中,如果需要手工触发重绘,就调用 panel1.Invalidate()
------解决方案--------------------------------------------------------
每个 Panel 都注册 Paint 事件
p1.Paint += new PaintEventHandler(p1_Paint);