C#使用USB介面進行Barcode Printer(讀取非C#的TSCLib.dll方法)
阿新 • • 發佈:2020-09-11
前言
就在上一篇部落格有寫如何使用C#系統方法進行串列埠通訊,但是否能進行USB控制印表機尚未測試,但原本就有一種方式去控制USB連線的印表機,而且以這種方式並不是輸入指令,可能更容易被理解。
其中還有一個很重要的知識點,就是如何在C#中引用非C#的DLL檔案,這才是本文的精華。
一、引用非C#的DLL檔案
直接在References中引用DLL的方法對於非C#的DLL檔案是不可行的,反而會出現以下問題。
1、導包
using System.Runtime.InteropServices;
2、如何使用
需要將DLL放在Bin路徑下,在bin路徑下如果再包一個資料夾也是可以的(如Resources/……),但指明的位置要準確,DLL檔名不區分大小寫,此DLL可在網上搜尋下載。
public class TSCLibDLL { [DllImport("Resources/TSCLIB.dll", EntryPoint = "about")] public static extern int about(); [DllImport("Resources/TSCLIB.dll", EntryPoint = "openport")] public static extern int openport(string printername); [DllImport("Resources/TSCLIB.dll", EntryPoint = "barcode")] public static extern int barcode(string x, string y, string type,string height, string readable, string rotation,string narrow, string wide, string code); [DllImport("Resources/TSCLIB.dll", EntryPoint = "clearbuffer")] public static extern intclearbuffer(); [DllImport("Resources/TSCLIB.dll", EntryPoint = "closeport")] public static extern int closeport(); [DllImport("Resources/TSCLIB.dll", EntryPoint = "downloadpcx")] public static extern int downloadpcx(string filename, string image_name); [DllImport("Resources/TSCLIB.dll", EntryPoint = "formfeed")] public static extern int formfeed(); [DllImport("Resources/TSCLIB.dll", EntryPoint = "nobackfeed")] public static extern int nobackfeed(); [DllImport("Resources/TSCLIB.dll", EntryPoint = "printerfont")] public static extern int printerfont(string x, string y, string fonttype, string rotation, string xmul, string ymul,string text); [DllImport("Resources/TSCLIB.dll", EntryPoint = "printlabel")] public static extern int printlabel(string set, string copy); [DllImport("Resources/TSCLIB.dll", EntryPoint = "sendcommand")] public static extern int sendcommand(string printercommand); [DllImport("Resources/TSCLIB.dll", EntryPoint = "setup")] public static extern int setup(string width, string height,string speed, string density,string sensor, string vertical,string offset); [DllImport("Resources/TSCLIB.dll", EntryPoint = "windowsfont")] public static extern int windowsfont(int x, int y, int fontheight, int rotation, int fontstyle, int fontunderline,string szFaceName, string content); }
二、使用USB介面控制印表機
前面一部分將DLL中的方法宣告,後面正常呼叫即可
private void usbPrint() { var res = TSCLibDLL.openport("USB"); if (res == 0) return;//介面未開啟 TSCLibDLL.setup("30", "14.4", "2", "10", "0", "3.2", "0");//設定長寬等要素,可自行實驗 TSCLibDLL.clearbuffer();//Clear image buffer TSCLibDLL.windowsfont(40, 5, 25, 0, 2, 0, "Arial", "Printer Header");//first row TSCLibDLL.barcode("30", "35", "EAN13", "60", "1", "0", "3", "6", "Barcode12345"); //Drawing barcode TSCLibDLL.windowsfont(30, 130, 20, 0, 2, 0, "Arial", "Printer Footer"); //third row TSCLibDLL.printlabel("1", "1"); TSCLibDLL.closeport(); //Close specified printer driver }