Skip to main content
 首页 » 编程设计

c#之在 Windows 窗体应用程序中创建新对象时,如何防止以前绘制的对象消失

2024年06月03日21lidabo

我的问题是,在我的 Windows 窗体应用程序中,每次在特定图片框中单击鼠标时,我都想绘制一个椭圆,并且我希望之前绘制的椭圆保留在图片框中。

在当前状态下,单击鼠标后,先前绘制的椭圆将替换为在光标新位置绘制的新椭圆。

Ball.Paint 绘制一个椭圆。

问题的相关代码如下:

    private Ball b; 
 
    private void pbField_Paint(object sender, PaintEventArgs e) 
    { 
        if (b != null) 
            b.Paint(e.Graphics); 
    } 
 
    private void pbField_MouseClick(object sender, MouseEventArgs e) 
    {            
        int width = 10; 
        b = new Ball(new Point(e.X - width / 2, e.Y - width / 2), width); 
        Refresh(); 
    } 

如果有更多需要的代码或信息,我可以提供。

请您参考如下方法:

您需要某种数据结构来存储先前的省略号。一种可能的解决方案如下:

private List<Ball> balls = new List<Ball>(); // Style Note:  Don't do this, initialize in the constructor.  I know it's legal, but it can cause issues with some code analysis tools. 
 
private void pbField_Paint(object sender, PaintEventArgs e) 
{ 
    if (b != null) 
    { 
        foreach(Ball b in balls) 
        { 
            b.Paint(e.Graphics); 
        } 
    } 
} 
 
private void pbField_MouseClick(object sender, MouseEventArgs e) 
{            
    int width = 10; 
    b = new Ball(new Point(e.X - width / 2, e.Y - width / 2), width); 
    balls.Add(b); 
    Refresh(); 
}