Windows Mobile 打开串口失败

meic1985 2012-02-07 03:06:54
菜鸟提问:windows mobile6.1 打开串口的时候失败,用GetLastError看了一下返回值是6,百度到6对应的错误是:无效句柄。
有没有高手知道怎么回事。
代码如下:

调用:
CommPort cp = new CommPort();
cp.Open();


/// <summary>
/// 这是一个关于调用串口的类
/// </summary>
public class CommPort
{

public int PortNum = 1;
public int BaudRate = 9600;
public byte ByteSize = 8;
public byte Parity = 0; // 0-4=no,odd,even,mark,space
public byte StopBits = 0; // 0,1,2 = 1, 1.5, 2
public int ReadTimeout = 0;

//comm port win32 file handle
private int hComm = -1;

public bool Opened = false;

//win32 api constants
private const uint GENERIC_READ = 0x80000000;
private const uint GENERIC_WRITE = 0x40000000;
private const int OPEN_EXISTING = 3;
private const int INVALID_HANDLE_VALUE = -1;

[StructLayout(LayoutKind.Sequential)]
public struct DCB
{
//taken from c struct in platform sdk
public int DCBlength; // sizeof(DCB)
public int BaudRate; // current baud rate
/* these are the c struct bit fields, bit twiddle flag to set
public int fBinary; // binary mode, no EOF check
public int fParity; // enable parity checking
public int fOutxCtsFlow; // CTS output flow control
public int fOutxDsrFlow; // DSR output flow control
public int fDtrControl; // DTR flow control type
public int fDsrSensitivity; // DSR sensitivity
public int fTXContinueOnXoff; // XOFF continues Tx
public int fOutX; // XON/XOFF out flow control
public int fInX; // XON/XOFF in flow control
public int fErrorChar; // enable error replacement
public int fNull; // enable null stripping
public int fRtsControl; // RTS flow control
public int fAbortOnError; // abort on error
public int fDummy2; // reserved
*/
public uint flags;
public ushort wReserved; // not currently used
public ushort XonLim; // transmit XON threshold
public ushort XoffLim; // transmit XOFF threshold
public byte ByteSize; // number of bits/byte, 4-8
public byte Parity; // 0-4=no,odd,even,mark,space
public byte StopBits; // 0,1,2 = 1, 1.5, 2
public char XonChar; // Tx and Rx XON character
public char XoffChar; // Tx and Rx XOFF character
public char ErrorChar; // error replacement character
public char EofChar; // end of input character
public char EvtChar; // received event character
public ushort wReserved1; // reserved; do not use
}

[StructLayout(LayoutKind.Sequential)]
private struct COMMTIMEOUTS
{
public int ReadIntervalTimeout;
public int ReadTotalTimeoutMultiplier;
public int ReadTotalTimeoutConstant;
public int WriteTotalTimeoutMultiplier;
public int WriteTotalTimeoutConstant;
}

[StructLayout(LayoutKind.Sequential)]
private struct OVERLAPPED
{
public int Internal;
public int InternalHigh;
public int Offset;
public int OffsetHigh;
public int hEvent;
}

[DllImport("kernel32.dll ")]
private static extern int CreateFile(
string lpFileName, // file name
uint dwDesiredAccess, // access mode
int dwShareMode, // share mode
int lpSecurityAttributes, // SD
int dwCreationDisposition, // how to create
int dwFlagsAndAttributes, // file attributes
int hTemplateFile // handle to template file
);

[DllImport("kernel32.dll ")]
private static extern bool GetCommState(
int hFile, // handle to communications device
ref DCB lpDCB // device-control block
);

[DllImport("kernel32.dll ")]
private static extern bool BuildCommDCB(
string lpDef, // device-control string
ref DCB lpDCB // device-control block
);

[DllImport("kernel32.dll ")]
private static extern bool SetCommState(
int hFile, // handle to communications device
ref DCB lpDCB // device-control block
);

[DllImport("kernel32.dll ")]
private static extern bool GetCommTimeouts(
int hFile, // handle to comm device
ref COMMTIMEOUTS lpCommTimeouts // time-out values
);

[DllImport("kernel32.dll ")]
private static extern bool SetCommTimeouts(
int hFile, // handle to comm device
ref COMMTIMEOUTS lpCommTimeouts // time-out values
);

[DllImport("kernel32.dll ")]
private static extern bool ReadFile(
int hFile, // handle to file
byte[] lpBuffer, // data buffer
int nNumberOfBytesToRead, // number of bytes to read
ref int lpNumberOfBytesRead, // number of bytes read
ref OVERLAPPED lpOverlapped // overlapped buffer
);

[DllImport("kernel32.dll ")]
private static extern bool WriteFile(
int hFile, // handle to file
byte[] lpBuffer, // data buffer
int nNumberOfBytesToWrite, // number of bytes to write
ref int lpNumberOfBytesWritten, // number of bytes written
ref OVERLAPPED lpOverlapped // overlapped buffer
);

[DllImport("kernel32.dll ")]
private static extern bool CloseHandle(
int hObject // handle to object
);

[DllImport("kernel32.dll ")]
private static extern uint GetLastError();

...全文
171 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
AndyZhang 2012-02-13
  • 打赏
  • 举报
回复
一、 首先保证你的代码没有逻辑错误,比如函数调用是不是穿得参数都对(最大可能的原因,比如C++, COM1: 你少写了冒号等等之类的。。。)

二、这个串口是不是在其他地方已经被打开了,如果打开了,没有关,那么这里你肯定是打不开的(很可能是这里的问题)

三、串口驱动是否加载上,看一下注册表active下面有没有你要打开串口的驱动(一般这里不会出问题)


如果这三条都没问题,那么你就要看看是不是硬件问题。
91program 2012-02-08
  • 打赏
  • 举报
回复
CE 下要这样使用串口,例如:COM1:

WM 没用过。
meic1985 2012-02-08
  • 打赏
  • 举报
回复
没有人遇到过么
meic1985 2012-02-08
  • 打赏
  • 举报
回复
刚把程序放到wince系统下面运行,正常。放到windows mobile下面就会出错。不解。
meic1985 2012-02-08
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 91program 的回复:]

