Share via


方法: GDI プリンターにデータを直接送信する

このトピックの後半のコード サンプルでは、GDI ベースのプリンター ドライバーを使用するプリンターにプリンターコントロールデータを直接送信する方法を示します。

次の手順では、プリンターにデータを直接送信する方法について説明します。 これらの手順は、次のコード例でも示されています。

  1. OpenPrinter を呼び出して、プリンターへのハンドルを取得します。
  2. プリンター データを使用して DOCINFO 構造体を初期化します。
  3. StartDocPrinter を呼び出して、アプリケーションがプリンターにドキュメント データを送信することを示します。
  4. StartPagePrinter を呼び出して、アプリケーションがプリンターに新しいページを送信することを示します。
  5. WritePrinter を呼び出してデータを送信します。
  6. EndPagePrinter を呼び出して、現在のページのすべてのデータが送信されたことを示します。
  7. EndDocPrinter を呼び出して、このドキュメントのすべてのデータが送信されたことを示します。
  8. ClosePrinter を呼び出してリソースを解放します。

GDI ベースのプリンター ドライバーを使用するプリンターにプリンターコントロールデータを直接送信します。

// 
// RawDataToPrinter - sends binary data directly to a printer 
//  
// szPrinterName: NULL-terminated string specifying printer name 
// lpData:        Pointer to raw data bytes 
// dwCount        Length of lpData in bytes 
//  
// Returns: TRUE for success, FALSE for failure. 
//  
BOOL RawDataToPrinter(LPTSTR szPrinterName, LPBYTE lpData, DWORD dwCount)
{
    BOOL     bStatus = FALSE;
    HANDLE     hPrinter = NULL;
    DOC_INFO_1 DocInfo;
    DWORD      dwJob = 0L;
    DWORD      dwBytesWritten = 0L;

    // Open a handle to the printer. 
    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 );
    }
    // Check to see if correct number of bytes were written. 
    if (!bStatus || (dwBytesWritten != dwCount)) {
        bStatus = FALSE;
    } else {
        bStatus = TRUE;
    }
    return bStatus;
}

ClosePrinter

EndDocPrinter

EndPagePrinter

OpenPrinter

StartDocPrinter

StartPagePrinter

WritePrinter