Windows 7上的GetLastError API问题

时间:2010-02-17 07:21:43

标签: winapi windows-7 getlasterror

我有一个与服务器交互的应用程序。如果服务器关闭,那么我将ERROR_WINHTTP_CANNOT_CONNECT我将使用getLastError() API来获取此错误代码,我正在处理此错误代码以向用户显示正确的错误消息。此程序在Windows 2003中正常工作。当我尝试使用Windows7时,我没有收到任何错误,getLastError() API每次都返回0,即使发生错误。我正在使用C ++作为编程语言。

提前致谢

Santhu

3 个答案:

答案 0 :(得分:0)

如果在失败和调用GetLastError()之间进行任何Windows API调用,则当该API调用成功时,错误代码可以重置为0。

您需要在失败后立即调用GetLastError(),并保存该值而不是尝试等待并稍后调用GetLastError()。

答案 1 :(得分:0)

我观察到Windows 2003和Windows 7中GetLastError API的不同行为。 以下是我的观察细节

在Windows 2003中:

示例代码:

WinHttpOpen () - 成功完成

Winhttpconnect() - 由于某些原因,此API失败,例如错误代码12029

GetLastErrorCode() - 按预期返回错误代码12029

WinHttpCloseHandle(hOpen); - 关闭HttpOpen的句柄,完成successfilly

GetLastErrorCode() - 返回错误代码12029

在Windows 7中

示例代码:

WinHttpOpen () - 成功完成

Winhttpconnect() - 由于某些原因,此API失败,例如错误代码12029

GetLastErrorCode() - 按预期返回错误代码12029

WinHttpCloseHandle(hOpen); - 关闭HttpOpen的句柄,成功完成

GetLastErrorCode() - 返回错误代码0 // 查看与Windows 2003示例的区别,在Windows 2003上,此API返回上一个错误,即1209

答案 2 :(得分:0)

微软就此行为提出的答案

The rules for GetLastError are:

•   If the WinHttp API returns error (for example WinHttpIsHostInProxyBypassList, http://msdn.microsoft.com/en-us/library/ee861268(VS.85).aspx) this is the error and GetLastError should *NOT* be called.
o   If GetLastError() is called, regardless of the success or failure of the API, the returned value is unpredictable and may change between Windows versions, Service Packs, or even between runs.
•   If the WinHttp API returns BOOL (for example WinHttpSetTimeouts, http://msdn.microsoft.com/en-us/library/aa384116(VS.85).aspx), it indicates failure by returning FALSE. If the caller is interested in the detailed error, (s)he should call GetLastError(). Note that GetLastError should be called *if and only if* the API failed.
o   If GetLastError() is called when the API succeded (returned anything but FALSE), the returned value is unpredictable and may change between Windows versions, Service Packs, or even between runs. 
•   If the WinHttp API returns HINTERNET (pseudo handle) the rules are exactly the same, except failure is indicated by returning NULL. 
o   If GetLastError() is called when the API succeded (returned anything but NULL), the returned value is unpredictable and may change between Windows versions, Service Packs, or even between runs.