How do I look up the proper Windows System Error Code to use in my application?

前端 未结 4 1042
遇见更好的自我
遇见更好的自我 2020-12-21 05:57

I am writing a C# .NET 2.0 application wherein when a message is expected to be received via the SerialPort. If the frame is not received (i.e. times out) or i

相关标签:
4条回答
  • 2020-12-21 06:41

    in the "good old days" (C and C++), the list of possible Windows errors was defined in winerror.h

    UPDATE: Link below is dead. Not sure if the file is still available for download, but all the Windows System Error Code definitions can be found at this link.

    This file can be found on Microsoft's site (although it surprises me a little that it is dated as far back as 2003 - might be worth hunting for a more recent version).

    But if you're getting (or wanting to set) Win32 error codes, this'll be where the definition is found.

    0 讨论(0)
  • 2020-12-21 06:41

    Unfortunately the above didn't work for me, however this worked perfectly for me, pasting the whole code so it can be copy pasted directly in 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;
        }
    }
    
    0 讨论(0)
  • 2020-12-21 06:49
    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);
    
    0 讨论(0)
  • 2020-12-21 06:49

    You can find a list of them all here:

    http://en.kioskea.net/faq/2347-error-codes-in-windows

    Then just do a search for 'Serial' and use whichever one best fits your error

    0 讨论(0)
提交回复
热议问题