zoukankan      html  css  js  c++  java
  • 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

     

  • 相关阅读:
    Js将字符串转换成对象或数组en
    iview渲染函数
    iview中render函数监听事件
    Arduino Nano 读取ADS1100实例
    Raspberry Pi 3 安装 Lazarus 1.6.2(2017-02-09更新)
    Lazarus for Raspbian安装
    Delphi xe7 FireMonkey / Mobile (Android, iOS)生成 QR Code完整实例
    Delphi xe7 up1 调用android振动功能
    Delphi xe7 android实现透明度可以调整的对话框
    delphi XE7 在Android编译SharedActivity时出错
  • 原文地址:https://www.cnblogs.com/kk1230/p/1610728.html
Copyright © 2011-2022 走看看