using System; using System.Runtime.InteropServices; using Vanara.Extensions; using Vanara.InteropServices; namespace Vanara.PInvoke { public static partial class Kernel32 { /// The exception maximum parameters public const int EXCEPTION_MAXIMUM_PARAMETERS = 15; /// /// An application-defined function that passes unhandled exceptions to the debugger, if the process is being debugged. Otherwise, it /// optionally displays an Application Error message box and causes the exception handler to be executed. This function can be called /// only from within the filter expression of an exception handler. /// /// /// A pointer to an EXCEPTION_POINTERS structure that specifies a description of the exception and the processor context at the time /// of the exception. This pointer is the return value of a call to the GetExceptionInformation function. /// /// /// The function returns one of the following values. /// /// /// Value /// Meaning /// /// /// EXCEPTION_CONTINUE_SEARCH = 0x0 /// The process is being debugged, so the exception should be passed (as second chance) to the application's debugger. /// /// /// EXCEPTION_EXECUTE_HANDLER = 0x1 /// /// If the SEM_NOGPFAULTERRORBOX flag was specified in a previous call to SetErrorMode, no Application Error message box is /// displayed. The function returns control to the exception handler, which is free to take any appropriate action. /// /// /// /// public delegate EXCEPTION_FLAG PTOP_LEVEL_EXCEPTION_FILTER(in EXCEPTION_POINTERS ExceptionInfo); /// /// An application-defined function that serves as a vectored exception handler. Specify this address when calling the /// AddVectoredExceptionHandler function. /// /// A pointer to an EXCEPTION_POINTERS structure that receives the exception record. /// /// To return control to the point at which the exception occurred, return EXCEPTION_CONTINUE_EXECUTION (0xffffffff). To continue the /// handler search, return EXCEPTION_CONTINUE_SEARCH (0x0). /// [UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate int PVECTORED_EXCEPTION_HANDLER(ref EXCEPTION_POINTERS ExceptionInfo); /// Exception flags public enum EXCEPTION_FLAG : uint { /// Indicates a continuable exception. EXCEPTION_CONTINUABLE = 0, /// /// Proceed with normal execution of UnhandledExceptionFilter. That means obeying the SetErrorMode flags, or invoking the /// Application Error pop-up message box. /// EXCEPTION_CONTINUE_SEARCH = 0x0000, /// Indicates a noncontinuable exception. EXCEPTION_NONCONTINUABLE = 0x0001, /// /// Return from UnhandledExceptionFilter and execute the associated exception handler. This usually results in process termination. /// EXCEPTION_EXECUTE_HANDLER = 0x0001, EXCEPTION_UNWINDING = 0x0002, EXCEPTION_EXIT_UNWIND = 0x0004, EXCEPTION_STACK_INVALID = 0x0008, EXCEPTION_NESTED_CALL = 0x0010, EXCEPTION_TARGET_UNWIND = 0x0020, EXCEPTION_COLLIDED_UNWIND = 0x0040, EXCEPTION_UNWIND = 0x0066, /// /// Return from UnhandledExceptionFilter and continue execution from the point of the exception. Note that the filter function is /// free to modify the continuation state by modifying the exception information supplied through its LPEXCEPTION_POINTERS parameter. /// EXCEPTION_CONTINUE_EXECUTION = 0xFFFFFFFF, EXCEPTION_CHAIN_END = 0xFFFFFFFF, } /// Flags that control the behavior of . public enum FAIL_FAST_FLAGS : uint { /// None. NONE = 0, /// /// Causes RaiseFailFastException to set the ExceptionAddress of EXCEPTION_RECORD to the return address of this function (the /// next instruction in the caller after the call to RaiseFailFastException). This function will set the exception address only /// if ExceptionAddress is not NULL. /// FAIL_FAST_GENERATE_EXCEPTION_ADDRESS = 0x1, } /// /// Flags passed to the method. /// [PInvokeData("winbase.h")] [Flags] public enum FormatMessageFlags { /// /// The function allocates a buffer large enough to hold the formatted message, and places a pointer to the allocated buffer at /// the address specified by lpBuffer. The nSize parameter specifies the minimum number of TCHARs to allocate for an output /// message buffer. The caller should use the LocalFree function to free the buffer when it is no longer needed. /// /// If the length of the formatted message exceeds 128K bytes, then FormatMessage will fail and a subsequent call to GetLastError /// will return ERROR_MORE_DATA. /// /// /// In previous versions of Windows, this value was not available for use when compiling Windows Store apps. As of Windows 10 /// this value can be used. /// /// /// Windows Server 2003 and Windows XP: If the length of the formatted message exceeds 128K bytes, then FormatMessage will not /// automatically fail with an error of ERROR_MORE_DATA. /// /// /// Windows 10: LocalFree is not in the modern SDK, so it cannot be used to free the result buffer. Instead, use HeapFree /// (GetProcessHeap(), allocatedMessage). In this case, this is the same as calling LocalFree on memory. /// /// /// Important: LocalAlloc() has different options: LMEM_FIXED, and LMEM_MOVABLE. FormatMessage() uses LMEM_FIXED, so HeapFree can /// be used. If LMEM_MOVABLE is used, HeapFree cannot be used. /// /// FORMAT_MESSAGE_ALLOCATE_BUFFER = 0x100, /// /// The Arguments parameter is not a va_list structure, but is a pointer to an array of values that represent the arguments. This /// flag cannot be used with 64-bit integer values. If you are using a 64-bit integer, you must use the va_list structure. /// FORMAT_MESSAGE_ARGUMENT_ARRAY = 0x2000, /// /// The lpSource parameter is a module handle containing the message-table resource(s) to search. If this lpSource handle is /// NULL, the current process's application image file will be searched. This flag cannot be used with . /// If the module has no message table resource, the function fails with ERROR_RESOURCE_TYPE_NOT_FOUND. /// FORMAT_MESSAGE_FROM_HMODULE = 0x800, /// /// The lpSource parameter is a pointer to a null-terminated string that contains a message definition. The message definition /// may contain insert sequences, just as the message text in a message table resource may. This flag cannot be used with or . /// FORMAT_MESSAGE_FROM_STRING = 0x400, /// /// The function should search the system message-table resource(s) for the requested message. If this flag is specified with /// , the function searches the system message table if the message is not found in the /// module specified by lpSource. This flag cannot be used with . /// /// If this flag is specified, an application can pass the result of the GetLastError function to retrieve the message text for a /// system-defined error. /// /// FORMAT_MESSAGE_FROM_SYSTEM = 0x1000, /// /// Insert sequences in the message definition are to be ignored and passed through to the output buffer unchanged. This flag is /// useful for fetching a message for later formatting. If this flag is set, the Arguments parameter is ignored. /// FORMAT_MESSAGE_IGNORE_INSERTS = 0x200, /// /// The function ignores regular line breaks in the message definition text. The function stores hard-coded line breaks in the /// message definition text into the output buffer. The function generates no new line breaks. /// /// Without this flag set: There are no output line width restrictions. The function stores line breaks that are in the message /// definition text into the output buffer. It specifies the maximum number of characters in an output line. The function ignores /// regular line breaks in the message definition text. The function never splits a string delimited by white space across a line /// break. The function stores hard-coded line breaks in the message definition text into the output buffer. Hard-coded line /// breaks are coded with the %n escape sequence. /// /// FORMAT_MESSAGE_MAX_WIDTH_MASK = 0xff } /// Registers a vectored continue handler. /// /// The order in which the handler should be called. If the parameter is nonzero, the handler is the first handler to be called. If /// the parameter is zero, the handler is the last handler to be called. /// /// A pointer to the handler to be called. For more information, see VectoredHandler. /// /// If the function succeeds, the return value is a handle to the exception handler. /// If the function fails, the return value is NULL. /// // PVOID WINAPI AddVectoredContinueHandler( _In_ ULONG FirstHandler, _In_ PVECTORED_EXCEPTION_HANDLER VectoredHandler); [DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "ms679273")] public static extern SafeContinueHandlerHandle AddVectoredContinueHandler(uint FirstHandler, PVECTORED_EXCEPTION_HANDLER VectoredHandler); /// Registers a vectored exception handler. /// /// The order in which the handler should be called. If the parameter is nonzero, the handler is the first handler to be called. If /// the parameter is zero, the handler is the last handler to be called. /// /// A pointer to the handler to be called. For more information, see VectoredHandler. /// /// If the function succeeds, the return value is a handle to the exception handler. /// If the function fails, the return value is NULL. /// // PVOID WINAPI AddVectoredExceptionHandler( _In_ ULONG FirstHandler, _In_ PVECTORED_EXCEPTION_HANDLER VectoredHandler); [DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "ms679274")] public static extern SafeExceptionHandlerHandle AddVectoredExceptionHandler(uint FirstHandler, PVECTORED_EXCEPTION_HANDLER VectoredHandler); /// /// Displays a message box and terminates the application when the message box is closed. If the system is running with a debug /// version of Kernel32.dll, the message box gives the user the opportunity to terminate the application or to cancel the message box /// and return to the application that called FatalAppExit. /// /// This parameter must be zero. /// The null-terminated string that is displayed in the message box. /// This function does not return a value. // void WINAPI FatalAppExit( _In_ UINT uAction, _In_ LPCTSTR lpMessageText); https://msdn.microsoft.com/en-us/library/windows/desktop/ms679336(v=vs.85).aspx [DllImport(Lib.Kernel32, SetLastError = false, CharSet = CharSet.Auto)] [PInvokeData("WinBase.h", MSDNShortId = "ms679336")] public static extern void FatalAppExit(uint uAction, string lpMessageText); /// /// 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. /// /// /// /// 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. /// /// This parameter can be one or more of the following values. /// /// /// /// Value /// Meaning /// /// /// FORMAT_MESSAGE_ALLOCATE_BUFFER0x00000100 /// /// The function allocates a buffer large enough to hold the formatted message, and places a pointer to the allocated buffer at the /// address specified by lpBuffer. The lpBuffer parameter is a pointer to an LPTSTR; you must cast the pointer to an LPTSTR (for /// example, ). The nSize parameter specifies the minimum number of TCHARs to allocate for an output message buffer. The caller /// should use the LocalFree function to free the buffer when it is no longer needed.If the length of the formatted message exceeds /// 128K bytes, then FormatMessage will fail and a subsequent call to GetLastError will return ERROR_MORE_DATA.In previous versions /// of Windows, this value was not available for use when compiling Windows Store apps. As of Windows 10 this value can be used. /// Windows Server 2003 and Windows XP: If the length of the formatted message exceeds 128K bytes, then FormatMessage will not /// automatically fail with an error of ERROR_MORE_DATA.Windows 10: LocalAlloc() has different options: LMEM_FIXED, and LMEM_MOVABLE. /// FormatMessage() uses LMEM_FIXED, so HeapFree can be used. If LMEM_MOVABLE is used, HeapFree cannot be used. /// /// /// /// FORMAT_MESSAGE_ARGUMENT_ARRAY0x00002000 /// /// The Arguments parameter is not a va_list structure, but is a pointer to an array of values that represent the arguments.This flag /// cannot be used with 64-bit integer values. If you are using a 64-bit integer, you must use the va_list structure. /// /// /// /// FORMAT_MESSAGE_FROM_HMODULE0x00000800 /// /// The lpSource parameter is a module handle containing the message-table resource(s) to search. If this lpSource handle is NULL, /// the current process's application image file will be searched. This flag cannot be used with FORMAT_MESSAGE_FROM_STRING.If the /// module has no message table resource, the function fails with ERROR_RESOURCE_TYPE_NOT_FOUND. /// /// /// /// FORMAT_MESSAGE_FROM_STRING0x00000400 /// /// The lpSource parameter is a pointer to a null-terminated string that contains a message definition. The message definition may /// contain insert sequences, just as the message text in a message table resource may. This flag cannot be used with /// FORMAT_MESSAGE_FROM_HMODULE or FORMAT_MESSAGE_FROM_SYSTEM. /// /// /// /// FORMAT_MESSAGE_FROM_SYSTEM0x00001000 /// /// The function should search the system message-table resource(s) for the requested message. If this flag is specified with /// FORMAT_MESSAGE_FROM_HMODULE, the function searches the system message table if the message is not found in the module specified /// by lpSource. This flag cannot be used with FORMAT_MESSAGE_FROM_STRING.If this flag is specified, an application can pass the /// result of the GetLastError function to retrieve the message text for a system-defined error. /// /// /// /// FORMAT_MESSAGE_IGNORE_INSERTS0x00000200 /// /// Insert sequences in the message definition are to be ignored and passed through to the output buffer unchanged. This flag is /// useful for fetching a message for later formatting. If this flag is set, the Arguments parameter is ignored. /// /// /// /// /// /// The low-order byte of dwFlags can specify the maximum width of a formatted output line. The following are possible values of the /// low-order byte. /// /// /// /// /// Value /// Meaning /// /// /// 0 /// /// There are no output line width restrictions. The function stores line breaks that are in the message definition text into the /// output buffer. /// /// /// /// FORMAT_MESSAGE_MAX_WIDTH_MASK0x000000FF /// /// The function ignores regular line breaks in the message definition text. The function stores hard-coded line breaks in the /// message definition text into the output buffer. The function generates no new line breaks. /// /// /// /// /// /// If the low-order byte is a nonzero value other than FORMAT_MESSAGE_MAX_WIDTH_MASK, it specifies the maximum number of /// characters in an output line. The function ignores regular line breaks in the message definition text. The function never splits /// a string delimited by white space across a line break. The function stores hard-coded line breaks in the message definition text /// into the output buffer. Hard-coded line breaks are coded with the %n escape sequence. /// /// /// /// The location of the message definition. The type of this parameter depends upon the settings in the dwFlags parameter. /// /// /// /// dwFlags Setting /// Meaning /// /// /// FORMAT_MESSAGE_FROM_HMODULE0x00000800 /// A handle to the module that contains the message table to search. /// /// /// FORMAT_MESSAGE_FROM_STRING0x00000400 /// 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. /// /// The message identifier for the requested message. This parameter is ignored if dwFlags includes FORMAT_MESSAGE_FROM_STRING. /// /// The language identifier for the requested message. This parameter is ignored if dwFlags includes 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: /// /// /// 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. /// /// /// /// /// A pointer to a buffer that receives the null-terminated string that specifies the formatted message. If dwFlags includes /// FORMAT_MESSAGE_ALLOCATE_BUFFER, the function allocates a buffer using the LocalAlloc function, and places the /// pointer to the buffer at the address specified in lpBuffer. /// /// This buffer cannot be larger than 64K bytes. /// /// /// /// If the FORMAT_MESSAGE_ALLOCATE_BUFFER flag is not set, this parameter specifies the size of the output buffer, in /// TCHARs. If FORMAT_MESSAGE_ALLOCATE_BUFFER is set, this parameter specifies the minimum number of TCHARs to /// allocate for an output buffer. /// /// The output buffer cannot be larger than 64K bytes. /// /// /// /// 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. /// /// /// /// /// 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 GetLastError. /// // DWORD WINAPI FormatMessage( _In_ DWORD dwFlags, _In_opt_ LPCVOID lpSource, _In_ DWORD dwMessageId, _In_ DWORD dwLanguageId, _Out_ // LPTSTR lpBuffer, _In_ DWORD nSize, _In_opt_ va_list *Arguments); https://msdn.microsoft.com/en-us/library/windows/desktop/ms679351(v=vs.85).aspx [DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)] [PInvokeData("WinBase.h", MSDNShortId = "ms679351")] public static extern int FormatMessage(FormatMessageFlags dwFlags, HINSTANCE lpSource, uint dwMessageId, uint dwLanguageId, ref IntPtr lpBuffer, uint nSize, string[] Arguments); /// /// 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. /// /// /// /// 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. /// /// This parameter can be one or more of the following values. /// /// /// /// Value /// Meaning /// /// /// FORMAT_MESSAGE_ALLOCATE_BUFFER0x00000100 /// /// The function allocates a buffer large enough to hold the formatted message, and places a pointer to the allocated buffer at the /// address specified by lpBuffer. The lpBuffer parameter is a pointer to an LPTSTR; you must cast the pointer to an LPTSTR (for /// example, ). The nSize parameter specifies the minimum number of TCHARs to allocate for an output message buffer. The caller /// should use the LocalFree function to free the buffer when it is no longer needed.If the length of the formatted message exceeds /// 128K bytes, then FormatMessage will fail and a subsequent call to GetLastError will return ERROR_MORE_DATA.In previous versions /// of Windows, this value was not available for use when compiling Windows Store apps. As of Windows 10 this value can be used. /// Windows Server 2003 and Windows XP: If the length of the formatted message exceeds 128K bytes, then FormatMessage will not /// automatically fail with an error of ERROR_MORE_DATA.Windows 10: LocalAlloc() has different options: LMEM_FIXED, and LMEM_MOVABLE. /// FormatMessage() uses LMEM_FIXED, so HeapFree can be used. If LMEM_MOVABLE is used, HeapFree cannot be used. /// /// /// /// FORMAT_MESSAGE_ARGUMENT_ARRAY0x00002000 /// /// The Arguments parameter is not a va_list structure, but is a pointer to an array of values that represent the arguments.This flag /// cannot be used with 64-bit integer values. If you are using a 64-bit integer, you must use the va_list structure. /// /// /// /// FORMAT_MESSAGE_FROM_HMODULE0x00000800 /// /// The lpSource parameter is a module handle containing the message-table resource(s) to search. If this lpSource handle is NULL, /// the current process's application image file will be searched. This flag cannot be used with FORMAT_MESSAGE_FROM_STRING.If the /// module has no message table resource, the function fails with ERROR_RESOURCE_TYPE_NOT_FOUND. /// /// /// /// FORMAT_MESSAGE_FROM_STRING0x00000400 /// /// The lpSource parameter is a pointer to a null-terminated string that contains a message definition. The message definition may /// contain insert sequences, just as the message text in a message table resource may. This flag cannot be used with /// FORMAT_MESSAGE_FROM_HMODULE or FORMAT_MESSAGE_FROM_SYSTEM. /// /// /// /// FORMAT_MESSAGE_FROM_SYSTEM0x00001000 /// /// The function should search the system message-table resource(s) for the requested message. If this flag is specified with /// FORMAT_MESSAGE_FROM_HMODULE, the function searches the system message table if the message is not found in the module specified /// by lpSource. This flag cannot be used with FORMAT_MESSAGE_FROM_STRING.If this flag is specified, an application can pass the /// result of the GetLastError function to retrieve the message text for a system-defined error. /// /// /// /// FORMAT_MESSAGE_IGNORE_INSERTS0x00000200 /// /// Insert sequences in the message definition are to be ignored and passed through to the output buffer unchanged. This flag is /// useful for fetching a message for later formatting. If this flag is set, the Arguments parameter is ignored. /// /// /// /// /// /// The low-order byte of dwFlags can specify the maximum width of a formatted output line. The following are possible values of the /// low-order byte. /// /// /// /// /// Value /// Meaning /// /// /// 0 /// /// There are no output line width restrictions. The function stores line breaks that are in the message definition text into the /// output buffer. /// /// /// /// FORMAT_MESSAGE_MAX_WIDTH_MASK0x000000FF /// /// The function ignores regular line breaks in the message definition text. The function stores hard-coded line breaks in the /// message definition text into the output buffer. The function generates no new line breaks. /// /// /// /// /// /// If the low-order byte is a nonzero value other than FORMAT_MESSAGE_MAX_WIDTH_MASK, it specifies the maximum number of /// characters in an output line. The function ignores regular line breaks in the message definition text. The function never splits /// a string delimited by white space across a line break. The function stores hard-coded line breaks in the message definition text /// into the output buffer. Hard-coded line breaks are coded with the %n escape sequence. /// /// /// /// The location of the message definition. The type of this parameter depends upon the settings in the dwFlags parameter. /// /// /// /// dwFlags Setting /// Meaning /// /// /// FORMAT_MESSAGE_FROM_HMODULE0x00000800 /// A handle to the module that contains the message table to search. /// /// /// FORMAT_MESSAGE_FROM_STRING0x00000400 /// 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. /// /// The message identifier for the requested message. This parameter is ignored if dwFlags includes FORMAT_MESSAGE_FROM_STRING. /// /// The language identifier for the requested message. This parameter is ignored if dwFlags includes 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: /// /// /// 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. /// /// /// /// /// A pointer to a buffer that receives the null-terminated string that specifies the formatted message. If dwFlags includes /// FORMAT_MESSAGE_ALLOCATE_BUFFER, the function allocates a buffer using the LocalAlloc function, and places the /// pointer to the buffer at the address specified in lpBuffer. /// /// This buffer cannot be larger than 64K bytes. /// /// /// /// If the FORMAT_MESSAGE_ALLOCATE_BUFFER flag is not set, this parameter specifies the size of the output buffer, in /// TCHARs. If FORMAT_MESSAGE_ALLOCATE_BUFFER is set, this parameter specifies the minimum number of TCHARs to /// allocate for an output buffer. /// /// The output buffer cannot be larger than 64K bytes. /// /// /// /// 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. /// /// /// /// /// 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 GetLastError. /// [DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)] [PInvokeData("WinBase.h", MSDNShortId = "ms679351")] public static extern int FormatMessage(FormatMessageFlags dwFlags, IntPtr lpSource, uint dwMessageId, uint dwLanguageId, ref IntPtr lpBuffer, uint nSize, string[] Arguments); /// /// 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. /// /// /// 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. /// /// This parameter can be one or more of the following values. /// /// /// /// Value /// Meaning /// /// /// FORMAT_MESSAGE_ALLOCATE_BUFFER0x00000100 /// /// The function allocates a buffer large enough to hold the formatted message, and places a pointer to the allocated buffer at the /// address specified by lpBuffer. The lpBuffer parameter is a pointer to an LPTSTR; you must cast the pointer to an LPTSTR (for /// example, ). The nSize parameter specifies the minimum number of TCHARs to allocate for an output message buffer. The caller /// should use the LocalFree function to free the buffer when it is no longer needed.If the length of the formatted message exceeds /// 128K bytes, then FormatMessage will fail and a subsequent call to GetLastError will return ERROR_MORE_DATA.In previous versions /// of Windows, this value was not available for use when compiling Windows Store apps. As of Windows 10 this value can be used. /// Windows Server 2003 and Windows XP: If the length of the formatted message exceeds 128K bytes, then FormatMessage will not /// automatically fail with an error of ERROR_MORE_DATA.Windows 10: LocalAlloc() has different options: LMEM_FIXED, and LMEM_MOVABLE. /// FormatMessage() uses LMEM_FIXED, so HeapFree can be used. If LMEM_MOVABLE is used, HeapFree cannot be used. /// /// /// /// FORMAT_MESSAGE_ARGUMENT_ARRAY0x00002000 /// /// The Arguments parameter is not a va_list structure, but is a pointer to an array of values that represent the arguments.This flag /// cannot be used with 64-bit integer values. If you are using a 64-bit integer, you must use the va_list structure. /// /// /// /// FORMAT_MESSAGE_FROM_HMODULE0x00000800 /// /// The lpSource parameter is a module handle containing the message-table resource(s) to search. If this lpSource handle is NULL, /// the current process's application image file will be searched. This flag cannot be used with FORMAT_MESSAGE_FROM_STRING.If the /// module has no message table resource, the function fails with ERROR_RESOURCE_TYPE_NOT_FOUND. /// /// /// /// FORMAT_MESSAGE_FROM_STRING0x00000400 /// /// The lpSource parameter is a pointer to a null-terminated string that contains a message definition. The message definition may /// contain insert sequences, just as the message text in a message table resource may. This flag cannot be used with /// FORMAT_MESSAGE_FROM_HMODULE or FORMAT_MESSAGE_FROM_SYSTEM. /// /// /// /// FORMAT_MESSAGE_FROM_SYSTEM0x00001000 /// /// The function should search the system message-table resource(s) for the requested message. If this flag is specified with /// FORMAT_MESSAGE_FROM_HMODULE, the function searches the system message table if the message is not found in the module specified /// by lpSource. This flag cannot be used with FORMAT_MESSAGE_FROM_STRING.If this flag is specified, an application can pass the /// result of the GetLastError function to retrieve the message text for a system-defined error. /// /// /// /// FORMAT_MESSAGE_IGNORE_INSERTS0x00000200 /// /// Insert sequences in the message definition are to be ignored and passed through to the output buffer unchanged. This flag is /// useful for fetching a message for later formatting. If this flag is set, the Arguments parameter is ignored. /// /// /// /// /// /// The low-order byte of dwFlags can specify the maximum width of a formatted output line. The following are possible values of the /// low-order byte. /// /// /// /// /// Value /// Meaning /// /// /// 0 /// /// There are no output line width restrictions. The function stores line breaks that are in the message definition text into the /// output buffer. /// /// /// /// FORMAT_MESSAGE_MAX_WIDTH_MASK0x000000FF /// /// The function ignores regular line breaks in the message definition text. The function stores hard-coded line breaks in the /// message definition text into the output buffer. The function generates no new line breaks. /// /// /// /// /// /// If the low-order byte is a nonzero value other than FORMAT_MESSAGE_MAX_WIDTH_MASK, it specifies the maximum number of /// characters in an output line. The function ignores regular line breaks in the message definition text. The function never splits /// a string delimited by white space across a line break. The function stores hard-coded line breaks in the message definition text /// into the output buffer. Hard-coded line breaks are coded with the %n escape sequence. /// /// The location of the message definition. The type of this parameter depends upon the settings in the dwFlags parameter. /// /// /// /// dwFlags Setting /// Meaning /// /// /// FORMAT_MESSAGE_FROM_HMODULE0x00000800 /// A handle to the module that contains the message table to search. /// /// /// FORMAT_MESSAGE_FROM_STRING0x00000400 /// 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. /// The message identifier for the requested message. This parameter is ignored if dwFlags includes FORMAT_MESSAGE_FROM_STRING. /// The language identifier for the requested message. This parameter is ignored if dwFlags includes 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: /// /// /// 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. /// /// /// A pointer to a buffer that receives the null-terminated string that specifies the formatted message. If dwFlags includes /// FORMAT_MESSAGE_ALLOCATE_BUFFER, the function allocates a buffer using the LocalAlloc function, and places the /// pointer to the buffer at the address specified in lpBuffer. /// /// This buffer cannot be larger than 64K bytes. /// /// If the FORMAT_MESSAGE_ALLOCATE_BUFFER flag is not set, this parameter specifies the size of the output buffer, in /// TCHARs. If FORMAT_MESSAGE_ALLOCATE_BUFFER is set, this parameter specifies the minimum number of TCHARs to /// allocate for an output buffer. /// /// The output buffer cannot be larger than 64K bytes. /// /// /// 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 GetLastError. /// // DWORD WINAPI FormatMessage( _In_ DWORD dwFlags, _In_opt_ LPCVOID lpSource, _In_ DWORD dwMessageId, _In_ DWORD dwLanguageId, _Out_ // LPTSTR lpBuffer, _In_ DWORD nSize, _In_opt_ va_list *Arguments); https://msdn.microsoft.com/en-us/library/windows/desktop/ms679351(v=vs.85).aspx [DllImport(Lib.Kernel32, CharSet = CharSet.Auto, SetLastError = true, CallingConvention = CallingConvention.Cdecl)] [PInvokeData("WinBase.h", MSDNShortId = "ms679351")] private static extern int FormatMessage(FormatMessageFlags dwFlags, IntPtr lpSource, uint dwMessageId, uint dwLanguageId, ref IntPtr lpBuffer, uint nSize, __arglist); /// /// Formats a message string. The function requires a message definition as input. The message definition 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 returns the formatted message text, processing any embedded insert sequences if requested. /// /// The message identifier for the requested message. /// /// 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. Each insert must have a corresponding element in the array. /// /// A handle to the module that contains the message table to search. /// /// 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 language identifier for the requested message. 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. /// /// /// If the function succeeds, the return value is the string that specifies the formatted message. To get extended error information, /// call GetLastError. /// [PInvokeData("WinBase.h", MSDNShortId = "ms679351")] public static string FormatMessage(uint id, string[] args = null, HINSTANCE hLib = default, FormatMessageFlags flags = 0, uint langId = 0) { flags &= ~FormatMessageFlags.FORMAT_MESSAGE_FROM_STRING; flags |= FormatMessageFlags.FORMAT_MESSAGE_ALLOCATE_BUFFER | FormatMessageFlags.FORMAT_MESSAGE_FROM_SYSTEM; if (!hLib.IsNull) flags |= FormatMessageFlags.FORMAT_MESSAGE_FROM_HMODULE; if (args != null && args.Length > 0 && !flags.IsFlagSet(FormatMessageFlags.FORMAT_MESSAGE_IGNORE_INSERTS)) flags |= FormatMessageFlags.FORMAT_MESSAGE_ARGUMENT_ARRAY; var ptr = IntPtr.Zero; var ret = FormatMessage(flags, hLib, id, langId, ref ptr, 0, args); if (ret == 0) Win32Error.ThrowLastError(); return new SafeLocalHandle(ptr, 0).ToString(-1); } /// /// Formats a message string. The function requires a message definition as input. The message definition 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 returns the formatted message text, processing any embedded insert sequences if requested. /// /// /// Pointer to a string that consists of unformatted message text. It will be scanned for inserts and formatted accordingly. /// /// /// 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. Each insert must have a corresponding element in the array. /// /// /// 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. /// /// /// If the function succeeds, the return value is the string that specifies the formatted message. To get extended error information, /// call GetLastError. /// [PInvokeData("WinBase.h", MSDNShortId = "ms679351")] public static string FormatMessage(string formatString, string[] args, FormatMessageFlags flags = 0) { if (string.IsNullOrEmpty(formatString) || args == null || args.Length == 0 || flags.IsFlagSet(FormatMessageFlags.FORMAT_MESSAGE_IGNORE_INSERTS)) return formatString; flags &= ~(FormatMessageFlags.FORMAT_MESSAGE_FROM_HMODULE | FormatMessageFlags.FORMAT_MESSAGE_FROM_SYSTEM); flags |= FormatMessageFlags.FORMAT_MESSAGE_FROM_STRING | FormatMessageFlags.FORMAT_MESSAGE_ALLOCATE_BUFFER | FormatMessageFlags.FORMAT_MESSAGE_ARGUMENT_ARRAY; var ptr = IntPtr.Zero; var s = new SafeCoTaskMemString(formatString); var ret = FormatMessage(flags, (IntPtr)s, 0U, 0U, ref ptr, 0U, args); if (ret == 0) Win32Error.ThrowLastError(); return new SafeLocalHandle(ptr, 0).ToString(-1); } /// Retrieves the error mode for the current process. /// /// The process error mode. This function returns one of the following values. /// /// /// /// Return code/value /// Description /// /// /// SEM_FAILCRITICALERRORS0x0001 /// /// The system does not display the critical-error-handler message box. Instead, the system sends the error to the calling process. /// /// /// /// SEM_NOALIGNMENTFAULTEXCEPT0x0004 /// /// The system automatically fixes memory alignment faults and makes them invisible to the application. It does this for the calling /// process and any descendant processes. This feature is only supported by certain processor architectures. For more information, /// see SetErrorMode. /// /// /// /// SEM_NOGPFAULTERRORBOX0x0002 /// The system does not display the Windows Error Reporting dialog. /// /// /// SEM_NOOPENFILEERRORBOX0x8000 /// /// The system does not display a message box when it fails to find a file. Instead, the error is returned to the calling process. /// /// /// /// /// // UINT WINAPI GetErrorMode(void); https://msdn.microsoft.com/en-us/library/windows/desktop/ms679355(v=vs.85).aspx [DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "ms679355")] public static extern uint GetErrorMode(); /// /// /// Retrieves the calling thread's last-error code value. The last-error code is maintained on a per-thread basis. Multiple threads /// do not overwrite each other's last-error code. /// /// Visual Basic: Applications should call err.LastDllError instead of GetLastError. /// /// /// The return value is the calling thread's last-error code. /// /// The Return Value section of the documentation for each function that sets the last-error code notes the conditions under which /// the function sets the last-error code. Most functions that set the thread's last-error code set it when they fail. However, some /// functions also set the last-error code when they succeed. If the function is not documented to set the last-error code, the value /// returned by this function is simply the most recent last-error code to have been set; some functions set the last-error code to 0 /// on success and others do not. /// /// // DWORD WINAPI GetLastError(void);// https://msdn.microsoft.com/en-us/library/windows/desktop/ms679360(v=vs.85).aspx [DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "ms679360")] public static extern Win32Error GetLastError(); /// Retrieves the error mode for the calling thread. /// /// The process error mode. This function returns one of the following values. /// /// /// /// Return code/value /// Description /// /// /// SEM_FAILCRITICALERRORS = 0x0001 /// /// The system does not display the critical-error-handler message box. Instead, the system sends the error to the calling process. /// /// /// /// SEM_NOGPFAULTERRORBOX = 0x0002 /// The system does not display the Windows Error Reporting dialog. /// /// /// SEM_NOOPENFILEERRORBOX = 0x8000 /// /// The system does not display a message box when it fails to find a file. Instead, the error is returned to the calling process. /// /// /// /// /// [DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "dd553629")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool GetThreadErrorMode(uint dwNewMode, out uint lpOldMode); /// Raises an exception in the calling thread. /// /// /// An application-defined exception code of the exception being raised. The filter expression and exception-handler block of an /// exception handler can use the GetExceptionCode function to retrieve this value. /// /// /// Note that the system will clear bit 28 of dwExceptionCode before displaying a message This bit is a reserved exception bit, used /// by the system for its own purposes. /// /// /// /// The exception flags. This can be either zero to indicate a continuable exception, or EXCEPTION_NONCONTINUABLE to indicate a /// noncontinuable exception. Any attempt to continue execution after a noncontinuable exception causes the /// EXCEPTION_NONCONTINUABLE_EXCEPTION exception. /// /// /// The number of arguments in the lpArguments array. This value must not exceed EXCEPTION_MAXIMUM_PARAMETERS. This parameter is /// ignored if lpArguments is NULL. /// /// /// An array of arguments. This parameter can be NULL. These arguments can contain any application-defined data that needs to /// be passed to the filter expression of the exception handler. /// /// This function does not return a value. // void WINAPI RaiseException( _In_ DWORD dwExceptionCode, _In_ DWORD dwExceptionFlags, _In_ DWORD nNumberOfArguments, _In_ const ULONG_PTR // *lpArguments); https://msdn.microsoft.com/en-us/library/windows/desktop/ms680552(v=vs.85).aspx [DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "ms680552")] public static extern void RaiseException(uint dwExceptionCode, EXCEPTION_FLAG dwExceptionFlags, uint nNumberOfArguments, [In] IntPtr lpArguments); /// /// Raises an exception that bypasses all exception handlers (frame or vector based). Raising this exception terminates the /// application and invokes Windows Error Reporting, if Windows Error Reporting is enabled. /// /// /// /// A pointer to an EXCEPTION_RECORD structure that contains the exception information. You must specify the /// ExceptionAddress and ExceptionCode members. /// /// /// If this parameter is NULL, the function creates an exception record and sets the ExceptionCode member to /// STATUS_FAIL_FAST_EXCEPTION. The function will also set the ExceptionAddress member if the dwFlags parameter contains the /// FAIL_FAST_GENERATE_EXCEPTION_ADDRESS flag. /// /// /// /// A pointer to a CONTEXT structure that contains the context information. If NULL, this function generates the /// context (however, the context will not exactly match the context of the caller). /// /// /// You can specify zero or the following flag that control this function's behavior: /// /// /// /// Value /// Meaning /// /// /// FAIL_FAST_GENERATE_EXCEPTION_ADDRESS0x1 /// /// Causes RaiseFailFastException to set the ExceptionAddress of EXCEPTION_RECORD to the return address of this function (the next /// instruction in the caller after the call to RaiseFailFastException). This function will set the exception address only if /// ExceptionAddress is not NULL. /// /// /// /// /// /// This function does not return a value. // VOID WINAPI RaiseFailFastException( _In_opt_ PEXCEPTION_RECORD pExceptionRecord, _In_opt_ PCONTEXT pContextRecord, _In_ DWORD // dwFlags); https://msdn.microsoft.com/en-us/library/windows/desktop/dd941688(v=vs.85).aspx [DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "dd941688")] public static extern void RaiseFailFastException(ref EXCEPTION_RECORD pExceptionRecord, IntPtr pContextRecord, FAIL_FAST_FLAGS dwFlags); /// Unregisters a vectored continue handler. /// /// A pointer to a vectored exception handler previously registered using the AddVectoredContinueHandler function. /// /// /// If the function succeeds, the return value is nonzero. /// If the function fails, the return value is zero. /// // ULONG WINAPI RemoveVectoredContinueHandler( _In_ PVOID Handler); https://msdn.microsoft.com/en-us/library/windows/desktop/ms680567(v=vs.85).aspx [DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "ms680567")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool RemoveVectoredContinueHandler([In] IntPtr Handler); /// Unregisters a vectored exception handler. /// /// A handle to the vectored exception handler previously registered using the AddVectoredExceptionHandler function. /// /// /// If the function succeeds, the return value is nonzero. /// If the function fails, the return value is zero. /// // ULONG WINAPI RemoveVectoredExceptionHandler( _In_ PVOID Handler); [DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "ms680571")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool RemoveVectoredExceptionHandler([In] IntPtr Handler); /// Restores the last-error code for the calling thread. /// The last-error code for the thread. [DllImport(Lib.Kernel32, ExactSpelling = true, SetLastError = true)] [PInvokeData("WinBase.h", MSDNShortId = "")] public static extern void RestoreLastError(uint dwErrCode); /// /// Controls whether the system will handle the specified types of serious errors or whether the process will handle them. /// /// /// The process error mode. This parameter can be one or more of the following values. /// /// /// /// Value /// Meaning /// /// /// 0 /// Use the system default, which is to display all error dialog boxes. /// /// /// SEM_FAILCRITICALERRORS0x0001 /// /// The system does not display the critical-error-handler message box. Instead, the system sends the error to the calling /// process.Best practice is that all applications call the process-wide SetErrorMode function with a parameter of /// SEM_FAILCRITICALERRORS at startup. This is to prevent error mode dialogs from hanging the application. /// /// /// /// SEM_NOALIGNMENTFAULTEXCEPT0x0004 /// /// The system automatically fixes memory alignment faults and makes them invisible to the application. It does this for the calling /// process and any descendant processes. This feature is only supported by certain processor architectures. For more information, /// see the Remarks section. After this value is set for a process, subsequent attempts to clear the value are ignored. /// /// /// /// SEM_NOGPFAULTERRORBOX0x0002 /// The system does not display the Windows Error Reporting dialog. /// /// /// SEM_NOOPENFILEERRORBOX0x8000 /// /// The OpenFile function does not display a message box when it fails to find a file. Instead, the error is returned to the caller. /// This error mode overrides the OF_PROMPT flag. /// /// /// /// /// /// The return value is the previous state of the error-mode bit flags. // UINT WINAPI SetErrorMode( _In_ UINT uMode); https://msdn.microsoft.com/en-us/library/windows/desktop/ms680621(v=vs.85).aspx [DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "ms680621")] public static extern uint SetErrorMode(uint uMode); /// Sets the last-error code for the calling thread. /// The last-error code for the thread. [DllImport(Lib.Kernel32, ExactSpelling = true, SetLastError = true)] [PInvokeData("WinBase.h", MSDNShortId = "ms680627")] public static extern void SetLastError(uint dwErrCode); /// /// Controls whether the system will handle the specified types of serious errors or whether the calling thread will handle them. /// /// /// The thread error mode. This parameter can be one or more of the following values. /// /// /// /// Value /// Meaning /// /// /// 0 /// Use the system default, which is to display all error dialog boxes. /// /// /// SEM_FAILCRITICALERRORS0x0001 /// /// The system does not display the critical-error-handler message box. Instead, the system sends the error to the calling /// thread.Best practice is that all applications call the process-wide SetErrorMode function with a parameter of /// SEM_FAILCRITICALERRORS at startup. This is to prevent error mode dialogs from hanging the application. /// /// /// /// SEM_NOGPFAULTERRORBOX0x0002 /// The system does not display the Windows Error Reporting dialog. /// /// /// SEM_NOOPENFILEERRORBOX0x8000 /// /// The OpenFile function does not display a message box when it fails to find a file. Instead, the error is returned to the caller. /// This error mode overrides the OF_PROMPT flag. /// /// /// /// /// /// /// If the function succeeds, this parameter is set to the thread's previous error mode. This parameter can be NULL. /// /// /// If the function succeeds, the return value is nonzero. /// If the function fails, the return value is zero. To get extended error information, call GetLastError. /// // BOOL SetThreadErrorMode( _In_ DWORD dwNewMode, _Out_ LPDWORD lpOldMode); https://msdn.microsoft.com/en-us/library/windows/desktop/dd553630(v=vs.85).aspx [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "dd553630")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool SetThreadErrorMode(uint dwNewMode, out uint lpOldMode); /// /// Enables an application to supersede the top-level exception handler of each thread of a process. /// /// After calling this function, if an exception occurs in a process that is not being debugged, and the exception makes it to the /// unhandled exception filter, that filter will call the exception filter function specified by the lpTopLevelExceptionFilter parameter. /// /// /// /// /// A pointer to a top-level exception filter function that will be called whenever the UnhandledExceptionFilter function gets /// control, and the process is not being debugged. A value of NULL for this parameter specifies default handling within UnhandledExceptionFilter. /// /// /// The filter function has syntax similar to that of UnhandledExceptionFilter: It takes a single parameter of type /// LPEXCEPTION_POINTERS, has a WINAPI calling convention, and returns a value of type LONG. The filter function should /// return one of the following values. /// /// /// /// /// Value /// Meaning /// /// /// EXCEPTION_EXECUTE_HANDLER0x1 /// Return from UnhandledExceptionFilter and execute the associated exception handler. This usually results in process termination. /// /// /// EXCEPTION_CONTINUE_EXECUTION0xffffffff /// /// Return from UnhandledExceptionFilter and continue execution from the point of the exception. Note that the filter function is /// free to modify the continuation state by modifying the exception information supplied through its LPEXCEPTION_POINTERS parameter. /// /// /// /// EXCEPTION_CONTINUE_SEARCH0x0 /// /// Proceed with normal execution of UnhandledExceptionFilter. That means obeying the SetErrorMode flags, or invoking the Application /// Error pop-up message box. /// /// /// /// /// /// /// The SetUnhandledExceptionFilter function returns the address of the previous exception filter established with the /// function. A NULL return value means that there is no current top-level exception handler. /// // LPTOP_LEVEL_EXCEPTION_FILTER WINAPI SetUnhandledExceptionFilter( _In_ LPTOP_LEVEL_EXCEPTION_FILTER lpTopLevelExceptionFilter); https://msdn.microsoft.com/en-us/library/windows/desktop/ms680634(v=vs.85).aspx [DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "ms680634")] public static extern PTOP_LEVEL_EXCEPTION_FILTER SetUnhandledExceptionFilter(PTOP_LEVEL_EXCEPTION_FILTER lpTopLevelExceptionFilter); /// Undocumented. /// Size of the failed allocation. [DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "")] public static extern void TerminateProcessOnMemoryExhaustion(SizeT FailedAllocationSize); /// /// An application-defined function that passes unhandled exceptions to the debugger, if the process is being debugged. Otherwise, it /// optionally displays an Application Error message box and causes the exception handler to be executed. This function can be /// called only from within the filter expression of an exception handler. /// /// /// A pointer to an EXCEPTION_POINTERS structure that specifies a description of the exception and the processor context at /// the time of the exception. This pointer is the return value of a call to the GetExceptionInformation function. /// /// /// The function returns one of the following values. /// /// /// /// Return code/value /// Description /// /// /// EXCEPTION_CONTINUE_SEARCH0x0 /// The process is being debugged, so the exception should be passed (as second chance) to the application's debugger. /// /// /// EXCEPTION_EXECUTE_HANDLER0x1 /// /// If the SEM_NOGPFAULTERRORBOX flag was specified in a previous call to SetErrorMode, no Application Error message box is /// displayed. The function returns control to the exception handler, which is free to take any appropriate action. /// /// /// /// /// // LONG WINAPI UnhandledExceptionFilter( _In_ struct _EXCEPTION_POINTERS *ExceptionInfo); https://msdn.microsoft.com/en-us/library/windows/desktop/ms681401(v=vs.85).aspx [DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "ms681401")] public static extern EXCEPTION_FLAG UnhandledExceptionFilter(in EXCEPTION_POINTERS ExceptionInfo); /// /// Contains an exception record with a machine-independent description of an exception and a context record with a machine-dependent /// description of the processor context at the time of the exception. /// // typedef struct _EXCEPTION_POINTERS { PEXCEPTION_RECORD ExceptionRecord; PCONTEXT ContextRecord;} EXCEPTION_POINTERS, *PEXCEPTION_POINTERS; [PInvokeData("WinNT.h", MSDNShortId = "ms679331")] [StructLayout(LayoutKind.Sequential)] public struct EXCEPTION_POINTERS { /// A pointer to an EXCEPTION_RECORD structure that contains a machine-independent description of the exception. public IntPtr ExceptionRecord; /// /// A pointer to a CONTEXT structure that contains a processor-specific description of the state of the processor at the /// time of the exception. /// public IntPtr ContextRecord; } /// Describes an exception. // typedef struct _EXCEPTION_RECORD { DWORD ExceptionCode; DWORD ExceptionFlags; struct _EXCEPTION_RECORD *ExceptionRecord; PVOID // ExceptionAddress; DWORD NumberParameters; ULONG_PTR ExceptionInformation[EXCEPTION_MAXIMUM_PARAMETERS];} EXCEPTION_RECORD, *PEXCEPTION_RECORD; [PInvokeData("WinNT.h", MSDNShortId = "aa363082")] [StructLayout(LayoutKind.Sequential)] public struct EXCEPTION_RECORD { /// /// The exception flags. This member can be either zero, indicating a continuable exception, or EXCEPTION_NONCONTINUABLE /// indicating a noncontinuable exception. Any attempt to continue execution after a noncontinuable exception causes the /// EXCEPTION_NONCONTINUABLE_EXCEPTION exception. /// public uint ExceptionCode; /// /// The exception flags. This member can be either zero, indicating a continuable exception, or EXCEPTION_NONCONTINUABLE /// indicating a noncontinuable exception. Any attempt to continue execution after a noncontinuable exception causes the /// EXCEPTION_NONCONTINUABLE_EXCEPTION exception. /// public EXCEPTION_FLAG ExceptionFlags; /// /// A pointer to an associated EXCEPTION_RECORD structure. Exception records can be chained together to provide additional /// information when nested exceptions occur. /// public IntPtr ExceptionRecord; /// The address where the exception occurred. public IntPtr ExceptionAddress; /// /// The number of parameters associated with the exception. This is the number of defined elements in the /// ExceptionInformation array. /// public uint NumberParameters; /// /// /// An array of additional arguments that describe the exception. The RaiseException function can specify this array of /// arguments. For most exception codes, the array elements are undefined. The following table describes the exception codes /// whose array elements are defined. /// /// /// /// Exception code /// Meaning /// /// /// EXCEPTION_ACCESS_VIOLATION /// /// The first element of the array contains a read-write flag that indicates the type of operation that caused the access /// violation. If this value is zero, the thread attempted to read the inaccessible data. If this value is 1, the thread /// attempted to write to an inaccessible address. If this value is 8, the thread causes a user-mode data execution prevention /// (DEP) violation.The second array element specifies the virtual address of the inaccessible data. /// /// /// /// EXCEPTION_IN_PAGE_ERROR /// /// The first element of the array contains a read-write flag that indicates the type of operation that caused the access /// violation. If this value is zero, the thread attempted to read the inaccessible data. If this value is 1, the thread /// attempted to write to an inaccessible address. If this value is 8, the thread causes a user-mode data execution prevention /// (DEP) violation. The second array element specifies the virtual address of the inaccessible data.The third array element /// specifies the underlying NTSTATUS code that resulted in the exception. /// /// /// /// [MarshalAs(UnmanagedType.ByValArray, SizeConst = EXCEPTION_MAXIMUM_PARAMETERS, ArraySubType = UnmanagedType.SysUInt)] public UIntPtr[] ExceptionInformation; } /// A safe handle for continue handler handles. /// public class SafeContinueHandlerHandle : GenericSafeHandle { /// Initializes a new instance of the class. public SafeContinueHandlerHandle() : this(IntPtr.Zero) { } /// Initializes a new instance of the class. /// The handle. public SafeContinueHandlerHandle(IntPtr handle) : base(handle, RemoveVectoredContinueHandler) { } } /// A safe handle for exception handler handles. /// public class SafeExceptionHandlerHandle : GenericSafeHandle { /// Initializes a new instance of the class. public SafeExceptionHandlerHandle() : this(IntPtr.Zero) { } /// Initializes a new instance of the class. /// The handle. public SafeExceptionHandlerHandle(IntPtr handle) : base(handle, RemoveVectoredExceptionHandler) { } } } }