12.2 Retrieving Information About the Current Printer

To create a printer device context for your application, you need information about the printer, such as its type and the computer port to which it is connected. Windows Control Panel adds information about the current printer to the device= setting in the [windows] section of the WIN.INI file. Any application can retrieve this information by using the GetProfileString function. You can then use the information with the CreateDC function to create a printer device context for a particular printer on a particular computer port.

Printer information from the WIN.INI file consists of three settings, separated by commas:

The name of the current printer device driver (for example, EPSON9)

The name of the current printer model (for example, Epson FX-80)

The current printer port (for example, LPT1:)

The following example retrieves printer information for the currently selected default printer and divides the fields into separate strings:

char  pPrintInfo[80];
LPSTR lpTemp;
LPSTR lpPrintDevice;
LPSTR lpPrintDriver;
LPSTR lpPrintPort;

GetProfileString("windows",
    "device",
    "",
    (LPSTR) pPrintInfo, 80);
lpTemp = lpPrintDevice = (LPSTR) pPrintInfo;
lpPrintDriver = lpPrintPort = (LPSTR) NULL;

while (*lpTemp) {
    if (*lpTemp == ',') {
        *lpTemp++ = 0;
        while (*lpTemp == ' ')
            lpTemp++;
        if (!lpPrintDriver)
            lpPrintDriver = lpTemp;
        else {
            lpPrintPort = lpTemp;
            break;
        }
    }

    else
        lpTemp = AnsiNext(lpTemp);
}

In this example, the GetProfileString function retrieves information about the currently selected default printer from the device= field in the [windows] section of the WIN.INI file. The function then copies the line to the pPrintInfo array.

A while statement divides the line into three separate fields: the printer driver name, the name of the printer model, and the printer port.

Because the fields are separated by commas, an if statement checks for a comma and, if necessary, replaces the comma with a zero in order to end the field with a terminating null character.

Another while statement skips any leading spaces in the next field. Each pointer—lpPrintDrvName, lpPrintModel, and lpPrintPort—receives the address of the beginning of its respective field.

These pointers are then used in a call to the CreateDC function to create a printer device context for the current printer.