无法连接到虚拟串行端口

时间:2016-02-26 19:18:10

标签: c# bluetooth serial-port windows-mobile-6.5

我正在编写一个在Windows CE 6上运行的.NET应用程序,用于创建蓝牙串行端口。对RegisterDevice()的调用成功返回,SerialPort.GetPortNames()表示存在COM端口。但是,当我尝试使用.NET的SerialPort类打开COM端口时,它会抛出IOException,说明该端口不存在。如果我尝试使用CreateFile打开它,则调用失败,并且GetLastError返回错误6(INVALID_HANDLE)。但是,如果我在HKLM \ Software \ Microsoft \ Bluetooth \ Serial下创建一个注册表项并重新启动设备以允许Microsoft蓝牙堆栈初始化端口,我可以毫无问题地连接到串行端口。如果可能的话,我想避免让用户重启设备。

我创建虚拟串口的代码:

static public IntPtr RegisterVirtualComPort(int index, long address, Guid service)
{
   PORTEMUPortParams portParams = new PORTEMUPortParams();
   portParams.uiportflags = RFCOMM_PORT_FLAGS.REMOTE_DCB;
   portParams.flocal = false;
   portParams.device = address;
   portParams.uuidService = service;
   IntPtr handle = RegisterDevice("COM", index, "btd.dll", ref portParams);
   return handle;
}

我尝试通过P / Invoke测试COM端口:

static public bool TestComPort(int index)
{
   string portName = string.Format("COM{0}:", index.ToString());
   IntPtr handle = CreateFile(portName, DESIRED_ACCESS.GENERIC_READ | DESIRED_ACCESS.GENERIC_WRITE, FILE_SHARE.FILE_SHARE_NONE, IntPtr.Zero, CREATION_DISPOSITION.OPEN_EXISTING, 0, IntPtr.Zero);
   bool success = handle.ToInt32() != -1;
   CloseHandle(handle);
   if (!success)
   {
      int errorCode = Marshal.GetLastWin32Error();
      App.Logger.DebugFormat("TestComPort failed for \'{0}\', return error code {1}.", portName, errorCode);
   }
   return success;
}

任何帮助都会受到赞赏。

0 个答案:

没有答案
相关问题