1

I have a program that can send print command to LPT source code below which i also followed from Send print commands directly to LPT parallel port using C#.net

Is there a way to check connectivity of LPT port programatically? Like if its online or connected to the computer?

[DllImport("kernel32.dll", SetLastError = true)]
static extern SafeFileHandle CreateFile(string lpFileName, FileAccess dwDesiredAccess, uint dwShareMode, IntPtr lpSecurityAttributes, FileMode dwCreationDisposition, uint dwFlagsAndAttributes, IntPtr hTemplateFile);
    

   
    public  bool Print(string Command)
    {
        string nl = Convert.ToChar(13).ToString() + Convert.ToChar(10).ToString();
        bool IsConnected = false;


        try
        {
            log.Info("COMMAND TO PRINT" + Command);

            Byte[] buffer = new byte[Command.Length];
            buffer = System.Text.Encoding.ASCII.GetBytes(Command);


            FileStream lpt1 = null;

            SafeFileHandle fh = CreateFile("LPT1:", FileAccess.Write, 0, IntPtr.Zero, FileMode.OpenOrCreate, 0, IntPtr.Zero);
           
           
            if (!fh.IsInvalid)
            {

           
                IsConnected = true;
                lpt1 = new FileStream(fh, FileAccess.ReadWrite);
                lpt1.Write(buffer, 0, buffer.Length);
                lpt1.Close();

            }
      
            lpt1.Dispose();

            if (lpt1 == null)
            {
                log.Info("LPT File is Disposed");
            }
            
            fh.Dispose();

        }
        catch (Exception ex)
        {
            string message = ex.Message;

            throw ex;
        }

        log.InfoFormat("Connected: " + IsConnected);
        return IsConnected;
    }
McNets
  • 9,869
  • 3
  • 31
  • 54
  • https://stackoverflow.com/questions/1622903/how-do-i-check-if-a-printer-is-installed-and-ready-using-c/1622931#1622931 – McNets May 23 '22 at 07:57
  • What type of device are you trying to find info about? – Charlieface May 23 '22 at 08:37
  • Autonics Label Printer @Charlieface – Mario Luigi Vibal May 26 '22 at 05:23
  • Maybe check this one https://stackoverflow.com/questions/2136942/printing-in-parallel-port-dot-matrix-over-c-sharp Also your code is missing `using` for the variables `fh` and `lpt1`, and disposing it doesn't make it null, and also `throw ex;` will wipe the stack trace, use `throw;` instead. – Charlieface May 26 '22 at 08:23
  • hi @Charlieface thanks for your suggestion but the printing functionality on my code is working fine. I just need to know how to check if its connected. – Mario Luigi Vibal Jun 01 '22 at 08:01

0 Answers0