C# OnPaint mousemove high cpu usage

I have written a custom control that renders some graphics. The graphics itself is fairly expensive to render but once rendered it rarely changes. The problem I have is that if you move the mouse really fast over the graphics surface it keeps calling the control's overridden Paint method which then incurs a high CPU penalty:

private void UserControl1_Paint(object sender, PaintEventArgs e)

What techniques could be used to avoid this situation or minimise any unnecessary redrawing since the graphics/image underneath the mouse pointer is not actually changing?


EDIT: After seeing your edit, I can assure you that OnPaint is not called by default when the mouse moves over a control. Something in your code is definitely causing the re-paint, you just don't see it yet. Perhaps posting some of your code would help us find the problem.

Are you invalidating your control on MouseMove? That is likely a bad idea, and if you really needed to do it (ie, you are making a graphics editor or something), you would have to be smart about how large a region was actually re-drawn. So, solution; don't paint your control in MouseMove.

Otherwise, I would not expect OnPaint to fire when the mouse moves over the control. You can also just generate the image once and then blt it to the Graphics object until it needs to be re-generated.


You can use a buffer image on which to draw when something is changed and in the Paint method just copy the image on the screen. Should be pretty fast. Also you can use the clip region to copy only the part that needs updating. This should reduce CPU usage.

You can also use an IsDirty flag to know when to update the buffer image (ie fully redraw it) if needed.


You should not call Paint directly.

Instead, call Invalidate (Control.Invalidate). This queues the need to be repainted, and Windows will take care of the call itself. This way, a lot of rapid invalidations (repaint requests) can be serviced by one call to Paint .

链接地址: http://www.djcxy.com/p/50276.html

上一篇: Bmp到jpg / png在C#中

下一篇: C#OnPaint mousemove使用较高的cpu