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

在Winform中通过按键画一条线
C# code

public partial class Form1 : Form
{

    public Form1()
    {
        InitializeComponent();
    }
    int x = 50, y = 50;
    private void Form1_Paint(object sender, PaintEventArgs e)
    {
        SolidBrush sb = new SolidBrush(Color.White);
        Graphics g = this.CreateGraphics();
        g.FillEllipse(sb, new Rectangle(x, y, 20, 20));

        sb.Dispose();
        g.Dispose();
    }
}
    private void Form1_KeyPress(object sender, KeyPressEventArgs e)
    {

        if (e.KeyChar == '6')
        {
          x += 3;
          SolidBrush sb = new SolidBrush(Color.Blue);
          Graphics g = this.CreateGraphics();
          g.FillEllipse(sb, new Rectangle(x,y,  20, 20));
        }
    }
}


我通过以上代码在windows窗口里画了一个圆球,按"6"小球向右移动画出一条线
我发现每当我将窗口最小化后再打开这条线就没了
想问有什么方法能使最小化后线条仍然存在?

------解决方案--------------------
C# code
public partial class Form1 : Form
{

    public Form1()
    {
        InitializeComponent();SetStyle(ControlStyles.UserPaint, true); 
    }
    int x = 50, y = 50;
protected override void OnPaint(PaintEventArgs e) 
        { 
            base.OnPaint(e); 
SolidBrush sb = new SolidBrush(Color.White); 
        Graphics g = e.graphics; 
        g.FillEllipse(sb, new Rectangle(x, y, 20, 20)); 

        } 

private void Form1_KeyPress(object sender, KeyPressEventArgs e) 
    { 

        if (e.KeyChar == '6') 
        { 
          x += 3; 
          this.refresh();        } 
    } 

}

------解决方案--------------------
Windows的窗口机制是不记录任何窗口的位图信息,也就是说窗口上的内容,比如:文字,图片,包括背景色等都不由操作系统记录;
当因为某些原因这些内容消失时,比如:最小化,被其它窗口覆盖等,那么就会发生Validate这样的事件。
上面的兄弟提到的OnPaint就是当窗口需要被重绘时所产生的事件,由于Windows没有记录任何图片的内容,那么在你的程序中就必须记录这些信息,它可以是位图形式的,也可以是矢量形式的。对于你的程序而言,就可以是矢量形式的,你只需要记录这条线的:起点,终点,颜色等。

C# code
//这样记录:
public Point startPoint;
public Point endPoint;
public Pen drawPen;

//这样重绘
public onPaint()
{
   DrawLine(startPoint,endPoint,drawPen);
}