Solved

using C#.net to communicate thermal printer through LPT port does not work

Posted on 2011-03-09
3
3,807 Views
Last Modified: 2013-12-17
Hi,  experts

I'm trying to write a program to communicate to a EPSON thermal printer (EPSON TM-T88V MODEL M244A) through LPT port.

It involves kernel32.dll and inpout.dll. the kernel32.dll is already in C:\WINDOWS\system32. I download the inpout32.dll and put it in the same folder with my compiled .exe file.

When the program got to calling writeFile function of the kernel32.dll, it stuck. The program had no response and the call stack crashed.

The Completed code is attached

the program stuck at the statement in the method Print (public void Print(string str, string align))

               WriteFile(TicketPrinterHandle, str.ToCharArray(), StrLen(str), out count, IntPtr.Zero);

Is there anyone can help me to fix the problem out or give me any idea?

Thx



using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Windows.Forms;
using Microsoft.Win32.SafeHandles;
using System.Runtime.InteropServices;
using System.ComponentModel;

namespace WindowsFormsApplication1
{
    public class TicketPrinter
    {
        public const short FILE_ATTRIBUTE_NORMAL = 0x80;
        public const short INVALID_HANDLE_VALUE = -1;
        public const uint GENERIC_READ = 0x80000000;
        public const uint GENERIC_WRITE = 0x40000000;
        public const uint CREATE_NEW = 1;
        public const uint CREATE_ALWAYS = 2;
        public const uint OPEN_EXISTING = 3;

        [StructLayout(LayoutKind.Sequential)]
      private struct OVERLAPPED
      {
          int Internal;
          int InternalHigh;
          int Offset;
          int OffSetHigh;
          int hEvent;
      }

        [DllImport("inpout32.dll", EntryPoint = "Out32")]
        private static extern void Output(int adress, int value);

        [DllImport("inpout32.dll", EntryPoint = "Inp32")]
        private static extern int Input(int adress);  


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

        [DllImport("kernel32.dll", SetLastError = true)]
        private static extern bool WriteFile(
         SafeFileHandle hFile,                  // handle to file
         char[] lpBuffer,                       // data buffer
         int nNumberOfBytesToWrite,             // number of bytes to write
         out int lpNumberOfBytesWritten,        // number of bytes written
         IntPtr lpOverlapped          // overlapped buffer
         );

        [DllImport("kernel32.dll", SetLastError = true)]
        private static extern bool CloseHandle(
         SafeFileHandle hObject   // handle to object
         );


        private string _PPort = "";
        public string Status = "Detecting...";

        public TicketPrinter()
        {

        }

        public void Create( string LPTName )
        {
            _PPort = "";
            TicketPrinterHandle = CreateFile(LPTName, GENERIC_WRITE, 0, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero);
            if (TicketPrinterHandle.IsInvalid)
            {
                MessageBox.Show("The port of printer cannot open!");
                return;
            }
            _PPort = LPTName;
        }

        public void Close()
        {
            if (TicketPrinterHandle == null)
                return;
            if (TicketPrinterHandle.IsInvalid)
                return;
            CloseHandle(TicketPrinterHandle);
        }

        public void Print(string str)
        {
            Print(str, "left");
        }

        public void Print(string str, string align)
        {
            if (TicketPrinterHandle == null)
                return;
            if (TicketPrinterHandle.IsInvalid)
                return;
            int PadCount = 30;
            PadCount -= StrLen( str );
            if (align == "center")
                str = str.PadLeft(PadCount / 2 + str.Length, ' ');
            else if (align == "right")
                str = str.PadLeft(PadCount, ' ');

            //////////////////////////////////////////////////////////
            //  7     6      5      4       3       2       1       0
            // Busy  nAck Paper-Out Select nError   x       x       x
            //////////////////////////////////////////////////////////
            //check Parallel port Status registers 
            int RetryCount = 10;
            Retry:
            int sta = 0;
            if (_PPort == "LPT1")
                sta = Input(0x379);
            else if (_PPort == "LPT2")
                sta = Input(0x279);

            if( sta == 0x7F )
            {
                Status = "Not Connected";
                return;
            }
            if ((sta & 0x10) == 0)
            {
                Status = "No Power";
                return;
            }
            if ((sta & 0x80) == 0)      //Busy
            {
                Status = "Printer Busy";
                RetryCount--;
                if (RetryCount <= 0)
                    return;
                goto Retry;
            }
            if ((sta & 0x20) != 0)      //Paper-Out
            {
                Status = "Paper Out";
                return;
            }

            ////////////////////////////////////////
            int count = 0;
            WriteFile(TicketPrinterHandle, str.ToCharArray(), StrLen(str), out count, IntPtr.Zero);
            Close();
            Status = "Ready";
        }

        public void PrintLn(string str)
        {
            Print(str, "left");
            Print("\r\n", "left");
        }

        public void PrintLn(string str,string align)
        {
            Print(str, align);
            Print("\r\n","left");
        }

        private int StrLen(string str)
        {
            return System.Text.Encoding.Default.GetByteCount(str);
        }
    }
}

Open in new window

0
Comment
Question by:william_gao
3 Comments
 
LVL 13

Accepted Solution

by:
agarwalrahul earned 500 total points
ID: 35090612
0
 
LVL 23

Expert Comment

by:wdosanjos
ID: 35090887
Does the printer work with ANSI or UNICODE chars?

If it's ANSI, I think your definition of WriteFile is not correct, and you need to specify that you are using ANSI chars.

        [DllImport("kernel32.dll", SetLastError = true)]
        private static extern bool WriteFile(
         SafeFileHandle hFile,                  // handle to file
         [MarshalAs(UnmanagedType.LPStr)] char[] lpBuffer,                       // data buffer
         int nNumberOfBytesToWrite,             // number of bytes to write
         out int lpNumberOfBytesWritten,        // number of bytes written
         IntPtr lpOverlapped          // overlapped buffer
         );

Open in new window


BTW, an alternative way to work with serial ports is through the SerialPort class:
http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.aspx
0
 

Author Closing Comment

by:william_gao
ID: 35093411
HI, agarwalrahul

Your answer is very helpful to me. I finally solved the problem by taking your advise. Thanks so much.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Error when loading the database 16 57
how to read json value 2 31
How to add <appSettings> to the webconfig file 2 21
What namespace do I need to import? 2 13
This document covers how to connect to SQL Server and browse its contents.  It is meant for those new to Visual Studio and/or working with Microsoft SQL Server.  It is not a guide to building SQL Server database connections in your code.  This is mo…
This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
Migrating to Microsoft Office 365 is becoming increasingly popular for organizations both large and small. If you have made the leap to Microsoft’s cloud platform, you know that you will need to create a corporate email signature for your Office 365…
Internet Business Fax to Email Made Easy - With  eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, f…

867 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now