C#编程实现向并口设备发送指令、获取并口设备的状态
作者:junjie 时间:2023-02-02 02:56:39
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
namespace ParallelPort
{
public partial class Form1 : Form
{
const uint GENERIC_READ = 0x80000000;
const uint GENERIC_WRITE = 0x40000000;
const uint FILE_ATTRIBUTE_NORMAL = 0x80;
#region win32 API
[DllImport("kernel32.dll ")]
private static extern int CreateFile(
string lpFileName,
uint dwDesiredAccess,
int dwShareMode,
int lpSecurityAttributes,
int dwCreationDisposition,
uint dwFlagsAndAttributes,
int hTemplateFile
);
[DllImport("kernel32.dll ")]
private static extern bool WriteFile(
int hFile,
byte[] lpBuffer,
int nNumberOfBytesToWrite,
ref int lpNumberOfBytesWritten,
int lpOverlapped
);
[DllImport("kernel32.dll ")]
private static extern bool DefineDosDevice(
int dwFlags,
string lpDeviceName,
string lpTargetPath);
[DllImport("kernel32.dll ")]
private static extern bool CloseHandle(
int hObject
);
[DllImport("kernel32.dll ")]
private static extern bool ReadFile(
int hFile,
byte[] lpBuffer,
int nNumberOfBytesToRead,
ref int lpNumberOfBytesRead,
int lpOverlapped
);
#endregion
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int iHandle = -1;
try
{
int i = 0;
//创建实例
DefineDosDevice(0x00000001, "LptPortName",@"\Device\Parallel0");
iHandle = CreateFile(@"\\.\LptPortName",GENERIC_READ | GENERIC_WRITE, 0, 0, 3, FILE_ATTRIBUTE_NORMAL, 0);
if (iHandle !=-1)
{
byte[] mybyte = new byte[3]{ 0x12, 0x14, 0x14 };//要发送的命令(16进制)
WriteFile(iHandle, mybyte, mybyte.Length, ref i, 0);
byte[] mybyte1 = new byte[3];
string content = String.Empty;
int j = 0;
ReadFile(iHandle, mybyte1, 3, ref j, 0);
if (mybyte1 != null)
{
foreach(var tempByte in mybyte1)
{
content += tempByte.ToString();
}
}
MessageBox.Show(content);//获取的状态值
}
else
{
MessageBox.Show("创建文件失败!");
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (iHandle > 0)
{
CloseHandle(iHandle);
}
}
}
}
}
标签:C#,并口设备,发送指令
0
投稿
猜你喜欢
初识Spring Boot框架和快速入门
2022-10-17 00:58:52
C#动态加载dll扩展系统功能的方法
2022-08-08 23:23:15
C#针对xml基本操作及保存配置文件应用实例
2022-11-24 05:51:17
详解使用IntelliJ IDEA新建Java Web后端resfulAPI模板
2023-12-14 09:26:04
Android 自定义View实现多节点进度条功能
2022-05-04 17:13:37
Java实现的3des加密解密工具类示例
2023-08-21 14:00:01
C#中SQL参数传入空值报错解决方案
2023-12-14 14:28:59
SpringBoot2零基础到精通之数据与页面响应
2022-08-25 22:26:41
只需两步实现Eclipse+Maven快速构建第一个Spring Boot项目
2023-08-03 23:47:43
细谈java同步之JMM(Java Memory Model)
2023-11-23 13:09:33
C#多线程学习之(四)使用线程池进行多线程的自动管理
2021-07-17 10:04:43
SpringBoot AOP控制Redis自动缓存和更新的示例
2023-08-31 17:34:37
使用Spring Data JDBC实现DDD聚合的示例代码
2022-05-04 05:11:23
java 文件流的处理方式 文件打包成zip
2022-07-08 12:43:03
java简单模仿win10计算器
2023-06-25 21:57:20
深入理解Spring Boot的日志管理
2021-11-16 09:58:40
你知道jdk竟有4个random吗
2022-06-14 23:37:08
Spring Boot统一异常处理最佳实践(拓展篇)
2023-10-29 16:00:04
android异步消息机制 从源码层面解析(2)
2023-08-06 15:55:39
java模拟实现银行ATM机操作
2021-09-03 04:28:11