C#打印條碼操作的實例淺析
C#打印條碼一般是通過圖片方式或指令方式來打印,圖片形式主要有fastreport。這里我們使用LPT端口控件來實現(xiàn),而實際上絕大多數的條碼打印機廠商都有一套他們自己的打印指令語言,通過這種語言,可以不需要驅動,支持直接打印,并且操作簡單,僅僅將指令送入打印機中就好。
VS中存在Com口操作的控件,卻未有現(xiàn)成的LPT端口控件,而相對COM口來說,LPT的速度要快,所以在打印的時候客戶一般選擇LPT通訊方式,經過網上的一些查閱,終于實現(xiàn)了LPT口的打印,打印機為Zebra,寫出來與大家分享。
C#打印條碼操作的實例:
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Text;
- using System.Windows.Forms;
- //C#打印條碼操作的實例
- namespace PrintDemo
- {
- public partial class Form1 : Form
- {
- public Form1()
- {
- InitializeComponent();
- }
- private void Form1_Load(object sender, EventArgs e)
- {
- tbBarCode.Focus();
- }
- //C#打印條碼操作的實例
- 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>;" +
- //C#打印條碼操作的實例
- 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);
- }
- }
- }
- }
C#打印條碼操作之類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);//C#打印條碼操作之寫數據
- sw.WriteLine(str);
- sw.Close();
- fs.Close();
- return "";
- }
- }
- }
- }
C#打印條碼操作的實例淺析就向你介紹到這里,希望對你了解和學習C#打印條碼操作有所了解。
【編輯推薦】