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

21,738

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.

Share:
21,738
HackTweaks
Author by

HackTweaks

Updated on July 05, 2022

Comments

  • HackTweaks
    HackTweaks almost 2 years

    As in DOS we can do:

    ECHO MESSAGE>LPT1
    

    How can we achieve same thing in C# .NET?

    Sending information to COM1 seems to be easy using C# .NET.

    What about LPT1 ports?

    I want to send Escape commands to the thermal printer.