c# - 使用C#.net直接向LPT并口发送打印命令

标签 c# printing lpt

<分区>

在 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/

相关文章:

c# - 如何在 C#.net 中获取此计数查询

c# - 选择进入解释/临时表

c# - 在通用应用程序中打印

c++ - 在 C++ 中访问 LPT

c# - 如何获取随机索引的 DropDownList 值?

c# - 在 Linux 上反序列化 TimeZoneInfo 会抛出 `The Month parameter must be in the range 1 through 12`

java - 需要将 RAW 打印数据转换为 ps/pdf 或从 Java 打印

java - 更改 JTextPane 上的打印边距

c# - Windows 监控并行或 LPT 端口

c# - C#中高速切换位