Printing to LPT1 in C#

前端 未结 3 2031
逝去的感伤
逝去的感伤 2021-01-31 23:50

How do you print directly to a dot matrix printer in C# using file LPT1.

I did it on C++ with fopen, but I don\'t know how to do it in c#.

thank you very much

3条回答
  •  失恋的感觉
    2021-02-01 00:33

    In C# 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.

提交回复
热议问题