CPrintDialog Creation Failing in Service Mode of an Application

跟風遠走 提交于 2019-12-04 06:37:11

问题


I have an application that prints the report automatically. I am using CPrintDialog to get the Printer DC.

void CMyClass::PrintReport()
{
    CDC dc;
    CPrintDialog printDlg(FALSE);
    printDlg.GetDefaults ();
    ::DeleteDC( printDlg.m_pd.hDC );
    LPDEVMODE pDevMode = printDlg.GetDevMode();
    if(pDevMode)
    {
        pDevMode->dmOrientation = DMORIENT_LANDSCAPE;
        ::GlobalUnlock(pDevMode);
    }
    HDC hDC;
    if( (hDC = printDlg.CreatePrinterDC()) == NULL )
    {
        ::GlobalFree( printDlg.m_pd.hDevMode );
        ::GlobalFree( printDlg.m_pd.hDevNames );
        return;
    }
    ::GlobalFree( printDlg.m_pd.hDevMode );
    ::GlobalFree( printDlg.m_pd.hDevNames );
    dc.Attach(hDC);         // Attach a printer DC
    dc.m_bPrinting = TRUE;
    dc.SetMapMode(MM_LOENGLISH);
    /* 

        Printing Logic using dc
    */
}

This works fine when I run my application in the Debug mode which comes a a Console application.

But, the CPrintDialog creation is failing when I run the application as a Windows Service.

Am I doing anything wrong? :( Please help me.

Note: The Application is designed in a way to run as a Service in the Installation.


回答1:


the CPrintDialog creation is failing when I run the application as a Windows Service.

You cannot display dialogs (or any type of user interface) in a Windows Service. So CPrintDialog is never going to work.

But you don't need to create a dialog to get a printer device context, assuming that you already know which printer you want to print to. And since you're running as a non-interactive service, you must already know this, because there's no way that the user can choose a printer.

To do so, just call CreateDC directly, specifying "WINSPOOL" as the device and the name of the printer. You can obtain the name of the desired printer by enumerating the installed printers using the EnumPrinters function. This is all conveniently documented in a how-to article: Retrieve a Printer Device Context.



来源:https://stackoverflow.com/questions/23211832/cprintdialog-creation-failing-in-service-mode-of-an-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!