public static bool ReadFromPrinter(string szPrinterName, IntPtr pBytes, Int32 dwCount) { // Read the data from the printer. Int32 dwError = 0, dwBytesRead = 0; IntPtr hPrinter = new IntPtr(0); NativeMethods.DOCINFOA di = new NativeMethods.DOCINFOA(); NativeMethods.PRINTER_DEFAULTS pd = new NativeMethods.PRINTER_DEFAULTS(); pd.DesiredAccess = 0x00000020; bool bSuccess = false; // Open the printer. if (NativeMethods.OpenPrinter2(szPrinterName.Normalize(), out hPrinter, pd)) { // Start a document. if (NativeMethods.StartDocPrinter(hPrinter, 1, di)) { // Start a page. if (NativeMethods.StartPagePrinter(hPrinter)) { // read your bytes. bSuccess = NativeMethods.ReadPrinter(hPrinter, out pBytes, dwCount, out dwBytesRead); // If you did not succeed, GetLastError may give more information // about why not. if (bSuccess == false) { dwError = Marshal.GetLastWin32Error(); } NativeMethods.EndPagePrinter(hPrinter); } NativeMethods.EndDocPrinter(hPrinter); } NativeMethods.ClosePrinter(hPrinter); } return(bSuccess); }
/// <summary> /// Send unmanaged data to the target printer. /// When the function is given a printer name and an unmanaged array /// of bytes, the function sends those bytes to the print queue. /// Returns true on success, false on failure. /// </summary> /// <param name="szPrinterName">String name of printer</param> /// <param name="pBytes">Pointer to data</param> /// <param name="dwCount">Length of data in bytes</param> /// <returns>bool</returns> public static bool SendBytesToPrinter(string szPrinterName, IntPtr pBytes, Int32 dwCount) { Int32 dwError = 0, dwWritten = 0; IntPtr hPrinter = new IntPtr(0); NativeMethods.DOCINFOA di = new NativeMethods.DOCINFOA(); bool bSuccess = false; // Assume failure unless you specifically succeed. di.pDocName = "ESCPOSTTester"; di.pDataType = "RAW"; // Open the printer. if (NativeMethods.OpenPrinter(szPrinterName.Normalize(), out hPrinter, IntPtr.Zero)) { // Start a document. if (NativeMethods.StartDocPrinter(hPrinter, 1, di)) { // Start a page. if (NativeMethods.StartPagePrinter(hPrinter)) { bSuccess = NativeMethods.WritePrinter(hPrinter, pBytes, dwCount, out dwWritten); NativeMethods.EndPagePrinter(hPrinter); } NativeMethods.EndDocPrinter(hPrinter); } NativeMethods.ClosePrinter(hPrinter); } // If you did not succeed, GetLastError may give more information // about why not. if (bSuccess == false) { dwError = Marshal.GetLastWin32Error(); } return(bSuccess); }