C#编程实现向并口设备发送指令、获取并口设备的状态
程序员文章站
2023-11-27 12:46:58
using system;
using system.diagnostics;
using system.runtime.interopservices;
u...
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); } } } } }