Mandar comandos a impresora

24/08/2004 - 16:04 por Guillermo Ruiz | Informe spam
Hola a todos,

Vuelvo a tener una serie de dudas sobre el envío de comandos a una impresora
térmica conectada
en el puerto LPT1.
Dichos comandos son una serie de letras y numeros separados por comas y
acabados en un salto de
línea que la impresora debe detectar como comandos propios.

He probado una solución propuesta en una respuesta a mi mensaje previo, que
consiste en usar
el objeto printer y enviar por allí dichos comandos.
El problema es que la impresora no parece reconocer dichos comandos más que
como texto, incluso
cambiando las letras,comas y saltos de línea por su valor ascii.

Ej de ordenes que he mandado:
Printer.Print Chr(10) //Salto de linea para empezar los comandos
Printer.Print "N" & Chr(10) // N es la orden para limpiar el buffer
Printer.Print "R50" & Chr(44) & 100 & Chr(10) // R50, 100 es la orden para
posicionar el texto
Printer.Print "A50,0,0,1,1,1,N," & Chr(44) & "Ejemplo1" & Chr(44) & Chr(10)
// A50,0,0,1,1,1,N,"Ejemplo1" imprimiría el texto Ejemplo 1 en tamaño
pequeño
Printer.Print "P" & Chr(10) // es la orden para imprimir todo
Printer.EndDoc

También he probado a abrir la impresora como un archivo y mandarle los
comandos, pero no logra imprimir nada.

Ej:
Open "LPT1" for output as #1
Print #1, "A50,0,0,1,1,1,N," & Chr(44) & "Ejemplo1" & Chr(44) & Chr(10)
Close #1

Entiendo que debe de haber una solución para que las cadenas de texto que
envíe a la impresora
sean interpretadas por esta como comandos propios, pero no se encontrarla.

Se agradecerá cualquier tipo de ayuda :)
 

Leer las respuestas

#1 Yosall
25/08/2004 - 00:22 | Informe spam
Ok, mira primero agrega un archivo de clase a tu aplicación

y llama ese archivo con el Nombre RawPrinterHelper

Agrega el siguiente código a tu nueva clase


Imports System.IO
Imports System.Drawing.Printing
Imports System.Runtime.InteropServices

Public Class RawPrinterHelper
' Structure and API declarions:
<StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Unicode)> _
Structure DOCINFOW
<MarshalAs(UnmanagedType.LPWStr)> Public pDocName As String
<MarshalAs(UnmanagedType.LPWStr)> Public pOutputFile As String
<MarshalAs(UnmanagedType.LPWStr)> Public pDataType As String
End Structure

<DllImport("winspool.Drv", EntryPoint:="OpenPrinterW", _
SetLastError:=True, CharSet:=CharSet.Unicode, _
ExactSpelling:=True, CallingConvention:=CallingConvention.StdCall)> _
Public Shared Function OpenPrinter(ByVal src As String, ByRef hPrinter
As IntPtr, ByVal pd As Long) As Boolean
End Function
<DllImport("winspool.Drv", EntryPoint:="ClosePrinter", _
SetLastError:=True, CharSet:=CharSet.Unicode, _
ExactSpelling:=True, CallingConvention:=CallingConvention.StdCall)> _
Public Shared Function ClosePrinter(ByVal hPrinter As IntPtr) As Boolean
End Function
<DllImport("winspool.Drv", EntryPoint:="StartDocPrinterW", _
SetLastError:=True, CharSet:=CharSet.Unicode, _
ExactSpelling:=True, CallingConvention:=CallingConvention.StdCall)> _
Public Shared Function StartDocPrinter(ByVal hPrinter As IntPtr, ByVal
level As Int32, ByRef pDI As DOCINFOW) As Boolean
End Function
<DllImport("winspool.Drv", EntryPoint:="EndDocPrinter", _
SetLastError:=True, CharSet:=CharSet.Unicode, _
ExactSpelling:=True, CallingConvention:=CallingConvention.StdCall)> _
Public Shared Function EndDocPrinter(ByVal hPrinter As IntPtr) As
Boolean
End Function
<DllImport("winspool.Drv", EntryPoint:="StartPagePrinter", _
SetLastError:=True, CharSet:=CharSet.Unicode, _
ExactSpelling:=True, CallingConvention:=CallingConvention.StdCall)> _
Public Shared Function StartPagePrinter(ByVal hPrinter As IntPtr) As
Boolean
End Function
<DllImport("winspool.Drv", EntryPoint:="EndPagePrinter", _
SetLastError:=True, CharSet:=CharSet.Unicode, _
ExactSpelling:=True, CallingConvention:=CallingConvention.StdCall)> _
Public Shared Function EndPagePrinter(ByVal hPrinter As IntPtr) As
Boolean
End Function
<DllImport("winspool.Drv", EntryPoint:="WritePrinter", _
SetLastError:=True, CharSet:=CharSet.Unicode, _
ExactSpelling:=True, CallingConvention:=CallingConvention.StdCall)> _
Public Shared Function WritePrinter(ByVal hPrinter As IntPtr, ByVal
pBytes As IntPtr, ByVal dwCount As Int32, ByRef dwWritten As Int32) As
Boolean
End Function
<DllImport("kernel32.dll", EntryPoint:="GetLastError", _
SetLastError:=True, CharSet:=CharSet.Unicode, _
ExactSpelling:=True, CallingConvention:=CallingConvention.StdCall)> _
Public Shared Function GetLastError() As Int32
End Function

