I have a program that has to draw the mouse whenever it is moved.. as the mouse is snaped to a grid. I hide the mouse cursor by setting it to be a transparent .cur file. Then for my mouse move code I have the following:
The DrawCursor function looks like this:
Now everything here works great.. Except one thing. When I move my mouse I get 70-100% processer used. (on a 2.2 ghz with a gig memory) When I try to move the cursor on a 1.5ghz computer it slows down and "skips".
The part of my code that takes most of the performance is the:
Bitmap backBufferBmp = new Bitmap ( mainBmp );
Graphics backBufferDC = Graphics.FromImage ( backBufferDC );
That exists in the MouseMove function.
What this is doing is taking a copy of my backround image, so that I can draw dynamically on top of it. Anyone know of a better way to do this? Do you think using something other than GDI+ would be better? (Like directx?) Thanks.
Code:
private void Map_MouseMove ( object sender, MouseEventArgs e )
{
if ( drawCursor )
{
// First thing we need to do, is snap the cursor to the grid (ScaledRoomSize is the size of a block on my backbuffer)
PointF cursorSnappedPosition = new PointF ( e.X - e.X % ScaledRoomSize, e.Y - e.Y % ScaledRoomSize );
// Now if this changed
if ( cursorSnappedPosition != lastSnappedPosition )
{
Graphics graphics = CreateGraphics ( );
Bitmap backBufferBmp = new Bitmap ( mainBmp );
Graphics backBufferDC = Graphics.FromImage ( backBufferDC );
// Draw our cursor
DrawCursor ( backBufferDC, cursorSnappedPosition, new PointF ( e.X, e.Y ) );
// Finally draw the image
graphics.DrawImage ( backBufferDC, 0, 0 );
// Free our memory
backBufferBmp.Dispose ( );
backBufferDC.Dispose ( );
graphics.Dispose ( );
lastSnappedPosition = cursorSnappedPosition;
} // End if changed
}
} // End of MouseMove function
Code:
private void DrawCursor ( Graphics graphics, PointF cursorSnappedPosition, PointF cursorPosition )
{
// Create our new solidBrush
solidBrush = new SolidBrush ( Color.FromArgb ( 20, 20, 20, 20 ) );
pen = new Pen ( Color.DarkBlue, 3 );
// highlight the corisponding column
graphics.FillRectangle ( solidBrush,
cursorSnappedPosition.X, 0, ScaledRoomSize, this.Height );
// highlight the corisponding row
graphics.FillRectangle ( solidBrush,
0, cursorSnappedPosition.Y, this.Width, ScaledRoomSize );
// It has changed so we draw our snapped position
graphics.DrawRectangle ( pen, cursorSnappedPosition.X,
cursorSnappedPosition.Y, ScaledRoomSize, ScaledRoomSize );
}
The part of my code that takes most of the performance is the:
Bitmap backBufferBmp = new Bitmap ( mainBmp );
Graphics backBufferDC = Graphics.FromImage ( backBufferDC );
That exists in the MouseMove function.
What this is doing is taking a copy of my backround image, so that I can draw dynamically on top of it. Anyone know of a better way to do this? Do you think using something other than GDI+ would be better? (Like directx?) Thanks.