In order to create a printer device context, you need information about the printer, such as its type and the computer port to which it is connected. The Windows Control Panel application adds information about the current printer to the device= field 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 fields, separated by commas:
The type of the current device driver (for example, “EPSON”)
The type of the current printer (for example, “EPSON FX-80”)
The current printer port (for example, LPT1:)
The following example shows how to retrieve the printer information and divide the fields into separate strings:
char pPrintInfo[80];
LPSTR lpTemp;
LPSTR lpPrintType;
LPSTR lpPrintDriver;
LPSTR lpPrintPort;
.
.
.
1 GetProfileString(“windows”,
“device”,
pPrintInfo,
(LPSTR) NULL, 80);
lpTemp = lpPrintType = pPrintInfo;
lpPrintDriver = lpPrintPort = 0;
2 while(*lpTemp) {
3 if(*lpTemp == ',') {
*lpTemp++ = 0;
4 while (*lpTemp == ' ')
lpTemp++;
if(!lpPrintDriver)
lpPrintDriver = lpTemp;
else {
lpPrintPort = lpTemp;
break;
}
}
else
lpTemp=AnsiNext(lpTemp);
}
5 hPr = CreateDC(lpPrintDriver,
pPrinterType,
lpPrintPort,
(LPSTR) NULL);
.
.
.
}
In this example:
1 | The GetProfileString function retrieves the device= field from the [windows] section of the WIN.INI file. The function then copies the line to the pPrintInfo array. |
2 | A while statement divides the line into three separate fields: the printer type, the printer device-driver name, and the printer port. |
3 | 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 terminate the field. |
4 | Another while statement skips any leading spaces in the next field. Each pointer—lpPrintType, lpPrintDriver, and lpPrintPort—receives the address of the beginning of its respective field. |
5 | These pointers are then used in the CreateDC function to create a printer device context for the current printer. |