Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am trying to draw a series of rectangles on my Windows Form application in C#. I am using System.Drawing.Graphics to draw the Rectangles. They work fine, but once I switch to another application on my computer or minimize the form, they just disappear. Does anyone know why this is the case?

System.Drawing.Graphics graphics = this.CreateGraphics();
System.Drawing.Rectangle rectangle = new System.Drawing.Rectangle(
     25 + (32 * PASS_THROUGH), 190, 32, 32);
graphics.DrawRectangle(System.Drawing.Pens.Green, rectangle);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
152 views
Welcome To Ask or Share your Answers For Others

1 Answer

You're not going about painting the right way. Here's some basic information on how it works:

http://msdn.microsoft.com/en-us/library/kxys6ytf.aspx

You should have code that looks like this:

protected override void OnPaint(PaintEventArgs e)
{
    base.OnPaint(e);

    Rectangle = new Rectangle(25 + (32 * PASS_THROUGH), 190, 32, 32);
    e.Graphics.DrawRectangle(Pens.Green, Rectangle);
}

Windows will call this method whenever it needs to repaint your window.

If you want to be able to change what is painted dynamically, you need to add logic to this method. Such as an if statement that writes, if (drawRectangle) ...

When you want to signal your control to repaint itself after changing a variable like my above example of drawRectangle, you just need to call the Control.Invalidate method on the control in question.

You can manage a lot of different variables and objects to control what is painted, such as a list of shapes. In your paint method you would then loop through those shapes and draw them one by one. I am not sure if this is what you're trying to do, or if you just want to customize the look of your form and you don't need it to change dynamically.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...