BitBlt and GDI32 for the Thick Headed

Timothy Patrick
Copyright Apr 18, 2004


Page 1

In this tutorial you will learn...

This tutorial should NOT take more then 15 minutes to read - If you read every line and follow every instruction, almost everything you need to know (about BitBlt) is here!

Welcome to my tutorial which I have titled "BitBlt for the Thick Headed". If you want to go through this tutorial quickly, all the essential parts are in BOLD. For the record, I mean no offence to anyone on the PSC community, I was going to call it BitBlt for Dummies like the popular For Dummies books, but didn't want to get into copyright complications with book publishers. The goal of this tutorial is to step-by-step explain howto use BitBlt and some other Win32 GDI functions, to accomplish tasks such as double buffering and loading sprites from files - All in a relatively short reading-time (basically i'll try not to ramble on too much) Anyways, let's get started...

The first thing your going to do obviously is create a form (so you can follow along with this tutorial), set the ScaleMode to '3 - Pixel', I suggest you always set the scalemode to Pixels if your going to be using the form with any sort of API to prevent confusion.

Next Increase the form's size until the ScaleWidth is 320, and the ScaleHeight is 256.
We will be using the form as our practice surface, note that the form property called "HasDC" must be set to TRUE - Actually it doesn't seem to matter, but it's good practice. Also, for many of you who fell in love with using AutoRedraw, we will NOT need AutoRedraw because we are going to be using Double Buffering which is ALOT faster, and more professional. So make sure the form property AutoRedraw is set to false.

The next step is to declare the API calls that we will need, as shown below. So copy and paste the code below into the very top of your form's code - in the (general)(declarations) section of your form.

  1. 'The following API calls are for:
  2. 'blitting
  3. Private Declare Function BitBlt Lib "gdi32" (ByVal hDestDC As Long,ByVal x As Long, ByVal y As Long, ByVal nWidth As Long, ByVal nHeightAs Long, ByVal hSrcDC As Long, ByVal xSrc As Long, ByVal ySrc As Long,ByVal dwRop As Long) As Long
  4. 'code timer
  5. Private Declare Function GetTickCount Lib "kernel32" () As Long
  6. 'creating buffers / loading sprites
  7. Private Declare Function CreateCompatibleBitmap Lib "gdi32" (ByVal hdcAs Long, ByVal nWidth As Long, ByVal nHeight As Long) As Long
  8. Private Declare Function CreateCompatibleDC Lib "gdi32" (ByVal hdc As Long) As Long
  9. Private Declare Function GetDC Lib "user32" (ByVal hwnd As Long) As Long
  10. 'loading sprites
  11. Private Declare Function SelectObject Lib "gdi32" (ByVal hdc As Long, ByVal hObject As Long) As Long
  12. 'cleanup
  13. Private Declare Function DeleteObject Lib "gdi32" (ByVal hObject As Long) As Long
  14. Private Declare Function DeleteDC Lib "gdi32" (ByVal hdc As Long) As Long
  15. 'end of copy-paste here...

Q & A
Q. What is a DC (Device Context aka. hDC)?
A. A Device Context is a number that is assigned to any peice of information stored in memory, like a name or handle, so we can call upon that information with ease, when using BitBlt, we point to the handle of images that we have loaded into memory.

* If you dont know what API is, then you should do some research about it, before you even try to figure this tutorial out! ;-)

Next, we need to store the addresses of the DC's that we are creating. DC's addresses are Long values so we will Declare Public Variables to store the DC's memory address as shown below. (copy and paste into general declarations)

  1. 'our Buffer's DC
  2. Public myBackBuffer As Long
  3. Public myBufferBMP As Long
  4. 'The DC of our sprite/graphic
  5. Public mySprite As Long
  6. 'coordinates of our sprite/graphic on the screen
  7. Public SpriteX As Long
  8. Public SpriteY As Long
  9. 'end of copy-paste here...

Q & A
Q. What is Double Buffering and why do we use it?
A. If you were to blit sprites directly to the form, you would soon notice that everything "flickers" alot, this is because of the slight time difference between blitting different sprites, they dont actually appear on the screen at the exact same time, but rather, one after another. Turning AutoRedraw ON and using a Form.Refresh call AFTER blitting is one way of fixing this problem - BUT, AutoRedraw is VERY slow, so we use a technique called Double Buffering to fix the problem and give our game FAST, FLICKERLESS graphics. Double buffering works like this:

Now we have the foundation of our code, we have all the API declarations we'll be needing, and all the variables we'll be using in this example. The next thing we're gunna do is create a function that loads graphics into memory, it makes working with the API alot simpler...

Copy and paste the function below, but be sure to read all the comments so you understance the concept.

  1. Public Function LoadGraphicDC(sFileName As String) As Long
  2. 'cheap error handling
  3. On Error Resume Next
  4. 'temp variable to hold our DC address
  5. Dim LoadGraphicDCTEMP As Long
  6. 'create the DC address compatible with
  7. 'the DC of the screen
  8. LoadGraphicDCTEMP = CreateCompatibleDC(GetDC(0))
  9. 'load the graphic file into the DC...
  10. SelectObject LoadGraphicDCTEMP, LoadPicture(sFileName)
  11. 'return the address of the file
  12. LoadGraphicDC = LoadGraphicDCTEMP
  13. End Function
  14. 'end of copy-paste here...

Ok, so this is what our function does... It creates a Device Context compatible with the screen, it then loads the specified graphics file into the device context...

We're going to be using the function in our example code... but before we go any further with the example project, I'm going to explain the BitBlt API from start to finish - in plain English:

