且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C#后台调用LPT1端口实现小票机打印方法。

更新时间:2021-09-27 17:04:59

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
public 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()
        {
         
        }
        public POSPrinter(string prnPort)
        {
            this.prnPort = prnPort;//打印机端口
        }
        public string PrintLine(string str)
        {
            IntPtr iHandle = CreateFile(prnPort, 0x50000000, 0, 0, OPEN_EXISTING, 0, 0);
            if (iHandle.ToInt32() == -1)
            {
                Console.WriteLine(iHandle.ToString());
                return "没有连接打印机或者打印机端口不是LPT1";
            }
            else
            {
                Console.WriteLine(iHandle.ToString());
                FileStream fs = new FileStream(iHandle, FileAccess.ReadWrite);
                StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.Default);
                sw.WriteLine("           小票单");
                sw.WriteLine();
                sw.WriteLine(str);
                sw.WriteLine("打印内容");
                sw.WriteLine("---------------------------");
 
                sw.Close();
                fs.Close();
                return "打印成功!";
            }
        }
    }

  直接调用PrintLine();方法进行打印具体需要的参数和打印格式大家自行调整

 

 

本文转自左正博客园博客,原文链接:http://www.cnblogs.com/soundcode/p/8044651.html,如需转载请自行联系原作者