在并行打印机上打印时,文本行顺序已更改 这适用于运行C#2.0的Windows 10
//PortType enum
//struct for PORT_INFO_2
[StructLayout(LayoutKind.Sequential)]
public struct PORT_INFO_2
{
public string pPortName;
public string pMonitorName;
public string pDescription;
public PortType fPortType;
internal int Reserved;
}
[Flags]
public enum PortType : int
{
write = 0x1,
read = 0x2,
redirected = 0x4,
net_attached = 0x8
}
//Win32 API
[DllImport("winspool.drv", EntryPoint = "EnumPortsA", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
public static extern int EnumPorts(string pName, int Level, IntPtr lpbPorts, int cbBuf, ref int pcbNeeded, ref int pcReturned);
public const short FILE_ATTRIBUTE_NORMAL = 0x80;
public const short INVALID_HANDLE_VALUE = -1;
public const uint GENERIC_READ = 0x80000000;
public const uint GENERIC_WRITE = 0x40000000;
public const uint CREATE_NEW = 1;
public const uint CREATE_ALWAYS = 2;
public const uint OPEN_EXISTING = 3;
[DllImport("kernel32.dll", SetLastError = true)]
static extern IntPtr CreateFile(string lpFileName, uint dwDesiredAccess,
uint dwShareMode, IntPtr lpSecurityAttributes, uint dwCreationDisposition,
uint dwFlagsAndAttributes, IntPtr hTemplateFile);
public int PrintText(string parallelport, string receiptText, Int16 nLen, Encoding encoding)
{
IntPtr ptr = CreateFile(parallelport, GENERIC_WRITE, 0,
IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero);
/* Is bad handle? INVALID_HANDLE_VALUE */
if (ptr.ToInt32() == -1)
{
/* ask the framework to marshall the win32 error code to an exception */
// Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
return (-1);
}
FileStream lpt = new FileStream(ptr, FileAccess.ReadWrite);
Byte[] buffer = new Byte[2048];
//Check to see if your printer support ASCII encoding or Unicode.
//If unicode is supported, use the following:
if (encoding == Encoding.Unicode)
{
buffer = System.Text.Encoding.Unicode.GetBytes(receiptText);
}
else if (encoding == Encoding.ASCII)
{
buffer = System.Text.Encoding.ASCII.GetBytes(receiptText);
}
lpt.Write(buffer, 0, buffer.Length);
lpt.Close();
return (0);
}
(调用部分) ParallelOutput po =新的ParallelOutput(); po.PrintText(“ LPT1”,strPrintText,Convert.ToInt16(strPrintText.Length),Encoding.ASCII);
另存为文件时,此模块可以正常工作。 但是,当打印到并行打印机时,行顺序会更改。 例如,如果将以下字符串传递到并行端口, AAAA BBBBBBBB 中华总商会 DDD 那么输出结果总是像下面这样。 BBBBBBBB 中华总商会 DDDAAAA