The BitBlt API...

BitBlt is a function in the DLL "gdi32".

Now lets take a look at the API declaration itself... The API declaration should be placed in the "General Declarations" section of a form or module. Here's what it looks like:
  1. Declare Function BitBlt Lib "gdi32" Alias "BitBlt" _
  2. (ByVal hDestDC As Long, _
  3. ByVal x As Long, _
  4. ByVal y As Long, _
  5. ByVal nWidth As Long, _
  6. ByVal nHeight As Long, _
  7. ByVal hSrcDC As Long, _
  8. ByVal xSrc As Long, _
  9. ByVal ySrc As Long, _
  10. ByVal dwRop As Long) As Long

The first part of this code, the first line (in this example) says that we're accessing the BitBlt function from the gdi32 DLL. the following lines are parameters that we have to input in order to use the function in our program. Here's a rundown of what each of these parameters is:

The last parameter - dwRop - determines how the graphic is drawn, often called the drawmode...
Drawmodes, or Raster Operations/ROPs available are as follows, each of these is a reserved constant in VB, so any one of these words (in italic) can be used in the dwRop parameter to acheive different effects

  1. 'An example of using BitBlt
  2. BitBlt Form1.hDC, PlayerX, PlayerY, 48, 48, picPlayer.hDC, 0, 0, vbSrcCopy

On with our example project...
Next in our example project (this is the final part), we're going to use BitBlt in a loop much like you would in a game. Here's what you need to do:
Copy and paste this code into the command button's Click-Event subroutine.
READ ALL THE COMMENTS, to understand the code...

  2. 'Timer variables...
  3. Dim T1 As Long, T2 As Long
  4. 'create a compatable DC for the back buffer..
  5. myBackBuffer = CreateCompatibleDC(GetDC(0))
  6. 'create a compatible bitmap surface for the DC
  7. 'that is the size of our form.. (320 X 256)
  8. 'NOTE - the bitmap will act as the actua ' l graphics surface inside the DC
  9. 'because without a bitmap in the DC, the ' DC cannot hold graphical data..
  10. myBufferBMP = CreateCompatibleBitmap(GetDC(0), 320, 256)
  11. 'final step of making the back buffer...
  12. 'load our created blank bitmap surface into our buffer
  13. '(this will be used as our canvas to draw-on off screen)
  14. SelectObject myBackBuffer, myBufferBMP
  15. 'before we can blit to the buffer, we should fill it with black
  16. BitBlt myBackBuffer, 0, 0, 320, 256, 0, 0, 0, vbWhiteness
  17. 'load our sprite (using the function we made)
  18. mySprite = LoadGraphicDC(App.Path & "sprite1.bmp")
  19. 'MsgBox Dir$(App.Path & "sprite1.bmp")
  20. 'ok now all the graphics are loaded so
  21. 'lets start our main loop..
  22. 'Disable cmdTest, because if the graphics are
  23. 'reloaded there will be memory leaks...
  24. cmdTest.Enabled = False
  25. '== START MAIN LOOP ==
  26. 'get current tickcount (this is used as a code timer)
  27. T2 = GetTickCount
  28. Do
  29.   DoEvents 'DoEvents makes sure that our mouse and keyboard dont freeze-up
  30.   T1 = GetTickCount
  31.   'if 15MS has gone by, execute our next frame
  32.   If (T1 - T2) >= 15 Then
  33.     'clear the place where the sprite used to be...
  34.     '(we do this by filling in the old sprites place
  35.     'with black... but in games you'll probably have
  36.     'a background tile that you would blit here)
  37.     BitBlt myBackBuffer, SpriteX - 1, SpriteY - 1, _
  38.     32, 32, 0, 0, 0, vbBlackness
  39.     'blit sprites to the back-buffer ***
  40.     'You could blit multiple sprites to the ' backbuffer,
  41.     'but in our example we only blit on...
  42.     BitBlt myBackBuffer, SpriteX, SpriteY, 32, 32, _
  43.     mySprite, 0, 0, vbSrcCopy
  44.     'now blit the backbuffer to the form...
  45.     BitBlt Me.hdc, 0, 0, 320, 256, myBackBuffer, _
  46.     0, 0, vbSrcCopy
  47.     'move our sprite down on a diagonal...
  48.     'Me.Caption = SpriteX & ", " & SpriteY
  49.     SpriteX = SpriteX + 1
  50.     SpriteY = SpriteY + 1
  51.     'update timer
  52.     T2 = GetTickCount
  53.   End If
  54.   'loop it until our sprite is off the screen...
  55. Loop Until SpriteX = 320
  56. 'end of copy-paste here...

DONT RUN THE PROGRAM YET, we need to write the cleanup code...
The cleanup code is just some code that we add that clears the memory that was occupied by the graphics that we loaded, and the backbuffer that we created (see above code). This code should usually go in the Form_Unload event, so that it is executed when the form unloads...

Copy and Paste the code below into the form's module

  1. Private Sub Form_Unload(Cancel As Integer)
  2. 'this clears up the memory we used to hold
  3. 'the graphics and the buffers we made
  4. 'Delete the bitmap surface that was in the backbuffer
  5. DeleteObject myBufferBMP
  6. 'Delete the backbuffer HDC
  7. DeleteDC myBackBuffer
  8. 'Delete the Sprite/Graphic HDC
  9. DeleteDC mySprite
  10. End Sub
  11. 'end of copy-paste here...

That's it! We're done! Run the program, click the button and you will see the sprite move from the top-left of the form to the bottom right, without any flickering...

Click Here to download completed project code

Yar Interactive Software