改变自己
我可以改变世界 改变自己

  条码打印一般是通过指令或图片方式来打印,图片方式有fastreport

,不过本人未曾找到VS调用它的方式,仅在Delphi 7中成功的使用。而

实际上大多数的条码打印机制造商都有一套他们自己的打印指令语言,

通过该语言,可以无需驱动,直接打印,并且操作也很简单,只需要将

指令送入打印机中就好。

  VS中存在Com口操作的控件,却未有现成的LPT端口控件,而相对COM

口来说,LPT的速度要快,所以在打印的时候客户一般选择LPT通讯方式

,经过网上的一些查阅,终于实现了LPT口的打印,打印机为Zebra,写

出来与大家分享。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace PrintDemo
{
    public partial class Form1 : Form
    {  
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            tbBarCode.Focus();
        }

        private void tbBarCode_KeyDown(object sender,

KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.Enter:
                    PrintBarcode(tbBarCode.Text.Trim());
                    tbBarCode.Text = "";
                    tbBarCode.Focus();
                    break;
                default:
                    break;
            }
        }
        private void PrintBarcode(string Barcode)
        {
            Barcode = "^XA^FO48,12^BY4^BCN,152,N,N^FD>;" +

Barcode.Trim() + "^FS^FT62,220^CI0^ABN,44,28^FD" +

Barcode.Trim() + "^FS^PQ1,0,1,Y^XZ";
            PrintDemo.POSPrinter prn = new

PrintDemo.POSPrinter("LPT1");
            string strmsg = prn.PrintLine(Barcode);
            if (strmsg != "")
            {
                MessageBox.Show(strmsg);
            }
        }
    }
}
 

其中类POSPrinter定义如下

namespace PrintDemo
{
    class POSPrinter
    {
        const int OPEN_EXISTING = 3;
        string prnPort = "LPT1";
        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        private static extern IntPtr CreateFile(string

lpFileName,
        int dwDesiredAccess,
        int dwShareMode,
        int lpSecurityAttributes,
        int dwCreationDisposition,
        int dwFlagsAndAttributes,
        int hTemplateFile);

        public POSPrinter()
        {
            //   
            //   TODO:   在此处添加构造函数逻辑   
            //   
        }

        public POSPrinter(string prnPort)
        {
            this.prnPort = prnPort;//打印机端口   
        }

        public string PrintLine(string str)
        {

            IntPtr iHandle = CreateFile(prnPort, 0x40000000,

0, 0, OPEN_EXISTING, 0, 0);
            if (iHandle.ToInt32() == -1)
            {
                return "LPT1 Port Open Failed";
            }
            else
            {

                FileStream fs = new FileStream(iHandle,

FileAccess.ReadWrite);
                StreamWriter sw = new StreamWriter(fs,

System.Text.Encoding.Default);   //写数据   
                sw.WriteLine(str);
                sw.Close();
                fs.Close();
                return "";
            }
        }
    }  
}

posted on 2009-05-31 10:27  dashan  阅读(1247)  评论(0编辑  收藏  举报