Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default Printer in Unmanaged C++

I'm looking for a way to find the name of the Windows default printer using unmanaged C++ (found plenty of .NET examples, but no success unmanaged). Thanks.

like image 589
Blumer Avatar asked Feb 03 '26 21:02

Blumer


2 Answers

Here is how to get a list of current printers and the default one if there is one set as the default.

Also note: getting zero for the default printer name length is valid if the user has no printers or has not set one as default.

Also being able to handle long printer names should be supported so calling GetDefaultPrinter with NULL as a buffer pointer first will return the name length and then you can allocate a name buffer big enough to hold the name.

DWORD numprinters;
DWORD defprinter=0;
DWORD               dwSizeNeeded=0;
DWORD               dwItem;
LPPRINTER_INFO_2    printerinfo = NULL;

// Get buffer size

EnumPrinters ( PRINTER_ENUM_LOCAL | PRINTER_ENUM_CONNECTIONS , NULL, 2, NULL, 0, &dwSizeNeeded, &numprinters );

// allocate memory
//printerinfo = (LPPRINTER_INFO_2)HeapAlloc ( GetProcessHeap (), HEAP_ZERO_MEMORY, dwSizeNeeded );
printerinfo = (LPPRINTER_INFO_2)new char[dwSizeNeeded];

if ( EnumPrinters ( PRINTER_ENUM_LOCAL | PRINTER_ENUM_CONNECTIONS,      // what to enumerate
            NULL,           // printer name (NULL for all)
            2,              // level
            (LPBYTE)printerinfo,        // buffer
            dwSizeNeeded,       // size of buffer
            &dwSizeNeeded,      // returns size
            &numprinters            // return num. items
          ) == 0 )
{
    numprinters=0;
}

{
    DWORD size=0;   

    // Get the size of the default printer name.
    GetDefaultPrinter(NULL, &size);
    if(size)
    {
       // Allocate a buffer large enough to hold the printer name.
        TCHAR* buffer = new TCHAR[size];

          // Get the printer name.
        GetDefaultPrinter(buffer, &size);

        for ( dwItem = 0; dwItem < numprinters; dwItem++ )
        {
                          if(!strcmp(buffer,printerinfo[dwItem].pPrinterName))
                defprinter=dwItem;
        }
        delete buffer;
    }
}
like image 58
KPexEA Avatar answered Feb 06 '26 12:02

KPexEA


The following works great for printing with the win32api from C++

char szPrinterName[255];
unsigned long lPrinterNameLength;
GetDefaultPrinter( szPrinterName, &lPrinterNameLength );
HDC hPrinterDC;
hPrinterDC = CreateDC("WINSPOOL\0", szPrinterName, NULL, NULL);

In the future instead of googling "unmanaged" try googling "win32 /subject/" or "win32 api /subject/"

like image 44
Doug T. Avatar answered Feb 06 '26 13:02

Doug T.