Displaying the Page Setup Dialog Box

You can use the PageSetupDlg() API function to display the Page Setup dialog box.  All that's required is the initialization of a PAGESETUPDLG structure and a single call to PageSetupDlg() function.  The example below uses the VCL TPrinter object to invoke the changes.  Also demonstrated is the use of a hook procedure for centering the dialog box relative to the calling Form.

KEYWORDS: PageSetupDlg(), PAGESETUPDLG. 
 



 

//---------------------------------------------------------------------------

UINT APIENTRY PageSetupHook(HWND HDlg, UINT uiMsg, WPARAM WParam,
                            LPARAM LParam);

//---------------------------------------------------------------------------

void __fastcall TForm1::PageSetupClick(TObject *Sender)
{
    PAGESETUPDLG psd;
    ZeroMemory(&psd, sizeof(PAGESETUPDLG));

    // Initialize the PAGESETUPDLG structure
    psd.lStructSize = sizeof(PAGESETUPDLG);
    psd.hwndOwner = Handle;
    psd.Flags = PSD_ENABLEPAGESETUPHOOK;
    psd.lpfnPageSetupHook = PageSetupHook;

    // Display the dialog box
    if (PageSetupDlg(&psd))
    {
        HANDLE HMem;
        char device[MAX_PATH], driver[MAX_PATH], port[MAX_PATH];

        // use the TPrinter object to invoke the changes
        Printer()->PrinterIndex = Printer()->PrinterIndex;
        Printer()->GetPrinter(device, driver, port, (int)HMem);
        Printer()->SetPrinter(device, driver, port, (int)psd.hDevMode);        

        GlobalFree(HMem);
        GlobalFree(psd.hDevNames);
    }
}
//---------------------------------------------------------------------------

UINT APIENTRY PageSetupHook(HWND HDlg, UINT uiMsg, WPARAM WParam,
    LPARAM LParam)
{
    if (uiMsg == WM_INITDIALOG)
    {
        // in the WM_INITDIALOG message, the LParam is a
        // pointer to the PAGESETUPDLG structure used above
        RECT FormRect, DialogRect;
        LPPAGESETUPDLG lppsd = (LPPAGESETUPDLG)LParam;

        ::GetWindowRect(lppsd->hwndOwner, &FormRect);
        ::GetWindowRect(HDlg, &DialogRect);
        
        int cxForm = FormRect.right - FormRect.left;
        int cyForm = FormRect.bottom - FormRect.top;
        int cxDialog = DialogRect.right - DialogRect.left;
        int cyDialog = DialogRect.bottom - DialogRect.top;

        MoveWindow(HDlg,
                   (cxForm - cxDialog) / 2 + FormRect.left,
                   (cyForm - cyDialog) / 2 + FormRect.top,
                   cxDialog, cyDialog,
                   true);
    }
    return 0L;
}