C#操作并口类,并口通信
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
C#操作并⼝类,并⼝通信
c#已提供了串⼝通信组件SerialPort,但是C#并没有提供直接的并⼝通信组件,只好通过调⽤API来与并⼝通信
代码
1using System;
2using System.Runtime.InteropServices;
3namespace LptPrint_test
4 {
5///<summary>
6/// LPTControl 的摘要说明。
7///</summary>
8public class LPTControl
9 {
10private string LptStr = "lpt1";
11public LPTControl(string l_LPT_Str)
12 {
13//
14 // TODO: 在此处添加构造函数逻辑
15 //
16 LptStr = l_LPT_Str;
17 }
18 [StructLayout(LayoutKind.Sequential)]
19private struct OVERLAPPED
20 {
21int Internal;
22int InternalHigh;
23int Offset;
24int OffSetHigh;
25int hEvent;
26 }
27 [DllImport("kernel32.dll")]
28private static extern int CreateFile(string lpFileName, uint dwDesiredAccess, int dwShareMode, int lpSecurityAttributes, int dwCreationDisposition, int dwFlagsAndAttributes, int hTemplateFile);
29 [DllImport("kernel32.dll")]
30private static extern bool WriteFile(int hFile, byte[] lpBuffer, int nNumberOfBytesToWrite, ref int lpNumberOfBytesWritten, ref OVERLAPPED lpOverlapped);
31 [DllImport("kernel32.dll")]
32private static extern bool CloseHandle(int hObject);
33private int iHandle;
34public bool Open()
35 {
36 iHandle = CreateFile(LptStr, 0x40000000, 0, 0, 3, 0, 0);
37if (iHandle != - 1)
38 {
39return true;
40 }
41else
42 {
43return false;
44 }
45 }
46public bool Write(String Mystring)
47 {
48if (iHandle != - 1)
49 {
50 OVERLAPPED x = new OVERLAPPED();
51int i = 0;
52byte[] mybyte = System.Text.Encoding.Default.GetBytes(Mystring);
53bool b = WriteFile(iHandle, mybyte, mybyte.Length, ref i, ref x);
54return b;
55 }
56else
57 {
58throw new Exception("不能连接到打印机!");
59 }
60 }
61public bool Write(byte[] mybyte)
62 {
63if (iHandle != - 1)
64 {
65 OVERLAPPED x = new OVERLAPPED();
66int i = 0;
67 WriteFile(iHandle, mybyte, mybyte.Length, ref i, ref x);
68return true;
69 }
70else
71 {
72throw new Exception("不能连接到打印机!");
73 }
74 }
75public bool Close()
76 {
77return CloseHandle(iHandle);
78 }
79 }
80 }
81
82。