2015-07-10 41 views
0

我有一个主要的PictureBox它添加到它,其他图片框;我通过父母的孩子,并将其添加到父如下:添加多个图片框到一个主要的图片框,并绘制它们

public class VectorLayer : PictureBox 
    { 
     Point start, end; 
     Pen pen; 

     public VectorLayer(Control parent) 
     { 
      pen = new Pen(Color.FromArgb(255, 0, 0, 255), 8); 
      pen.StartCap = LineCap.ArrowAnchor; 
      pen.EndCap = LineCap.RoundAnchor; 
      parent.Controls.Add(this); 
      BackColor = Color.Transparent; 
      Location = new Point(0, 0); 

     } 


     public void OnPaint(object sender, PaintEventArgs e) 
     { 
      e.Graphics.DrawLine(pen, end, start); 
     } 

     public void OnMouseDown(object sender, MouseEventArgs e) 
     { 
      start = e.Location; 
     } 

     public void OnMouseMove(object sender, MouseEventArgs e) 
     { 
      end = e.Location; 
      Invalidate(); 
     } 

     public void OnMouseUp(object sender, MouseEventArgs e) 
     { 
      end = e.Location; 
      Invalidate(); 
     } 
    } 

和我处理来自主PictureBox里面那些On Events,现在在主PictureBox我在操控性上Paint事件如下:

private void PicBox_Paint(object sender, PaintEventArgs e) 
    { 
//current layer is now an instance of `VectorLayer` which is a child of this main picturebox 
     if (currentLayer != null) 
     { 
      currentLayer.OnPaint(this, e); 
     } 
     e.Graphics.Flush(); 
     e.Graphics.Save(); 
    } 

但是当我画什么都不出现,当我做Alt+Tab从它失去焦点,我看到我的载体,当我尝试重新绘制和失去焦点没有任何反应..

为什么这种奇怪的行为,我该如何解决它?

+0

'currentLayer'在哪里设置? –

+0

@PatrikEckebrecht在OnMouseClick事件中,并且我调用Invalidate()OnMouseMove事件。 – Abanoub

回答

0

您忘记了挂钩您的活动。

这些行添加到您的类:

MouseDown += OnMouseDown; 
MouseMove += OnMouseMove; 
MouseUp += OnMouseUp; 
Paint += OnPaint; 

不知道,如果你不希望也许这在MouseMove

public void OnMouseMove(object sender, MouseEventArgs e) 
{ 
    if (e.Button == System.Windows.Forms.MouseButtons.Left) 
    { 
     end = e.Location; 
     Invalidate(); 
    } 
} 

ASLO这些线是没用的,应予删除:

e.Graphics.Flush(); 
    e.Graphics.Save(); 

GraphicsState oldState = Graphics.Save将保存当前的状态,即设置当前的Graphics对象。如果您需要在几种状态之间切换,可能会缩放或剪切或旋转或翻译等,但这很有用。但不是在这里!

Graphics.Flush刷新所有待处理的图形操作,但实际上没有理由怀疑您的应用程序中有任何图形操作。