C # Call the Win32API series list listed in the COM port

zhaozj2021-02-17  56

C # By calling Win32API to achieve a very powerful function, this article will focus on how to enumerate by calling Win32API

All COM ports. First we look at the definition BOOL EnumPorts EnumPorts function (LPTSTR pName, // server name DWORD Level, // information level LPBYTE pPorts, // port information buffer DWORD cbBuf, // size of port information buffer LPDWORD pcbNeeded, // bytes received Or Required LPDWORD PCRETURNED / / NUMBER OF PORTS Received; This API Return Information is placed in the buffer referred to in PPorts, which is an array of struct port_info_1 {string pname;}. According to the Level parameters, this structure array is somewhat different. C # To call the API first to introduce a dynamic library, Enumports is in the dynamic library of Winspool.drv. The introduction statement is as follows [DLLIMPORT ("Winspool.drv", Charset = Charset.auto)] Then define the port_info_1 structure Struct port_info_1 {[Marshalas (unmanagedtype.lptstr)] public string pname;} Ok, all source code is as follows: useing System; using System.Collections; using System.Runtime.InteropServices; using System.Diagnostics; namespace rooksoft.Demo {public class EnumPortDemo {[StructLayout (LayoutKind.Sequential, CharSet = CharSet.Auto)] struct PORT_INFO_1 {[MarshalAs (UnmanagedType. LPTStr)] public string pName;} [DllImport ( "winspool.drv", CharSet = CharSet.Auto)] static extern bool EnumPorts (string pName, int level, IntPtr bufptr, int cbBuf, out int pcbNeeded, out int pcReturned);

public EnumPortDemo () {} public void ListPorts () // out ArrayList portslist {int pcReturned = 0; int pcbNeeded = 0; IntPtr outb = IntPtr.Zero; EnumPorts (null, 1, outb, 0, out pcbNeeded, out pcReturned) Outb = Marshal.allochglobal (PCBNEEDED 1); Enumports (NULL, 1, OUTB, PCBNEDED, OUT PCBNEED, OUT PCRETURNED); Port_INFO_1 [] PortsArray = new port_info_1 [pcreturned];

INTPTR CURRENT = OUTB; For (int i = 0; i

((int) Current Marshal.Sizeof (TypeOf (port_info_1)))))); console.writeline (portsarray [i] .pname);} Marshal.Freehglobal (OUTB); // Return MAIN ()} public static void main ()} ENUMPORTDEMO DEMO = New EnumportDemo (); demo.listports ();}

}} Contact the author zlyperson@163.net

转载请注明原文地址:https://www.9cbs.com/read-29352.html

New Post(0)