views:

769

answers:

5

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.

+3  A: 

Maybe this would help:

from the site:

char szPrinterName[255];
unsigned long lPrinterNameLentgth;
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/"

Doug T.
sometimes there is no default printer selected and in this case you will get 0 for printernamelength
KPexEA
+1  A: 

GetDefaultPrinter (MSDN) ought to do the trick. That will get you the name to pass to CreateDC for printing.

christopher_f
A: 

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;
 }
}
KPexEA
A: 

Unmanaged C++ doesn't exist (and managed C++ is now C++/CLI), if you are referring to C++, using unmanaged as a tag is just sad...

Panic
A: 

How to retrieve and set the default printer in Windows:

http://support.microsoft.com/default.aspx?scid=kb;EN-US;246772

jeffm