2011年8月7日 星期日

LPT指令打印条码——代码嵌套指令

參考來源
---
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 "";
}
}
}
}

沒有留言:

張貼留言