问题描述
大家好
我是新手我担心如何使用GetLastError()函数会有点困惑。我有一个无法打开的COM端口,并试图找到它的错误代码。我正在使用;
I'm a newby I'm afraid an a bit confused on how to use the GetLastError() function. I have a com port that is failing to open and trying to find the error code for it. I'm using;
我试过使用https://msdn.microsoft.com/en-us/library/windows/desktop/ms680582(v=)上的示例代码vs.85).aspx但没有取得多大成功。
I have tried using the example code at https://msdn.microsoft.com/en-us/library/windows/desktop/ms680582(v=vs.85).aspx but am not having much success.
我如何正确使用它来查找最后一个错误?我虽然只是添加ErrorExit函数并将'main'代码复制到上面的主代码中,但后来我在构建中得到了多个错误。非常感谢提前!
How would I correctly use this to find the last error?? I though it would just be a case of adding the ErrorExit function and copying over the 'main' code into the above main code, but then I get number of errors in the build. Thanks very much in advance!
推荐答案
hComm = CreateFile(ComPortName, // Name of the Port to be Opened
GENERIC_READ | GENERIC_WRITE, // Read/Write Access
0, // No Sharing, ports cant be shared
NULL, // No Security
OPEN_EXISTING, // Open existing port only
0, // Non Overlapped I/O
NULL); // Null for Comm Devices
if (hComm == INVALID_HANDLE_VALUE)
{
DWORD lasterror = GetLastError();
printf("\n Error! - Port %s can't be opened\nError code %d\n", ComPortName, lasterror);
}
else
printf("\n Port %s Opened\n ", ComPortName);
这将使用printf将错误与错误代码一起打印到控制台。然后,如果CreateFile此时返回INVALID_HANDLE_VALUE,您将以与当前相同的方式处理事务。
This will use printf to print the error to the console along with the error code. You would then handle things in the same way as you would currently do if CreateFile returned INVALID_HANDLE_VALUE at the moment.
除此之外的任何内容只是一个扩展,如果您获得任何编译器或链接器错误然后你应该提供细节。至少,该样本可以干净地编译而无需修改。
Anything beyond this is just an extension, and if you are getting any compiler or linker errors then you should provide details. At the very least, that sample compiles cleanly without modification.
这篇关于如何使用GetLastError()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!