public string FormatString(uint id, params string[] args) { CheckDisposed(); IntPtr buffer = IntPtr.Zero; string source = LoadString(id); // For some reason FORMAT_MESSAGE_FROM_HMODULE doesn't work so we use this way. FormatMessageFlags flags = FormatMessageFlags.FormatMessageAllocateBuffer | FormatMessageFlags.FormatMessageArgumentArray | FormatMessageFlags.FormatMessageFromString; IntPtr sourcePtr = System.Runtime.InteropServices.Marshal.StringToHGlobalAuto(source); try { if (Kernel32.FormatMessage(flags, sourcePtr, id, 0, ref buffer, 0, args) == 0) { throw new System.ComponentModel.Win32Exception(System.Runtime.InteropServices.Marshal.GetLastWin32Error()); } } finally { System.Runtime.InteropServices.Marshal.FreeHGlobal(sourcePtr); } string result = System.Runtime.InteropServices.Marshal.PtrToStringAuto(buffer); // FreeHGlobal calls LocalFree System.Runtime.InteropServices.Marshal.FreeHGlobal(buffer); return(result); }
/// <summary> /// Tries to get the error message text using the supplied buffer. /// </summary> /// <param name="flags"> /// The formatting options, and how to interpret the lpSource parameter. The low-order byte of dwFlags specifies how the function handles line breaks in the output buffer. The low-order byte can also specify the maximum width of a formatted output line. /// </param> /// <param name="source"> /// The location of the message definition. The type of this parameter depends upon the settings in the <paramref name="flags"/> parameter. /// If <see cref="FormatMessageFlags.FORMAT_MESSAGE_FROM_HMODULE"/>: A handle to the module that contains the message table to search. /// If <see cref="FormatMessageFlags.FORMAT_MESSAGE_FROM_STRING"/>: Pointer to a string that consists of unformatted message text. It will be scanned for inserts and formatted accordingly. /// If neither of these flags is set in dwFlags, then lpSource is ignored. /// </param> /// <param name="messageId"> /// The message identifier for the requested message. This parameter is ignored if dwFlags includes <see cref="FormatMessageFlags.FORMAT_MESSAGE_FROM_STRING" />. /// </param> /// <param name="languageId"> /// The language identifier for the requested message. This parameter is ignored if dwFlags includes <see cref="FormatMessageFlags.FORMAT_MESSAGE_FROM_STRING"/>. /// If you pass a specific LANGID in this parameter, FormatMessage will return a message for that LANGID only.If the function cannot find a message for that LANGID, it sets Last-Error to ERROR_RESOURCE_LANG_NOT_FOUND.If you pass in zero, FormatMessage looks for a message for LANGIDs in the following order: /// Language neutral /// Thread LANGID, based on the thread's locale value /// User default LANGID, based on the user's default locale value /// System default LANGID, based on the system default locale value /// US English /// If FormatMessage does not locate a message for any of the preceding LANGIDs, it returns any language message string that is present.If that fails, it returns ERROR_RESOURCE_LANG_NOT_FOUND. /// </param> /// <param name="sb">The buffer to use for acquiring the message.</param> /// <param name="arguments"> /// An array of values that are used as insert values in the formatted message. A %1 in the format string indicates the first value in the Arguments array; a %2 indicates the second argument; and so on. /// The interpretation of each value depends on the formatting information associated with the insert in the message definition.The default is to treat each value as a pointer to a null-terminated string. /// By default, the Arguments parameter is of type va_list*, which is a language- and implementation-specific data type for describing a variable number of arguments.The state of the va_list argument is undefined upon return from the function.To use the va_list again, destroy the variable argument list pointer using va_end and reinitialize it with va_start. /// If you do not have a pointer of type va_list*, then specify the FORMAT_MESSAGE_ARGUMENT_ARRAY flag and pass a pointer to an array of DWORD_PTR values; those values are input to the message formatted as the insert values.Each insert must have a corresponding element in the array. /// </param> /// <param name="errorMsg">Receives the resulting error message.</param> /// <returns><c>true</c> if the attempt is successful; <c>false</c> otherwise.</returns> private static unsafe bool TryGetErrorMessage(FormatMessageFlags flags, void *source, int messageId, int languageId, StringBuilder sb, IntPtr[] arguments, out string errorMsg) { errorMsg = string.Empty; int result = FormatMessage( flags | FormatMessageFlags.FORMAT_MESSAGE_ARGUMENT_ARRAY & ~FormatMessageFlags.FORMAT_MESSAGE_ALLOCATE_BUFFER, source, messageId, languageId, sb, sb.Capacity + 1, arguments); if (result > 0) { int i = sb.Length; while (i > 0) { char ch = sb[i - 1]; if (ch > 32 && ch != '.') { break; } i--; } errorMsg = sb.ToString(0, i); return(true); } else { return(false); } }
/// <summary> /// Formats a message string. The function requires a message definition as input. The message definition can come from a buffer passed into the function. It can come from a message table resource in an already-loaded module. Or the caller can ask the function to search the system's message table resource(s) for the message definition. The function finds the message definition in a message table resource based on a message identifier and a language identifier. The function copies the formatted message text to an output buffer, processing any embedded insert sequences if requested. /// </summary> /// <param name="dwFlags"> /// The formatting options, and how to interpret the lpSource parameter. The low-order byte of dwFlags specifies how the function handles line breaks in the output buffer. The low-order byte can also specify the maximum width of a formatted output line. /// The <see cref="FormatMessageFlags.FORMAT_MESSAGE_ARGUMENT_ARRAY"/> flag is always added /// and the <see cref="FormatMessageFlags.FORMAT_MESSAGE_ALLOCATE_BUFFER"/> flag is always suppressed by this helper method /// </param> /// <param name="lpSource"> /// The location of the message definition. The type of this parameter depends upon the settings in the <paramref name="dwFlags"/> parameter. /// If <see cref="FormatMessageFlags.FORMAT_MESSAGE_FROM_HMODULE"/>: A handle to the module that contains the message table to search. /// If <see cref="FormatMessageFlags.FORMAT_MESSAGE_FROM_STRING"/>: Pointer to a string that consists of unformatted message text. It will be scanned for inserts and formatted accordingly. /// If neither of these flags is set in dwFlags, then lpSource is ignored. /// </param> /// <param name="dwMessageId"> /// The message identifier for the requested message. This parameter is ignored if dwFlags includes <see cref="FormatMessageFlags.FORMAT_MESSAGE_FROM_STRING" />. /// </param> /// <param name="dwLanguageId"> /// The language identifier for the requested message. This parameter is ignored if dwFlags includes <see cref="FormatMessageFlags.FORMAT_MESSAGE_FROM_STRING"/>. /// If you pass a specific LANGID in this parameter, FormatMessage will return a message for that LANGID only.If the function cannot find a message for that LANGID, it sets Last-Error to ERROR_RESOURCE_LANG_NOT_FOUND.If you pass in zero, FormatMessage looks for a message for LANGIDs in the following order: /// Language neutral /// Thread LANGID, based on the thread's locale value /// User default LANGID, based on the user's default locale value /// System default LANGID, based on the system default locale value /// US English /// If FormatMessage does not locate a message for any of the preceding LANGIDs, it returns any language message string that is present.If that fails, it returns ERROR_RESOURCE_LANG_NOT_FOUND. /// </param> /// <param name="Arguments"> /// An array of values that are used as insert values in the formatted message. A %1 in the format string indicates the first value in the Arguments array; a %2 indicates the second argument; and so on. /// The interpretation of each value depends on the formatting information associated with the insert in the message definition.The default is to treat each value as a pointer to a null-terminated string. /// By default, the Arguments parameter is of type va_list*, which is a language- and implementation-specific data type for describing a variable number of arguments.The state of the va_list argument is undefined upon return from the function.To use the va_list again, destroy the variable argument list pointer using va_end and reinitialize it with va_start. /// If you do not have a pointer of type va_list*, then specify the FORMAT_MESSAGE_ARGUMENT_ARRAY flag and pass a pointer to an array of DWORD_PTR values; those values are input to the message formatted as the insert values.Each insert must have a corresponding element in the array. /// </param> /// <param name="maxAllowedBufferSize">The maximum size of the returned string. If exceeded, <c>null</c> is returned.</param> /// <returns> /// If the function succeeds, the return value is the number of TCHARs stored in the output buffer, excluding the terminating null character. /// If the function fails, the return value is zero. To get extended error information, call <see cref="GetLastError"/>. /// </returns> public static unsafe string FormatMessage(FormatMessageFlags dwFlags, void *lpSource, int dwMessageId, int dwLanguageId, IntPtr[] Arguments, int maxAllowedBufferSize) { string errorMsg; StringBuilder sb = new StringBuilder(256); do { if (TryGetErrorMessage(dwFlags, lpSource, dwMessageId, dwLanguageId, sb, Arguments, out errorMsg)) { return(errorMsg); } else { if (GetLastError() == Win32ErrorCode.ERROR_INSUFFICIENT_BUFFER) { // increase the capacity of the StringBuilder by 4 times. sb.Capacity *= 4; } else { // No message with the given ID was found, or some other error occurred. return(null); } } }while (sb.Capacity < maxAllowedBufferSize); // If you come here then a size as large as 65K is also not sufficient. return(null); }
private static extern uint FormatMessage(FormatMessageFlags flags, IntPtr source, uint messageId, uint languageId, ref IntPtr buffer, uint size, IntPtr arguments);
/// <summary> /// Formats a message string. The function requires a message definition as input. The message definition can come from a buffer passed into the function. It can come from a message table resource in an already-loaded module. Or the caller can ask the function to search the system's message table resource(s) for the message definition. The function finds the message definition in a message table resource based on a message identifier and a language identifier. The function copies the formatted message text to an output buffer, processing any embedded insert sequences if requested. /// </summary> /// <param name="dwFlags"> /// The formatting options, and how to interpret the lpSource parameter. The low-order byte of dwFlags specifies how the function handles line breaks in the output buffer. The low-order byte can also specify the maximum width of a formatted output line. /// The <see cref="FormatMessageFlags.FORMAT_MESSAGE_ARGUMENT_ARRAY"/> flag is always added /// and the <see cref="FormatMessageFlags.FORMAT_MESSAGE_ALLOCATE_BUFFER"/> flag is always suppressed by this helper method /// </param> /// <param name="lpSource"> /// The location of the message definition. The type of this parameter depends upon the settings in the <paramref name="dwFlags"/> parameter. /// If <see cref="FormatMessageFlags.FORMAT_MESSAGE_FROM_HMODULE"/>: A handle to the module that contains the message table to search. /// If <see cref="FormatMessageFlags.FORMAT_MESSAGE_FROM_STRING"/>: Pointer to a string that consists of unformatted message text. It will be scanned for inserts and formatted accordingly. /// If neither of these flags is set in dwFlags, then lpSource is ignored. /// </param> /// <param name="dwMessageId"> /// The message identifier for the requested message. This parameter is ignored if dwFlags includes <see cref="FormatMessageFlags.FORMAT_MESSAGE_FROM_STRING" />. /// </param> /// <param name="dwLanguageId"> /// The language identifier for the requested message. This parameter is ignored if dwFlags includes <see cref="FormatMessageFlags.FORMAT_MESSAGE_FROM_STRING"/>. /// If you pass a specific LANGID in this parameter, FormatMessage will return a message for that LANGID only.If the function cannot find a message for that LANGID, it sets Last-Error to ERROR_RESOURCE_LANG_NOT_FOUND.If you pass in zero, FormatMessage looks for a message for LANGIDs in the following order: /// Language neutral /// Thread LANGID, based on the thread's locale value /// User default LANGID, based on the user's default locale value /// System default LANGID, based on the system default locale value /// US English /// If FormatMessage does not locate a message for any of the preceding LANGIDs, it returns any language message string that is present.If that fails, it returns ERROR_RESOURCE_LANG_NOT_FOUND. /// </param> /// <param name="Arguments"> /// An array of values that are used as insert values in the formatted message. A %1 in the format string indicates the first value in the Arguments array; a %2 indicates the second argument; and so on. /// The interpretation of each value depends on the formatting information associated with the insert in the message definition.The default is to treat each value as a pointer to a null-terminated string. /// By default, the Arguments parameter is of type va_list*, which is a language- and implementation-specific data type for describing a variable number of arguments.The state of the va_list argument is undefined upon return from the function.To use the va_list again, destroy the variable argument list pointer using va_end and reinitialize it with va_start. /// If you do not have a pointer of type va_list*, then specify the FORMAT_MESSAGE_ARGUMENT_ARRAY flag and pass a pointer to an array of DWORD_PTR values; those values are input to the message formatted as the insert values.Each insert must have a corresponding element in the array. /// </param> /// <param name="maxAllowedBufferSize">The maximum size of the returned string. If exceeded, <c>null</c> is returned.</param> /// <returns> /// If the function succeeds, the return value is the number of TCHARs stored in the output buffer, excluding the terminating null character. /// If the function fails, the return value is zero. To get extended error information, call <see cref="GetLastError"/>. /// </returns> public static unsafe string FormatMessage(FormatMessageFlags dwFlags, void* lpSource, int dwMessageId, int dwLanguageId, IntPtr[] Arguments, int maxAllowedBufferSize) { string errorMsg; StringBuilder sb = new StringBuilder(256); do { if (TryGetErrorMessage(dwFlags, lpSource, dwMessageId, dwLanguageId, sb, Arguments, out errorMsg)) { return errorMsg; } else { if (GetLastError() == Win32ErrorCode.ERROR_INSUFFICIENT_BUFFER) { // increase the capacity of the StringBuilder by 4 times. sb.Capacity *= 4; } else { // No message with the given ID was found, or some other error occurred. return null; } } } while (sb.Capacity < maxAllowedBufferSize); // If you come here then a size as large as 65K is also not sufficient. return null; }
internal static extern int FormatMessage(FormatMessageFlags dwFlags, SafeLibraryHandle lpSource, int dwMessageId, int dwLanguageId, [In, Out] ref IntPtr lpBuffer, int nSize, IntPtr pArguments);
private static String GetErrorString(Int32 errorCode) { String failed = "Unable to FormatMessage({0}), cause: {1}"; String message; Int16 languageId = MakeLangId(LanguageId.Neutral, SubLanguageId.Neutral); FormatMessageFlags flags = FormatMessageFlags.AllocateBuffer | FormatMessageFlags.FromSystem; IntPtr zero = IntPtr.Zero; Int32 length = FormatMessage(flags, zero, errorCode, languageId, out message, 0, zero); if ( length == 0 || message == null || message.Length != length) { return(String.Format(Cult.InvariantCulture, failed, errorCode, GetLastErrorString())); } message = message.Trim('\r', '\n'); return(message); }
public static extern int FormatMessage(FormatMessageFlags flags, IntPtr source, int messageId, int languageId, out string buffer, int size, IntPtr arguments);
/// <summary> /// /// </summary> /// <param name="errorCode"></param> /// <param name="moduleHandle"></param> /// <param name="args"></param> /// <returns></returns> public static string TranslateError(int errorCode, IntPtr moduleHandle = default(IntPtr), params string[] args) { FormatMessageFlags flags = moduleHandle.IsZero() ? FormatMessageFlags.FromSystem : FormatMessageFlags.FromModule; if (args != null && !args.Length.IsZero()) { flags |= FormatMessageFlags.ArgumentArray; } else { flags |= FormatMessageFlags.IgnoreInserts; } StringBuilder sbDescription = new StringBuilder(0x400); int result = Kernel32.FormatMessage( flags, moduleHandle, errorCode, 0x400 /* NEUTRAL LANGUAGE */, sbDescription, 0x400 /* Size */, args); // if PInvoke fails, use Win32Exception to get error message if (result.IsZero()) { Win32Exception exception = new Win32Exception(Marshal.GetLastWin32Error()); return(exception.Message); } return(sbDescription.ToString()); }
public static extern uint FormatMessage(FormatMessageFlags dwFlags, IntPtr lpSource, uint dwMessageId, uint dwLanguageId, out IntPtr lpBuffer, uint nSize, IntPtr Arguments);
public static extern int FormatMessage( FormatMessageFlags dwFlags, IntPtr lpSource, int dwMessageId, int dwLanguageId, IntPtr buffer, int nSize, IntPtr arguments);
public static extern uint FormatMessageW( [MarshalAs(UnmanagedType.U4)] FormatMessageFlags dwFlags, IntPtr lpSource, uint dwMessageId, uint dwLanguageId, [Out] StringBuilder lpBuffer, uint nSize, IntPtr Arguments);
internal extern static uint FormatMessage( FormatMessageFlags dwFlags, IntPtr lpSource, UInt32 dwMessageId, UInt32 dwLanguageId, ref IntPtr lpBuffer, UInt32 nSize, IntPtr vaArguments );
public static extern uint FormatMessageW( [MarshalAs(UnmanagedType.U4)] FormatMessageFlags dwFlags, UnmanagedString lpSource, uint dwMessageId, uint dwLanguageId, IntPtr lpBuffer, uint nSize, [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPWStr)] string[] Arguments);
public static extern uint FormatMessageW( FormatMessageFlags dwFlags, IntPtr lpSource, uint dwMessageId, // LANGID or 0 for auto lookup uint dwLanguageId, IntPtr lpBuffer, // Size is in chars uint nSize, string[] Arguments);
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms679351.aspx public static uint FormatMessageW( FormatMessageFlags dwFlags, IntPtr lpSource, uint dwMessageId, // LANGID or 0 for auto lookup uint dwLanguageId, IntPtr lpBuffer, // Size is in chars uint nSize, string[] Arguments) => Internal.Imports.FormatMessageW(dwFlags, lpSource, dwMessageId, dwLanguageId, lpBuffer, nSize, Arguments);
public static string FormatMessage(FormatMessageFlags dwFlags, IntPtr lpSource, int dwMessageId, int dwLanguageId, IntPtr argumentsLong) { var ret = new String('\0', MAX_BUFFER_SIZE); var Length = FormatMessage((int)dwFlags, lpSource, dwMessageId, dwLanguageId, ret, (uint)ret.Length, argumentsLong); ret = ret.Substring(0, Length); return(ret); }
// .NET's Win32Exception impements the error code lookup on FormatMessage using FORMAT_MESSAGE_FROM_SYSTEM. // It won't handle Network Errors (NERR_BASE..MAX_NERR), which come from NETMSG.DLL. public static string FormatMessage( uint messageId, IntPtr source, FormatMessageFlags flags, params string[] args) { using (StringBuffer buffer = new StringBuffer()) { // Don't use line breaks flags |= FormatMessageFlags.FORMAT_MESSAGE_MAX_WIDTH_MASK; if (args == null || args.Length == 0) { flags |= FormatMessageFlags.FORMAT_MESSAGE_IGNORE_INSERTS; } WindowsError lastError = WindowsError.ERROR_INSUFFICIENT_BUFFER; uint capacity = byte.MaxValue; uint result = 0; while (lastError == WindowsError.ERROR_INSUFFICIENT_BUFFER && capacity <= short.MaxValue) { buffer.EnsureCharCapacity(capacity); result = Imports.FormatMessageW( dwFlags: flags, lpSource: source, dwMessageId: messageId, // Do the default language lookup dwLanguageId: 0, lpBuffer: buffer.DangerousGetHandle(), nSize: buffer.CharCapacity, Arguments: args); if (result == 0) { lastError = Errors.GetLastError(); capacity = (uint)Math.Min(capacity * 2, short.MaxValue); } else { buffer.Length = result; return(buffer.ToString()); } } throw new IOException("Failed to get error string.", (int)ErrorMacros.HRESULT_FROM_WIN32(lastError)); } }
private static string GetSysErrMsg(uint errCode) { var lpMsgBuf = IntPtr.Zero; const FormatMessageFlags flags = FormatMessageFlags.FormatMessageAllocateBuffer | FormatMessageFlags.FormatMessageIgnoreInserts | FormatMessageFlags.FormatMessageFromSystem; var chars = FormatMessage(flags /*0x1300*/, IntPtr.Zero, errCode, 0, ref lpMsgBuf, 255, IntPtr.Zero); if (chars == 0) { return(null); } var msg = Marshal.PtrToStringAnsi(lpMsgBuf); LocalFree(lpMsgBuf); return(msg); }
public static String GetErrorString(Int32 errorCode) { String message; Int16 languageId = MakeLangId(LanguageId.Neutral, SubLanguageId.Neutral); FormatMessageFlags flags = FormatMessageFlags.AllocateBuffer | FormatMessageFlags.FromSystem; IntPtr zero = IntPtr.Zero; Int32 length = FormatMessage(flags, zero, errorCode, languageId, out message, 0, zero); if (message.Length != length) { return(null); // TODO: Throw exception } message = message.Trim('\r', '\n'); return(message); }
/// <summary> /// Returns the last error code in a formatted message. /// </summary> public static string GetLastErrorMsg() { try { IntPtr lpMsgBuf = IntPtr.Zero; uint errorCode = GetLastError(); FormatMessageFlags dwFlags = FormatMessageFlags.AllocateBuffer | FormatMessageFlags.FromSystem | FormatMessageFlags.IgnoreInserts; if (FormatMessage(dwFlags, IntPtr.Zero, errorCode, 0, out lpMsgBuf, 0, IntPtr.Zero) == 0) { return(string.Format("Failed to get error message from system ({0})", GetLastError())); } string result = Marshal.PtrToStringAnsi(lpMsgBuf); lpMsgBuf = LocalFree(lpMsgBuf); return(result); } catch (Exception e) { return(string.Format("Failed to get error message from system, ex ({0})", e.Message)); } }
public static extern int FormatMessage(FormatMessageFlags dwFlags, IntPtr lpSource, int dwMessageId, int dwLanguageId, StringBuilder lpBuffer, int nSize, string[] Arguments);
public static extern int FormatMessage (FormatMessageFlags dwFlags, IntPtr lpSource, uint dwMessageId, int dwLanguageId, ref IntPtr lpBuffer, int nSize, IntPtr [] arguments);
public static extern Int32 FormatMessage(FormatMessageFlags flags, IntPtr source, Int32 messageId, Int32 languageId, out String buffer, Int32 size, IntPtr arguments);
public static extern uint FormatMessage( FormatMessageFlags dwFlags, IntPtr lpSource, uint dwMessageId, uint dwLanguageId, StringBuilder lpBuffer, uint nSize, IntPtr arguments);
public static extern uint NoSetLastErrorFormatMessage([MarshalAs(UnmanagedType.U4)] FormatMessageFlags dwFlags, IntPtr lpSource, uint dwMessageId, uint dwLanguageId, out IntPtr lpBuffer, uint nSize, IntPtr Arguments);
public extern static int FormatMessage(FormatMessageFlags dwFlags, IntPtr lpSource, int dwMessageId, int dwLanguageId, System.Text.StringBuilder lpBuffer, int nSize, IntPtr[] Arguments);
public static extern uint FormatMessage([MarshalAs(UnmanagedType.U4)] FormatMessageFlags dwFlags, IntPtr lpSource, uint dwMessageId, uint dwLanguageId, ref IntPtr lpBuffer, uint nSize, string[] Arguments);
private static extern uint FormatMessage(FormatMessageFlags dwFlags, IntPtr lpSource, uint dwMessageId, uint dwLanguageId, ref IntPtr lpBuffer, uint nSize, IntPtr pArguments);
public static string GetErrorText(int hr) { string sRet = null; int dwBufferLength; IntPtr ip = IntPtr.Zero; FormatMessageFlags dwFormatFlags = FormatMessageFlags.AllocateBuffer | FormatMessageFlags.IgnoreInserts | FormatMessageFlags.FromSystem | FormatMessageFlags.MaxWidthMask; // Scan both the Windows Media library, and the system library looking for the message dwBufferLength = FormatMessage( dwFormatFlags, s_hModule, // module to get message from (NULL == system) hr, // error number to get message for 0, // default language out ip, 0, null ); // Not a system message. In theory, you should be able to get both with one call. In practice (at // least on my 64bit box), you need to make 2 calls. if (dwBufferLength == 0) { if (s_hModule == IntPtr.Zero) { // Load the Media Foundation error message dll s_hModule = LoadLibraryEx(MESSAGEFILE, IntPtr.Zero, LoadLibraryExFlags.LoadLibraryAsDataFile); } if (s_hModule != IntPtr.Zero) { // If the load succeeds, make sure we look in it dwFormatFlags |= FormatMessageFlags.FromHmodule; // Scan both the Windows Media library, and the system library looking for the message dwBufferLength = FormatMessage( dwFormatFlags, s_hModule, // module to get message from (NULL == system) hr, // error number to get message for 0, // default language out ip, 0, null ); } } try { // Convert the returned buffer to a string. If ip is null (due to not finding // the message), no exception is thrown. sRet just stays null. The // try/finally is for the (remote) possibility that we run out of memory // creating the string. sRet = Marshal.PtrToStringUni(ip); } finally { // Cleanup if (ip != IntPtr.Zero) { LocalFree(ip); } } return(sRet); }
public static extern int FormatMessage(FormatMessageFlags dwFlags, IntPtr lpSource, int dwMessageId, int dwLanguageId, [Out] StringBuilder lpBuffer, int nSize, IntPtr Arguments);
private static extern int FormatMessage(FormatMessageFlags dwFlags, IntPtr lpSource, int dwMessageId, int dwLanguageId, ref IntPtr lpBuffer, int nSize, IntPtr Arguments);
public static unsafe extern int FormatMessage(FormatMessageFlags dwFlags, void* lpSource, int dwMessageId, int dwLanguageId, StringBuilder lpBuffer, int nSize, IntPtr[] Arguments);
public static extern int FormatMessage(FormatMessageFlags flags, IntPtr source, int messageId, int languageId, StringBuilder buffer, int size, IntPtr arguments);
public static extern int FormatMessage([In] FormatMessageFlags dwFlags, [In] IntPtr lpSource, [In] uint dwMessageId, [In] uint dwLanguageId, out IntPtr lpBuffer, [In] uint nSize, [In] IntPtr Arguments);
/// <summary> /// Tries to get the error message text using the supplied buffer. /// </summary> /// <param name="flags"> /// The formatting options, and how to interpret the lpSource parameter. The low-order byte of dwFlags specifies how the function handles line breaks in the output buffer. The low-order byte can also specify the maximum width of a formatted output line. /// </param> /// <param name="source"> /// The location of the message definition. The type of this parameter depends upon the settings in the <paramref name="flags"/> parameter. /// If <see cref="FormatMessageFlags.FORMAT_MESSAGE_FROM_HMODULE"/>: A handle to the module that contains the message table to search. /// If <see cref="FormatMessageFlags.FORMAT_MESSAGE_FROM_STRING"/>: Pointer to a string that consists of unformatted message text. It will be scanned for inserts and formatted accordingly. /// If neither of these flags is set in dwFlags, then lpSource is ignored. /// </param> /// <param name="messageId"> /// The message identifier for the requested message. This parameter is ignored if dwFlags includes <see cref="FormatMessageFlags.FORMAT_MESSAGE_FROM_STRING" />. /// </param> /// <param name="languageId"> /// The language identifier for the requested message. This parameter is ignored if dwFlags includes <see cref="FormatMessageFlags.FORMAT_MESSAGE_FROM_STRING"/>. /// If you pass a specific LANGID in this parameter, FormatMessage will return a message for that LANGID only.If the function cannot find a message for that LANGID, it sets Last-Error to ERROR_RESOURCE_LANG_NOT_FOUND.If you pass in zero, FormatMessage looks for a message for LANGIDs in the following order: /// Language neutral /// Thread LANGID, based on the thread's locale value /// User default LANGID, based on the user's default locale value /// System default LANGID, based on the system default locale value /// US English /// If FormatMessage does not locate a message for any of the preceding LANGIDs, it returns any language message string that is present.If that fails, it returns ERROR_RESOURCE_LANG_NOT_FOUND. /// </param> /// <param name="sb">The buffer to use for acquiring the message.</param> /// <param name="arguments"> /// An array of values that are used as insert values in the formatted message. A %1 in the format string indicates the first value in the Arguments array; a %2 indicates the second argument; and so on. /// The interpretation of each value depends on the formatting information associated with the insert in the message definition.The default is to treat each value as a pointer to a null-terminated string. /// By default, the Arguments parameter is of type va_list*, which is a language- and implementation-specific data type for describing a variable number of arguments.The state of the va_list argument is undefined upon return from the function.To use the va_list again, destroy the variable argument list pointer using va_end and reinitialize it with va_start. /// If you do not have a pointer of type va_list*, then specify the FORMAT_MESSAGE_ARGUMENT_ARRAY flag and pass a pointer to an array of DWORD_PTR values; those values are input to the message formatted as the insert values.Each insert must have a corresponding element in the array. /// </param> /// <param name="errorMsg">Receives the resulting error message.</param> /// <returns><c>true</c> if the attempt is successful; <c>false</c> otherwise.</returns> private static unsafe bool TryGetErrorMessage(FormatMessageFlags flags, void* source, int messageId, int languageId, StringBuilder sb, IntPtr[] arguments, out string errorMsg) { errorMsg = string.Empty; int result = FormatMessage( flags | FormatMessageFlags.FORMAT_MESSAGE_ARGUMENT_ARRAY & ~FormatMessageFlags.FORMAT_MESSAGE_ALLOCATE_BUFFER, source, messageId, languageId, sb, sb.Capacity + 1, arguments); if (result > 0) { int i = sb.Length; while (i > 0) { char ch = sb[i - 1]; if (ch > 32 && ch != '.') { break; } i--; } errorMsg = sb.ToString(0, i); return true; } else { return false; } }
internal static extern int FormatMessage(FormatMessageFlags dwFlags, int lpSource, int dwMessageId, int dwLanguageId, out IntPtr lpBuffer, int nSize, int[] Arguments);
public static int FormatMessage (FormatMessageFlags dwFlags, IntPtr lpSource, uint dwMessageId, int dwLanguageId, ref IntPtr lpBuffer, int nSize, IntPtr [] arguments) { throw new System.NotImplementedException(); }
internal static extern int FormatMessage(FormatMessageFlags flags, IntPtr source, int messageId, int languageId, StringBuilder buffer, int size, IntPtr arguments);
public int FormatMessage(FormatMessageFlags dwFlags, IntPtr lpSource, uint dwMessageId, uint dwLanguageId, StringBuilder lpBuffer, int nSize, IntPtr[] Arguments) => FormatMessage(dwFlags, lpSource, dwMessageId, dwLanguageId, lpBuffer, nSize, Arguments);