C#通过调用WIN32API可以实现非常强大的功能,本文将着重讲述如何通过调用WIN32API实现列举
所有COM端口。
首先我们看看EnumPorts函数的定义
BOOL EnumPorts(
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
);
这个api返回信息放在pPorts所指的缓冲区中,是一个
struct PORT_INFO_1
{
string pName;
}
的结构数组。根据Level参数不同,这个结构数组有些不同。
C#要调用API首先要引入动态库,EnumPorts在winspool.drv这个动态库中。引入语句如下
[DllImport("winspool.drv", CharSet=CharSet.Auto)]
然后是定义PORT_INFO_1结构
struct PORT_INFO_1
{
[MarshalAs(UnmanagedType.LPTStr)]
public string pName;
}
好了,全部的源代码如下:
using 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, pcbNeeded, out pcbNeeded, out pcReturned);
PORT_INFO_1[] portsArray = new PORT_INFO_1[pcReturned]; 软件开发网
IntPtr current = outb;
for (int i=0; i<pcReturned; i )
{
portsArray[i] = (PORT_INFO_1)
Marshal.PtrToStructure(current,
typeof(PORT_INFO_1));
current=(IntPtr)
((int)current Marshal.SizeOf(typeof(PORT_INFO_1)));
Console.WriteLine(portsArray[i].pName);
}
Marshal.FreeHGlobal(outb);
//return manyArr;
}
public static void Main() {
EnumPortDemo demo = new EnumPortDemo();
demo.ListPorts();
}
}
}