cwinapicreatefileprinterslpt

Can't get port handle from LPT1


I'm writing a program which reads from file and send to printer to print.

I set "HP Laser Jet 4" as default printer and checked "LPT1" in printer properties of "HP Laser Jet 4". Print spooler is also running (Windows 7).

The problem is hPort always returns INVALID_HANDLE_VALUE.

I don't have a real printer. Is it a problem?

#include "stdafx.h"
#include <windows.h>

int main()
{
    HANDLE hPort = CreateFile(_T("LPT1:"), GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
    if(hPort != INVALID_HANDLE_VALUE) {
        printf("success");
    } else {
        printf("%i", GetLastError());
    }    
    return 0;
}

Solution

  • Why you try for open LPT port. This is realy need for you? If printer (e.g. HP Laser Jet 4 or any other) installed in OS and you want to write to it directly without using printer driver, you can write data (from file, for example) as showed bellow:

    TCHAR *pPrinterName = TEXT("HP Laser Jet 4");
    TCHAR *pFileName = TEXT("c:\filename.prn");
    HANDLE hPrinter = NULL;
    DOC_INFO_1 docinfo;
    FILE *pfile = NULL;
    DWORD dwBytesWritten = 0L;
    BYTE data[1024];
    DWORD dwCount = 0L;
    
    if (OpenPrinter(pPrinterName, &hPrinter, NULL))
    {
      docinfo.pDocName = TEXT("RAW Output Document Name");
      docinfo.pOutputFile = NULL;
      docinfo.pDatatype = TEXT("RAW");
    
      DWORD dwPrtJob = StartDocPrinter(hPrinter, 1, (LPBYTE)&docinfo);
    
      if (dwPrtJob > 0)
      {
        if (0 == _tfopen_s(&pfile, pFileName, TEXT("rb")))
        {
          while (!feof(pfile))
          {
            dwCount = (DWORD)fread(&data, 1, 1024, pfile);
            WritePrinter(hPrinter, &data, dwCount, &dwBytesWritten);
          }
          fclose(pfile);
        }
      }
      EndDocPrinter(hPrinter);
      ClosePrinter(hPrinter);
    }
    

    May be, this code has some errors. I am do not test it. I am simply cut it from one my old project.

    In same manner you can send file (that contains printer commands - PCL/PJL for HP PCL5/PCL6 printers, for example) to any printer/port.