C# 操作并口类,并口通信
生活随笔
收集整理的這篇文章主要介紹了
C# 操作并口类,并口通信
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
c#已提供了串口通信組件SerialPort,但是C#并沒有提供直接的并口通信組件,只好通過調用API來與并口通信
?
代碼 1 using System;2 ?using System.Runtime.InteropServices;
3 ?namespace LptPrint_test
4 {
5 /// <summary>
6 /// LPTControl 的摘要說明。
7 /// </summary>
8 ? public class LPTControl
9 {
10 private string LptStr = "lpt1";
11 public LPTControl(string l_LPT_Str)
12 {
13 //
14 // TODO: 在此處添加構造函數邏輯
15 //
16 LptStr = l_LPT_Str;
17 }
18 [StructLayout(LayoutKind.Sequential)]
19 private struct OVERLAPPED
20 {
21 int Internal;
22 int InternalHigh;
23 int Offset;
24 int OffSetHigh;
25 int hEvent;
26 }
27 [DllImport("kernel32.dll")]
28 private static extern int CreateFile(string lpFileName, uint dwDesiredAccess, int dwShareMode, int lpSecurityAttributes, int dwCreationDisposition, int dwFlagsAndAttributes, int hTemplateFile);
29 [DllImport("kernel32.dll")]
30 private static extern bool WriteFile(int hFile, byte[] lpBuffer, int nNumberOfBytesToWrite, ref int lpNumberOfBytesWritten, ref OVERLAPPED lpOverlapped);
31 [DllImport("kernel32.dll")]
32 private static extern bool CloseHandle(int hObject);
33 private int iHandle;
34 public bool Open()
35 {
36 iHandle = CreateFile(LptStr, 0x40000000, 0, 0, 3, 0, 0);
37 if (iHandle != - 1)
38 {
39 return true;
40 }
41 else
42 {
43 return false;
44 }
45 }
46 public bool Write(String Mystring)
47 {
48 if (iHandle != - 1)
49 {
50 OVERLAPPED x = new OVERLAPPED();
51 int i = 0;
52 byte[] mybyte = System.Text.Encoding.Default.GetBytes(Mystring);
53 bool b = WriteFile(iHandle, mybyte, mybyte.Length, ref i, ref x);
54 return b;
55 }
56 else
57 {
58 throw new Exception("不能連接到打印機!");
59 }
60 }
61 public bool Write(byte[] mybyte)
62 {
63 if (iHandle != - 1)
64 {
65 OVERLAPPED x = new OVERLAPPED();
66 int i = 0;
67 WriteFile(iHandle, mybyte, mybyte.Length, ref i, ref x);
68 return true;
69 }
70 else
71 {
72 throw new Exception("不能連接到打印機!");
73 }
74 }
75 public bool Close()
76 {
77 return CloseHandle(iHandle);
78 }
79 }
80 }
81
82
?
?
?
轉載于:https://www.cnblogs.com/kk1230/archive/2009/11/25/1610728.html
總結
以上是生活随笔為你收集整理的C# 操作并口类,并口通信的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 在save中重写 AdminModel
- 下一篇: .NET代码混淆学习和解决视频批量转换中