Send print commands directly to LPT parallel port using C#.net [duplicate]

隐身守侯 提交于 2019-11-29 16:35:36

In C# 4.0 and later its possible, first you need to connect to that port using the CreateFile method then open a filestream to that port to finally write to it. Here is a sample class that writes two lines to the printer on 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;
            }
        }
}

Assuming your printer is connected on the LPT1 port, if not you will need to adjust the CreateFile method to match the port you are using.

you can call the method anywhere in your program with the following line

Print2LPT.Print();

I think this is the shortest and most efficient solution to your problem.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!