' SendBytesToPrinter()
' 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 or False on failure.
Public Shared Function SendBytesToPrinter(ByVal szPrinterName As String,
ByVal pBytes As IntPtr, ByVal dwCount As Int32, ByVal NombreDocumento As
String) As Boolean
Dim hPrinter As IntPtr ' The printer handle.
Dim dwError As Int32 ' Last error - in case there was
trouble.
Dim di As DOCINFOW ' Describes your document (name, port,
data type).
Dim dwWritten As Int32 ' The number of bytes written by
WritePrinter().
Dim bSuccess As Boolean ' Your success code.

' Set up the DOCINFO structure.
With di
.pDocName = NombreDocumento
.pDataType = "RAW"
End With
' Assume failure unless you specifically succeed.
bSuccess = False
If OpenPrinter(szPrinterName, hPrinter, 0) Then
If StartDocPrinter(hPrinter, 1, di) Then
If StartPagePrinter(hPrinter) Then
' Write your printer-specific bytes to the printer.
bSuccess = WritePrinter(hPrinter, pBytes, dwCount,
dwWritten)
EndPagePrinter(hPrinter)
End If
EndDocPrinter(hPrinter)
End If
ClosePrinter(hPrinter)
End If
' If you did not succeed, GetLastError may give more information
' about why not.
If bSuccess = False Then
dwError = GetLastError()
End If
Return bSuccess
End Function ' SendBytesToPrinter()

' SendFileToPrinter()
' When the function is given a file name and a printer name,
' the function reads the contents of the file and sends the
' contents to the printer.
' Presumes that the file contains printer-ready data.
' Shows how to use the SendBytesToPrinter function.
' Returns True on success or False on failure.
Public Shared Function SendFileToPrinter(ByVal szPrinterName As String,
ByVal szFileName As String, ByVal NombreDocumento As String) As Boolean
' Open the file.
Dim fs As New FileStream(szFileName, FileMode.Open)
' Create a BinaryReader on the file.
Dim br As New BinaryReader(fs)
' Dim an array of bytes large enough to hold the file's contents.
Dim bytes(fs.Length) As Byte
Dim bSuccess As Boolean
' Your unmanaged pointer
Dim pUnmanagedBytes As IntPtr

' Read the contents of the file into the array.
bytes = br.ReadBytes(fs.Length)
' Allocate some unmanaged memory for those bytes.
pUnmanagedBytes = Marshal.AllocCoTaskMem(fs.Length)
' Copy the managed byte array into the unmanaged array.
Marshal.Copy(bytes, 0, pUnmanagedBytes, fs.Length)
' Send the unmanaged bytes to the printer.
bSuccess = SendBytesToPrinter(szPrinterName, pUnmanagedBytes,
fs.Length, NombreDocumento)
' Free the unmanaged memory that you allocated earlier.
Marshal.FreeCoTaskMem(pUnmanagedBytes)
Return bSuccess
End Function ' SendFileToPrinter()

' When the function is given a string and a printer name,
' the function sends the string to the printer as raw bytes.
Public Shared Function SendStringToPrinter(ByVal szPrinterName As
String, ByVal szString As String, ByVal NombreDocumento As String)
Dim pBytes As IntPtr
Dim dwCount As Int32
' How many characters are in the string?
dwCount = szString.Length()
' Assume that the printer is expecting ANSI text, and then convert
' the string to ANSI text.
pBytes = Marshal.StringToCoTaskMemAnsi(szString)
' Send the converted ANSI string to the printer.
SendBytesToPrinter(szPrinterName, pBytes, dwCount, NombreDocumento)
Marshal.FreeCoTaskMem(pBytes)
End Function
End Class




Y finalmente puedes ocupar la impresora de la siguiente manera

Dim Resultado as string

If CortaPapel = True Then Resultado = Resultado + Chr(27) + Chr(105)

RawPrinterHelper.SendStringToPrinter('Aqui va el nombre de la
impresora', Resultado, "Este es el nombre del documento a imprimir" )




Eduardo Puchades Fuentes
MCSD .NET
-Quien solo busca el placer del cuerpo
ha olvidado que tiene cerebro-

Preguntas similares