【发布时间】:2018-06-26 06:24:36
【问题描述】:
我正在编写一个可直接在 Windows 上打印的 C++ 脚本。
目前我正在使用来自here的以下代码:
BOOL RawDataToPrinter(LPTSTR szPrinterName, LPBYTE lpData, DWORD dwCount)
{
BOOL bStatus = FALSE;
HANDLE hPrinter = NULL;
DOC_INFO_1 DocInfo;
DWORD dwJob = 0L;
DWORD dwBytesWritten = 0L;
bStatus = OpenPrinter(szPrinterName, &hPrinter, NULL);
if (bStatus) {
// Fill in the structure with info about this "document."
DocInfo.pDocName = (LPTSTR)_T("My Document");
DocInfo.pOutputFile = NULL;
DocInfo.pDatatype = (LPTSTR)_T("RAW");
// Inform the spooler the document is beginning.
dwJob = StartDocPrinter(hPrinter, 1, (LPBYTE)&DocInfo);
if (dwJob > 0) {
// Start a page.
bStatus = StartPagePrinter(hPrinter);
if (bStatus) {
// Send the data to the printer.
bStatus = WritePrinter(hPrinter, lpData, dwCount, &dwBytesWritten);
EndPagePrinter(hPrinter);
}
// Inform the spooler that the document is ending.
EndDocPrinter(hPrinter);
}
// Close the printer handle.
ClosePrinter(hPrinter);
std::cout << GetLastError() << std::endl;
}
// Check to see if correct number of bytes were written.
if (!bStatus || (dwBytesWritten != dwCount)) {
bStatus = FALSE;
}
else {
bStatus = TRUE;
}
return bStatus;
}
我正在调用该方法:
std::string str = "Hello World";
BOOL blubb = RawDataToPrinter((LPTSTR)_T("PRINTER_NAME"), (LPBYTE) str.c_str(), str.size());
我遇到的问题是打印作业在我的打印机的打印队列中显示了几毫秒(刚好够看到),但他没有打印任何东西。
有人知道我做错了什么吗?
【问题讨论】:
-
sizeof(str)将 not 为您提供您所期望的(包含的字符串的长度)。为此使用str.size()。 -
我试过了,结果和之前一样
-
为什么需要
(LPTSTR)演员?只需_T("PRINTER_NAME")就足够了。也不能选择使用CreateDC进行直接打印吗? -
我使用了强制转换,因为示例代码提供了它。而且我不知道是否需要使用
CreateDC。 -
我无法发现您的代码有错误。我的意思是,如果您只想绕过打印对话框,请使用
HDC hdc = CreateDC(L"WINSPOOL", L"Printer Name", NULL, NULL); StartDoc, StartPage, TextOut(hdc,...)(这与 RAW 无关)
标签: c++ windows winapi printing