Before going into details, let's look at a quick example to get the feel of this process. Let's say that your program needs a 48-KB chunk of global memory during the entire time the program is running. During initialization (for instance, when processing the WM_CREATE message), the program uses GlobalAlloc to allocate a 48-KB segment of moveable memory:
hGlobalMemory = GlobalAlloc (GMEM_MOVEABLE, 0xC000L) ;
The value returned from GlobalAlloc is a handle to a 48-KB global memory segment. Store the handle in a static variable (here called hGlobalMemory).
While processing other messages, you might need to read from or write to this memory segment. At that time you lock the block of memory using GlobalLock and save the far pointer returned from that function:
lpGlobalMemory = GlobalLock (hGlobalMemory) ;
You can now use the lpGlobalMemory pointer as a normal far pointer. When you are finished using the memory or processing the message, unlock the segment so that Windows can move it around in memory again:
GlobalUnlock (hGlobalMemory) ;
When your program cleans up in preparing to terminate (probably when processing the WM_DESTROY message), it can free up the memory segment by using:
GlobalFree (hGlobalMemory) ;
This procedure shows how a polite, well-behaved Windows program uses global memory. (I've ignored some details for now but will cover them shortly.) Good Windows programmers keep in mind that their programs share resources with other Windows programs. Good Windows programmers structure their programs to allow Windows to move the global segments around in memory if necessary. Good Windows programmers lock their segments only when they need to use the memory and unlock the segments when they are done.
An impolite, bad Windows program uses initialization code like this:
lpGlobalMemory = GlobalLock (GlobalAlloc (GMEM_FIXED, 0xC000L)) ;
The GMEM_FIXED flag in GlobalAlloc specifies that the segment is fixed in memory. Windows can't move it; therefore, the lpGlobalMemory value returned from GlobalLock will be valid until the segment is freed up. More convenient, yes. But don't do it.