C++: Deleting a printer queue

蓝咒 提交于 2019-12-23 19:10:07

问题


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>

回答1:


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);


来源:https://stackoverflow.com/questions/22825373/c-deleting-a-printer-queue

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