我写一个C#的.NET 2.0应用程序,其中,当预期的消息经由SerialPort被接收。如果帧没有接收(即超时),或者它被确定为是无效的,我需要使用SetLastError设置一个错误代码。 Windows有错误代码过多。有一个简单的工具或引用帮助缩小正确的错误代码使用?

其他INFO

虽然抛出一个异常,并处理它越往上堆是我的偏好,这是不是在这种情况下一种选择,因为我更新旨在不采取这样一个实用的功能优势的应用程序。

有帮助吗?

解决方案

在 “好时光”(C和C ++),可能的Windows错误的列表中Winerror.h中

的定义

<强>更新链接下面是死的。不知道如果该文件仍可供下载,但所有的 Windows系统错误代码定义可以在此链接被发现。

此文件可以在微软的网站(尽管它发现惊喜我一点点,它的日期是早在2003 - 可能是值得狩猎的最新版本)

但是,如果你获得(或想组)的Win32错误代码,这将是其中的定义中找到。

其他提示

不幸的是,上面并没有为我工作,然而,这完美地工作对我来说,粘贴整个代码,因此可以直接复制在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);

您都可以在这里找到它们的列表:

http://en.kioskea.net/faq/2347-错误码-在窗口

然后,只需做“串行”和使用哪一个最适合你的错误

搜索
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top