基本上,你做错的是使用CreateGraphics
method.
这是您很少(如果有的话)需要做的事情。当然,这并不是说这个方法被破坏了。它的作用正如其所言:它被记录为正在执行:返回Graphics
代表表单绘图表面的对象。
问题是,每当您的表单被重绘时(这可能由于多种原因而发生),Graphics
对象基本上得到reset。结果,您在获得的内容中绘制的所有内容都将被删除。
A form is always redrawn when it is first loaded, so using CreateGraphics
never makes sense in the Load
event handler method. It is also going to be redrawn any time that it is minimized and restored, covered up by another window, or even resized (some of these depend on your operating system, graphics drivers, and your form's properties, but that's beyond the point).
你唯一可以利用的时间CreateGraphics
当你想要展示的时候即时反馈给用户的是不应该坚持重绘。例如,在处理程序中MouseMove
显示拖放反馈时的事件。
那么,解决办法是什么呢?总是在里面画画Paint
事件处理程序方法。这样,它就会在重绘中持续存在,因为“重绘”基本上涉及提高Paint
event.
当。。。的时候Paint
事件被引发,处理程序被传递一个实例PaintEventArgs
类,其中包含一个Graphics
您可以绘制的对象。
这就是你的代码should看起来像:
Public Class Form1
Protected Overridable Sub OnPaint(e As PaintEventArgs)
' Call the base class
MyBase.OnPaint(e)
' Do your painting
e.Graphics.DrawLine(Pens.Azure, 10, 10, 20, 20)
End Sub
End Class
(另请注意,在上面的代码中,我覆盖了OnPaint
方法,而不是处理相应的Paint
事件。这被认为是在派生类中处理事件的最佳实践。但无论哪种方式都会起作用。)