C#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 "";
??????????? }
??????? }
??? }??
}
總結
以上是生活随笔為你收集整理的C#LPT指令打印条码——代码嵌套指令的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: VSAN配置手册
- 下一篇: 群晖NAS教程(十)、利用Docker安