Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
?
Solved

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

Posted on 2011-03-09
3
Medium Priority
?
4,204 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:
Rahul Agarwal earned 2000 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

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

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

A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
In an interesting question (https://www.experts-exchange.com/questions/29008360/) here at Experts Exchange, a member asked how to split a single image into multiple images. The primary usage for this is to place many photographs on a flatbed scanner…
Please read the paragraph below before following the instructions in the video — there are important caveats in the paragraph that I did not mention in the video. If your PaperPort 12 or PaperPort 14 is failing to start, or crashing, or hanging, …
Suggested Courses

564 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