Setting Up the Printed Page

This topic describes sample code that displays a Page Setup dialog box so a user can select the attributes of the printed page, such as the paper type, paper source, page orientation, and page margins. The sample code first initializes a PAGESETUPDLG structure, and then calls the PageSetupDlg function to display the dialog box.

This example sets the PSD_MARGINS flag in the Flags member and uses the rtMargin member to specify the initial margin values. It sets the PSD_INTHOUSANDTHSOFINCHES flag to ensure that the dialog box expresses margin dimensions in thousandths of an inch.

On input, the sample code sets the hDevMode and hDevNames members to NULL. If the function returns TRUE, the function uses these members to return handles to DEVMODE and DEVNAMES structures containing the user's input and information about the printer. You can use this information to prepare the output to be sent to the selected printer.

The example also enables a PagePaintHook hook procedure to customize drawing of the contents of the sample page.

PAGESETUPDLG psd; // common dialog box structure
HWND hwnd; // owner window

// Initialize PAGESETUPDLG
ZeroMemory(&psd, sizeof(PAGESETUPDLG));

psd.lStructSize = sizeof(PAGESETUPDLG);
psd.hwndOwner = hwnd;
psd.hDevMode = NULL; // Don't forget to free or store hDevMode.
psd.hDevNames = NULL; // Don't forget to free or store
hDevNames.
psd.Flags = PSD_INTHOUSANDTHSOFINCHES | PSD_MARGINS |
PSD_ENABLEPAGEPAINTHOOK;
psd.rtMargin.top = 1000;
psd.rtMargin.left = 1250;
psd.rtMargin.right = 1250;
psd.rtMargin.bottom = 1000;
psd.lpfnPagePaintHook = PaintHook;

if (PageSetupDlg(&psd)==TRUE) {
// check paper size and margin values here
}

The following example shows a sample PagePaintHook hook procedure that draws the margin rectangle in the sample page area:

BOOL CALLBACK PaintHook(HWND hwndDlg, UINT uMsg, WPARAM wParam,

LPARAM lParam)

{

LPRECT lprc;

COLORREF crMargRect;

HDC hdc, hdcOld;

switch (uMsg) {

// Drawing the margin rectangle.

case WM_PSD_MARGINRECT:

hdc = (HDC) wParam;

lprc = (LPRECT) lParam;

// Get the system highlight color.

crMargRect = GetSysColor(COLOR_HIGHLIGHT);

// Create a dash-dot pen of the system highlight color and

// select it into the DC of the sample page.

hdcOld = SelectObject(hdc, CreatePen(PS_DASHDOT, .5,

crMargRect));

// Draw the margin rectangle.

Rectangle(hdc, lprc->left, lprc->top, lprc->right,

lprc->bottom);

// Restore the previous pen to the DC.

SelectObject(hdc, hdcOld);

return TRUE;

default:

return FALSE;

}

return TRUE;

}