Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/amazon-s3/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在动态创建的picturebox上绘制线_C#_Winforms_Drawing - Fatal编程技术网

C# 在动态创建的picturebox上绘制线

C# 在动态创建的picturebox上绘制线,c#,winforms,drawing,C#,Winforms,Drawing,例如,我需要在动态创建的PictureBox中画一条线。发生的情况是,图片框已创建并显示在表单中,但缺少行。下面是我的代码,有什么想法吗??thnx public void create_pb() { PictureBox pb = new PictureBox(); pb.Size = new Size(200, 200); pb.BorderStyle = BorderStyle.Fixed3D; pb.Location = new Point(0,0);

例如,我需要在动态创建的
PictureBox
中画一条线。发生的情况是,图片框已创建并显示在表单中,但缺少行。下面是我的代码,有什么想法吗??thnx

public void create_pb()
{
    PictureBox pb = new PictureBox();
    pb.Size = new Size(200, 200);
    pb.BorderStyle = BorderStyle.Fixed3D;
    pb.Location = new Point(0,0);
    panel1.Controls.Add(pb);
    g = pb.CreateGraphics();
    Pen p = new Pen(Color.Black, 2);

    g.DrawLine(p, 0, 0, 200, 200);           
}

g
定义为
公共图形g

不要使用
CreateGraphics
。您需要使用传递给您的事件参数中的
e.Graphics
,在
Paint
事件处理程序中进行绘制

否则,在下一次重新绘制图片框时(例如,当窗体被移动、调整大小、被另一个窗体覆盖等),您的行将被删除

例如:

pb.Paint += (sender, e) =>
{
    Pen p = new Pen(Color.Black, 2);
    e.Graphics.DrawLine(p, 0, 0, 200, 200);
};

您是否查看了
Invalidate()
方法?听起来这可能是问题所在。这里有一个现有的工作项目,也可以为您提供一些想法。请查看的底部,特别是事件处理程序的设置!