Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Deleting a printer queue

I'm trying to remove all the files in queue from a printer. I found this piece of code which seemed pretty straight forward.

I tried deleting the queue with the code below. It compiles, but SetPrinter returns false. The error message I got was 5, which I tried to decode to a "normal" error message using the approach from this question. But I wasn't able to compile with that, because STR_ELEMS is undefined. Searched google for "STR_ELEMS is undefined" but hit a dead end.

Can someone help me decode the error message and delete the printer queue?

BOOL bStatus = false;
HANDLE     hPrinter = NULL;
DOC_INFO_1 DocInfo;

bStatus = OpenPrinter((LPTSTR)_T("CN551A"), &hPrinter, NULL);

if(bStatus) {

    DWORD dwBufsize=0;

    GetPrinterA(hPrinter, 2, NULL, 0, &dwBufsize); // Edit: Returns false

    PRINTER_INFO_2* pinfo = (PRINTER_INFO_2*)malloc(dwBufsize);
    long result = GetPrinterA(hPrinter, 2, 
        (LPBYTE)pinfo, dwBufsize, &dwBufsize);

    if ( pinfo->cJobs==0 ) // Edit: pinfo->cJobs is not 0
    {
        printf("No printer jobs found.");
    }
    else
    {
        if ( SetPrinter(hPrinter, 0, 0, PRINTER_CONTROL_PURGE)==0 )
            printf("SetPrinter call failed: %x\n", GetLastError() );
        else printf("Number of printer jobs deleted: %u\n",
            pinfo->cJobs);
    }

    ClosePrinter( hPrinter );

}

My includes are:

#include <windows.h>
#include <winspool.h>
like image 757
Attaque Avatar asked Apr 08 '26 07:04

Attaque


1 Answers

The error code of 5 means "access is denied". (System Error Codes)

Try running with admin privileges.

To format a printable error message from the return value of GetLastError, use FormatMessage something like this:

  TCHAR buffer[256];
  if (0 == FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, 0,
           GetLastError(), 0, buffer, 256, 0)) {
    // FormatMessage failed.
  }

Also, you can try passing a PRINTER_DEFAULTS struct to OpenPrinter, maybe like this:

PRINTER_DEFAULTS PrnDefs;
PrnDefs.pDataType = "RAW";
PrnDefs.pDevMode = 0;
PrnDefs.DesiredAccess = PRINTER_ALL_ACCESS;

bStatus = OpenPrinter((LPTSTR)_T("CN551A"), &hPrinter, &PrnDefs);
like image 111
ooga Avatar answered Apr 10 '26 22:04

ooga