我正在编写一个 C# .NET 2.0 应用程序,其中当预期通过SerialPort
. 如果没有接收到帧(即超时)或被确定为无效,我需要使用SetLastError
. Windows 有大量的错误代码。是否有简单的工具或参考来帮助缩小要使用的正确错误代码?
附加信息
虽然抛出异常并在堆栈的更高位置处理它是我的偏好,但在这种情况下这不是一个选项,因为我正在更新的应用程序并非旨在利用这种有用的特性。
我正在编写一个 C# .NET 2.0 应用程序,其中当预期通过SerialPort
. 如果没有接收到帧(即超时)或被确定为无效,我需要使用SetLastError
. Windows 有大量的错误代码。是否有简单的工具或参考来帮助缩小要使用的正确错误代码?
附加信息
虽然抛出异常并在堆栈的更高位置处理它是我的偏好,但在这种情况下这不是一个选项,因为我正在更新的应用程序并非旨在利用这种有用的特性。
不幸的是,上面的方法对我不起作用,但这对我来说非常有用,粘贴整个代码,因此可以直接复制粘贴到 C#
public static class WinErrors
{
/// <summary>
/// Gets a user friendly string message for a system error code
/// </summary>
/// <param name="errorCode">System error code</param>
/// <returns>Error string</returns>
public static string GetSystemMessage(uint errorCode)
{
var exception = new Win32Exception((int)errorCode);
return exception.Message;
}
}
using System.Runtime.InteropServices; // DllImport
public static string GetSystemMessage(int errorCode) {
int capacity = 512;
int FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000;
StringBuilder sb = new StringBuilder(capacity);
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, IntPtr.Zero, errorCode, 0,
sb, sb.Capacity, IntPtr.Zero);
int i = sb.Length;
if (i>0 && sb[i - 1] == 10) i--;
if (i>0 && sb[i - 1] == 13) i--;
sb.Length = i;
return sb.ToString();
}
[DllImport("kernel32.dll")]
public static extern int FormatMessage(int dwFlags, IntPtr lpSource, int dwMessageId,
int dwLanguageId, StringBuilder lpBuffer, int nSize, IntPtr Arguments);
在“过去的美好时光”(C 和 C++)中,可能的 Windows 错误列表在 winerror.h 中定义
更新:下面的链接已失效。不确定该文件是否仍可供下载,但可以在此链接中找到所有Windows 系统错误代码定义。
这个文件可以在微软的网站上找到(虽然它的历史可以追溯到 2003 年,这让我有点惊讶——可能值得寻找更新的版本)。
但是,如果您得到(或想要设置)Win32 错误代码,这将是找到定义的地方。