我正在使用PInvoke的其他人编写的Serial Wrapper(我对此不太了解)
串行包装器在Silverlight Web App中用于通过串行com端口访问USB设备
这个应用程序已经工作了很长时间,但奇怪的是我们无法让应用程序工作,并且在调用以下“CreateFile”方法时,Serial Wrapper无法打开COM端口:
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
static extern IntPtr CreateFile(string fileName,
[MarshalAs(UnmanagedType.U4)] FileAccess fileAccess,
[MarshalAs(UnmanagedType.U4)] FileShare fileShare,
IntPtr securityAttributes,
[MarshalAs(UnmanagedType.U4)] FileMode creationDisposition,
int flags,
IntPtr template);
这些是我发送给此方法的参数:
CreateFile(COM12, FileAccess.ReadWrite, FileShare.None, IntPtr.Zero, FileMode.Open, 0, IntPtr.Zero)
这似乎将IntPtr作为-1返回,而不是比IntPtr.Zero更大的东西,但正如我所说的只发生在很少的PC上,到目前为止,我能找到的唯一的patern似乎是HP机器Windows 7 64位SP1
在Hans的建议中添加了以下代码:
Log lg = new Log();
lg.write("Opening Serial Port - CreateFile(this.PortName, FileAccess.ReadWrite, FileShare.None, IntPtr.Zero, FileMode.Open, 0, IntPtr.Zero)");
lg.write("PARAMETERS - CreateFile(" + this.sPortName.ToString()+ ", FileAccess.ReadWrite, FileShare.None, IntPtr.Zero, FileMode.Open, 0, IntPtr.Zero)");
pHandle = CreateFile(this.sPortName, FileAccess.ReadWrite, FileShare.None,
IntPtr.Zero, FileMode.Open, 0, IntPtr.Zero);
if (pHandle == IntPtr.Zero || pHandle == new IntPtr(-1))
{
int ErrorCode = Marshal.GetLastWin32Error();
if (pHandle == IntPtr.Zero)
{
lg.write("Open Serial Port Failed: CreateFile (pHandle == IntPtr.Zero)");
lg.write("LastWin32Error = " + ErrorCode.ToString());
}
else
{
lg.write("Open Serial Port Failed: CreateFile (pHandle == IntPtr(-1))");
lg.write("LastWin32Error = " + ErrorCode.ToString());
}
return false;
}
else
{
lg.write("Open Serial Port Success");
}