14.4.1 Creating a Callback Function

For all callback functions, you must follow these steps:

1.Define the callback function by using the PASCAL keyword. This causes the function parameters to be pushed onto the stack from right to left, just like standard Windows functions.

2.Define the callback function by using the FAR keyword. This allows the function to be called outside the code segment that contains the function. This rule does not apply to the WinMain function.

3.Compile the module that contains the callback function by using the /Gw option (not the GW option). This adds the proper Windows prolog and epilog code to the function, ensuring that the current data segment is used by the function when it runs.

4.List the callback function in the EXPORTS statement of the application's module-definition (.DEF) file. This defines the ordinal value and attributes of the callback function.

With the exception of the WinMain function, your application passes the procedure-instance address of the callback function to a Windows function to tell Windows when it should execute the callback function. For example, when you create a dialog box, one of the parameters of the function that creates the dialog box is the procedure-instance address of the function that will handle the messages sent to the dialog box.

To create a procedure-instance address of a function, call the MakeProcInstance function. This function returns a procedure-instance address that points to prolog code that is executed before the function is executed. The prolog code binds the data segment of the instance of your application to the callback function. Thus, when the function is executed, it has access to variables and data in the data segment of the application instance. You need not create a procedure-instance address for the WinMain function or any window procedure that your application registers by using the RegisterClass function.

When your application no longer needs the callback function (that is, when you are certain Windows will no longer call it), you should call FreeProcInstance to free the function from the data segment.