<分区>
在 DOS 中我们可以这样做:
ECHO MESSAGE>LPT1
我们如何在 C# .NET 中实现同样的事情?
使用 C# .NET 向 COM1 发送信息似乎很容易。
LPT1 端口呢?
我想向热敏打印机发送 Escape 命令。
<分区>
在 DOS 中我们可以这样做:
ECHO MESSAGE>LPT1
我们如何在 C# .NET 中实现同样的事情?
使用 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();
我认为这是解决您的问题的最短且最有效的解决方案。
关于c# - 使用C#.net直接向LPT并口发送打印命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4692937/