CE 下要这样使用串口,例如:COM1:

WM 没用过。
[/Quote]
试过加冒号 也不行。
真的没人遇到过么
meic1985 2012-02-07
  • 打赏
  • 举报
回复

public void Open()
{
DCB dcbCommPort = new DCB();
COMMTIMEOUTS ctoCommPort = new COMMTIMEOUTS();

// OPEN THE COMM PORT.
hComm = CreateFile("COM" + PortNum, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);

// IF THE PORT CANNOT BE OPENED, BAIL OUT.
if (hComm == INVALID_HANDLE_VALUE)
{
uint ErrorNum = GetLastError(); ////////////// 这儿的返回值是6:无效句柄
throw (new ApplicationException("GetLastError:" + ErrorNum));
}

// SET THE COMM TIMEOUTS.
GetCommTimeouts(hComm, ref ctoCommPort);
ctoCommPort.ReadTotalTimeoutConstant = ReadTimeout;
ctoCommPort.ReadTotalTimeoutMultiplier = 0;
ctoCommPort.WriteTotalTimeoutMultiplier = 0;
ctoCommPort.WriteTotalTimeoutConstant = 0;
SetCommTimeouts(hComm, ref ctoCommPort);

// SET BAUD RATE, PARITY, WORD SIZE, AND STOP BITS.
GetCommState(hComm, ref dcbCommPort);
dcbCommPort.BaudRate = BaudRate;
dcbCommPort.flags = 0;
//dcb.fBinary=1;
dcbCommPort.flags |= 1;
if (Parity > 0)
{
//dcb.fParity=1
dcbCommPort.flags |= 2;
}
dcbCommPort.Parity = Parity;
dcbCommPort.ByteSize = ByteSize;
dcbCommPort.StopBits = StopBits;
if (!SetCommState(hComm, ref dcbCommPort))
{
//uint ErrorNum=GetLastError();
throw (new ApplicationException("Comm Port Can Not Be Opened "));
}
//unremark to see if setting took correctly
//DCB dcbCommPort2 = new DCB();
//GetCommState(hComm, ref dcbCommPort2);
Opened = true;

}

/// <summary>
/// 关闭串口
/// </summary>
/// <param name= "Close "> 关闭串口 </param>
/// <returns> 这里填写对返回值的注释或说明 </returns>
public void Close()
{
if (hComm != INVALID_HANDLE_VALUE)
{
CloseHandle(hComm);
}
}

public byte[] Read(int NumBytes)
{
byte[] BufBytes;
byte[] OutBytes;
BufBytes = new byte[NumBytes];
if (hComm != INVALID_HANDLE_VALUE)
{
OVERLAPPED ovlCommPort = new OVERLAPPED();
int BytesRead = 0;
bool result = ReadFile(hComm, BufBytes, NumBytes, ref BytesRead, ref ovlCommPort);
OutBytes = new byte[BytesRead];
Array.Copy(BufBytes, OutBytes, BytesRead);
}
else
{
throw (new ApplicationException("Comm Port Not Open "));
}
return OutBytes;
}

public void Write(byte[] WriteBytes)
{
if (hComm != INVALID_HANDLE_VALUE)
{
OVERLAPPED ovlCommPort = new OVERLAPPED();
int BytesWritten = 0;
bool result = WriteFile(hComm, WriteBytes, WriteBytes.Length, ref BytesWritten, ref ovlCommPort);
}
else
{
throw (new ApplicationException("Comm Port Not Open "));
}
}
}

7,655

社区成员

发帖
与我相关
我的任务
社区描述
Windows Phone是微软发布的一款手机操作系统,它将微软旗下的Xbox LIVE游戏、Zune音乐与独特的视频体验整合至手机中。
社区管理员
  • Windows客户端开发社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