C++:删除打印机队列

标签 c++ winapi printing error-handling

我正在尝试从打印机中删除队列中的所有文件。我找到了 this piece of code这看起来很简单。

我尝试使用以下代码删除队列。它编译,但 SetPrinter 返回 false。我收到的错误消息是 5,我尝试使用 from this question 方法将其解码为“正常”错误消息。 .但是我无法用它编译,因为 STR_ELEMS 是未定义的。在谷歌上搜索“STR_ELEMS is undefined”,但遇到了死胡同。

谁能帮我解码错误信息并删除打印机队列?

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

}

我的包括:

#include <windows.h>
#include <winspool.h>

最佳答案

错误代码 5 表示“访问被拒绝”。 ( System Error Codes )

尝试以管理员权限运行。

要根据 GetLastError 的返回值格式化可打印的错误消息,请使用 FormatMessage,如下所示:

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

此外,您可以尝试将 PRINTER_DEFAULTS 结构传递给 OpenPrinter,可能像这样:

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

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

关于C++:删除打印机队列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22825373/

相关文章:

c++ - QString::arg() 调整变量的大小并删除空格

NetBeans 中的 C++ 显示错误(无法解析标识符)但代码运行正常

c++ - WINAPI C++获取当前的物理驱动器号

c - 如何使用 wchar_t* 在 C 中提取和附加路径

java - 为什么使用相同的页码多次调用 java Printable 的打印方法?

c++ - 对字符串数组进行排序

c++ - 图像卷积与高斯模糊,加速可能吗?

c - 以编程方式查找单词含义并将其打印到文件

asp.net - ASP :multiview control - can we show all the views on one tab instead of different tabs

c# - 如何在不遍历所有 papersources 的情况下直接打印到 "Tray 2"