Solved

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

Posted on 2011-03-09
3
3,771 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
Comment Utility
0
 
LVL 23

Expert Comment

by:wdosanjos
Comment Utility
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
Comment Utility
HI, agarwalrahul

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

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

In my previous article (http://www.experts-exchange.com/Programming/Languages/.NET/.NET_Framework_3.x/A_4362-Serialization-in-NET-1.html) we saw the basics of serialization and how types/objects can be serialized to Binary format. In this blog we wi…
This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
It is a freely distributed piece of software for such tasks as photo retouching, image composition and image authoring. It works on many operating systems, in many languages.
This video explains how to create simple products associated to Magento configurable product and offers fast way of their generation with Store Manager for Magento tool.

763 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

10 Experts available now in Live!

Get 1:1 Help Now