使用C#.net直接将打印命令发送到LPT并行端口

在DOS中我们可以这样做:

ECHO MESSAGE>LPT1 

我们如何在C#.NET中实现同样的function?

使用C#.NET将信息发送到COM1似乎很容易。

LPT1端口怎么样?

我想将Escape命令发送到热敏打印机。

在C#4.0及更高版本中,首先需要使用CreateFile方法连接到该端口,然后打开该端口的文件流以最终写入该端口。 这是一个示例类,它在LPT1上将两行写入打印机。

 using Microsoft.Win32.SafeHandles; using System; using System.IO; using System.Runtime.InteropServices; namespace YourNamespace { public static class Print2LPT { [DllImport("kernel32.dll", SetLastError = true)] static extern SafeFileHandle CreateFile(string lpFileName, FileAccess dwDesiredAccess,uint dwShareMode, IntPtr lpSecurityAttributes, FileMode dwCreationDisposition, uint dwFlagsAndAttributes, IntPtr hTemplateFile); public static bool Print() { string nl = Convert.ToChar(13).ToString() + Convert.ToChar(10).ToString(); bool IsConnected= false; string sampleText ="Hello World!" + nl + "Enjoy Printing..."; try { Byte[] buffer = new byte[sampleText.Length]; buffer = System.Text.Encoding.ASCII.GetBytes(sampleText); SafeFileHandle fh = CreateFile("LPT1:", FileAccess.Write, 0, IntPtr.Zero, FileMode.OpenOrCreate, 0, IntPtr.Zero); if (!fh.IsInvalid) { IsConnected= true; FileStream lpt1 = new FileStream(fh,FileAccess.ReadWrite); lpt1.Write(buffer, 0, buffer.Length); lpt1.Close(); } } catch (Exception ex) { string message = ex.Message; } return IsConnected; } } } 

假设您的打印机已连接到LPT1端口,如果不是,则需要调整CreateFile方法以匹配您正在使用的端口。

您可以使用以下行在程序中的任何位置调用该方法

 Print2LPT.Print(); 

我认为这是解决问题的最短,最有效的解决方案。

您可以随时尝试此代码示例 。

Br Anders

您应该从microsoft的这篇文章中获得一些帮助: 如何使用Visual C#.NET将原始数据发送到打印机