100's of new methods to Kernel32

pull/10/head
David Hall 2018-05-13 21:41:49 -06:00
parent eb5285043b
commit 5d907ff3a3
59 changed files with 44409 additions and 2469 deletions

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,278 @@
using System;
using System.Runtime.InteropServices;
using System.Text;
namespace Vanara.PInvoke
{
public static partial class Kernel32
{
/// <summary>Flags specifying time format options.</summary>
[Flags]
public enum TIME_FORMAT : uint
{
/// <summary>Do not use minutes or seconds.</summary>
TIME_NOMINUTESORSECONDS = 1,
/// <summary>Do not use seconds.</summary>
TIME_NOSECONDS = 2,
/// <summary>Do not use a time marker.</summary>
TIME_NOTIMEMARKER = 4,
/// <summary>Always use a 24-hour time format.</summary>
TIME_FORCE24HOURFORMAT = 8,
/// <summary>
/// Windows Me/98, Windows 2000: System default Windows ANSI code page (ACP) instead of the locale code page used for string translation. See Code
/// Page Identifiers for a list of ANSI and other code pages.
/// </summary>
LOCAL_USE_CP_ACP = 0x40000000,
/// <summary>
/// No user override. In several functions, for example, GetLocaleInfo and GetLocaleInfoEx, this constant causes the function to bypass any user
/// override and use the system default value for any other constant specified in the function call. The information is retrieved from the locale
/// database, even if the identifier indicates the current locale and the user has changed some of the values using the Control Panel, or if an
/// application has changed these values by using SetLocaleInfo. If this constant is not specified, any values that the user has configured from the
/// Control Panel or that an application has configured using SetLocaleInfo take precedence over the database settings for the current system default locale.
/// </summary>
LOCALE_NOUSEROVERRIDE = 0x80000000
}
/// <summary>
/// Formats a date as a date string for a locale specified by the locale identifier. The function formats either a specified date or the local system date.
/// </summary>
/// <param name="Locale">
/// Locale identifier that specifies the locale this function formats the date string for. You can use the <c>MAKELCID</c> macro to create a locale
/// identifier or use one of the following predefined values.
/// </param>
/// <param name="dwFlags">Flags specifying date format options. For detailed definitions, see the dwFlags parameter of <c>GetDateFormatEx</c>.</param>
/// <param name="lpDate">
/// Pointer to a <c>SYSTEMTIME</c> structure that contains the date information to format. The application sets this parameter to <c>NULL</c> if the
/// function is to use the current local system date.
/// </param>
/// <param name="lpFormat">
/// <para>
/// Pointer to a format picture string that is used to form the date. Possible values for the format picture string are defined in Day, Month, Year, and
/// Era Format Pictures.
/// </para>
/// <para>
/// The function uses the specified locale only for information not specified in the format picture string, for example, the day and month names for the
/// locale. The application can set this parameter to <c>NULL</c> to format the string according to the date format for the specified locale.
/// </para>
/// </param>
/// <param name="lpDateStr">Pointer to a buffer in which this function retrieves the formatted date string.</param>
/// <param name="cchDate">
/// Size, in characters, of the lpDateStr buffer. The application can set this parameter to 0 to return the buffer size required to hold the formatted
/// date string. In this case, the buffer indicated by lpDateStr is not used.
/// </param>
/// <returns>
/// <para>
/// Returns the number of characters written to the lpDateStr buffer if successful. If the cchDate parameter is set to 0, the function returns the number
/// of characters required to hold the formatted date string, including the terminating null character.
/// </para>
/// <para>
/// The function returns 0 if it does not succeed. To get extended error information, the application can call <c>GetLastError</c>, which can return one
/// of the following error codes:
/// </para>
/// </returns>
// int GetDateFormat( _In_ LCID Locale, _In_ DWORD dwFlags, _In_opt_ const SYSTEMTIME *lpDate, _In_opt_ LPCTSTR lpFormat, _Out_opt_ LPTSTR lpDateStr,
// _In_ int cchDate); https://msdn.microsoft.com/en-us/library/windows/desktop/dd318086(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)]
[PInvokeData("Datetimeapi.h", MSDNShortId = "dd318086")]
public static extern int GetDateFormat(uint Locale, DATE_FORMAT dwFlags, [In] ref SYSTEMTIME lpDate, [In] string lpFormat, [Out] StringBuilder lpDateStr, int cchDate);
/// <summary>Formats a date as a date string for a locale specified by name. The function formats either a specified date or the local system date.</summary>
/// <param name="lpLocaleName">Pointer to a locale name, or one of the following predefined values.</param>
/// <param name="dwFlags">
/// <para>
/// Flags specifying various function options that can be set if lpFormat is set to <c>NULL</c>. The application can specify a combination of the
/// following values and LOCALE_USE_CP_ACP or LOCALE_NOUSEROVERRIDE.
/// </para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Value</term>
/// <term>Meaning</term>
/// </listheader>
/// <item>
/// <term>DATE_AUTOLAYOUT</term>
/// <term>
/// Windows 7 and later: Detect the need for right-to-left and left-to-right reading layout using the locale and calendar information, and add marks
/// accordingly. This value cannot be used with DATE_LTRREADING or DATE_RTLREADING. DATE_AUTOLAYOUT is preferred over DATE_LTRREADING and DATE_RTLREADING
/// because it uses the locales and calendars to determine the correct addition of marks.
/// </term>
/// </item>
/// <item>
/// <term>DATE_LONGDATE</term>
/// <term>Use the long date format. This value cannot be used with DATE_MONTHDAY, DATE_SHORTDATE, or DATE_YEARMONTH.</term>
/// </item>
/// <item>
/// <term>DATE_LTRREADING</term>
/// <term>Add marks for left-to-right reading layout. This value cannot be used with DATE_RTLREADING.</term>
/// </item>
/// <item>
/// <term>DATE_RTLREADING</term>
/// <term>Add marks for right-to-left reading layout. This value cannot be used with DATE_LTRREADING</term>
/// </item>
/// <item>
/// <term>DATE_SHORTDATE</term>
/// <term>Use the short date format. This is the default. This value cannot be used with DATE_MONTHDAY, DATE_LONGDATE, or DATE_YEARMONTH.</term>
/// </item>
/// <item>
/// <term>DATE_USE_ALT_CALENDAR</term>
/// <term>
/// Use the alternate calendar, if one exists, to format the date string. If this flag is set, the function uses the default format for that alternate
/// calendar, rather than using any user overrides. The user overrides will be used only in the event that there is no default format for the specified
/// alternate calendar.
/// </term>
/// </item>
/// <item>
/// <term>DATE_YEARMONTH</term>
/// <term>Windows Vista: Use the year/month format. This value cannot be used with DATE_MONTHDAY, DATE_SHORTDATE, or DATE_LONGDATE.</term>
/// </item>
/// <item>
/// <term>DATE_MONTHDAY</term>
/// <term>
/// Windows 10: Use the combination of month and day formats appropriate for the specified locale. This value cannot be used with DATE_YEARMONTH,
/// DATE_SHORTDATE, or DATE_LONGDATE.
/// </term>
/// </item>
/// </list>
/// </para>
/// <para>
/// If the application does not specify DATE_YEARMONTH, DATE_MONTHDAY, DATE_SHORTDATE, or DATE_LONGDATE, and lpFormat is set to <c>NULL</c>,
/// DATE_SHORTDATE is the default.
/// </para>
/// </param>
/// <param name="lpDate">
/// Pointer to a <c>SYSTEMTIME</c> structure that contains the date information to format. The application can set this parameter to <c>NULL</c> if the
/// function is to use the current local system date.
/// </param>
/// <param name="lpFormat">
/// <para>
/// Pointer to a format picture string that is used to form the date. Possible values for the format picture string are defined in Day, Month, Year, and
/// Era Format Pictures.
/// </para>
/// <para>For example, to get the date string "Wed, Aug 31 94", the application uses the picture string "ddd',' MMM dd yy".</para>
/// <para>
/// The function uses the specified locale only for information not specified in the format picture string, for example, the day and month names for the
/// locale. The application can set this parameter to <c>NULL</c> to format the string according to the date format for the specified locale.
/// </para>
/// </param>
/// <param name="lpDateStr">Pointer to a buffer in which this function retrieves the formatted date string.</param>
/// <param name="cchDate">
/// Size, in characters, of the lpDateStr buffer. The application can set this parameter to 0 to return the buffer size required to hold the formatted
/// date string. In this case, the buffer indicated by lpDateStr is not used.
/// </param>
/// <param name="lpCalendar">Reserved; must set to <c>NULL</c>.</param>
/// <returns>
/// <para>
/// Returns the number of characters written to the lpDateStr buffer if successful. If the cchDate parameter is set to 0, the function returns the number
/// of characters required to hold the formatted date string, including the terminating null character.
/// </para>
/// <para>
/// This function returns 0 if it does not succeed. To get extended error information, the application can call <c>GetLastError</c>, which can return one
/// of the following error codes:
/// </para>
/// </returns>
// int GetDateFormatEx( _In_opt_ LPCWSTR lpLocaleName, _In_ DWORD dwFlags, _In_opt_ const SYSTEMTIME *lpDate, _In_opt_ LPCWSTR lpFormat, _Out_opt_ LPWSTR
// lpDateStr, _In_ int cchDate, _In_opt_ LPCWSTR lpCalendar); https://msdn.microsoft.com/en-us/library/windows/desktop/dd318088(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
[PInvokeData("Datetimeapi.h", MSDNShortId = "dd318088")]
public static extern int GetDateFormatEx(string lpLocaleName, DATE_FORMAT dwFlags, [In] ref SYSTEMTIME lpDate, [In] string lpFormat, [Out] StringBuilder lpDateStr, int cchDate);
/// <summary>
/// Formats time as a time string for a locale specified by identifier. The function formats either a specified time or the local system time.
/// </summary>
/// <param name="Locale">
/// Locale identifier that specifies the locale. You can use the <c>MAKELCID</c> macro to create a locale identifier or use one of the following
/// predefined values.
/// </param>
/// <param name="dwFlags">Flags specifying time format options. For detailed definitions see the dwFlags parameter of <c>GetTimeFormatEx</c>.</param>
/// <param name="lpTime">
/// Pointer to a <c>SYSTEMTIME</c> structure that contains the time information to format. The application can set this parameter to <c>NULL</c> if the
/// function is to use the current local system time.
/// </param>
/// <param name="lpFormat">
/// Pointer to a format picture to use to format the time string. If the application sets this parameter to <c>NULL</c>, the function formats the string
/// according to the time format of the specified locale. If the application does not set the parameter to <c>NULL</c>, the function uses the locale only
/// for information not specified in the format picture string, for example, the locale-specific time markers. For information about the format picture
/// string, see the Remarks section.
/// </param>
/// <param name="lpTimeStr">Pointer to a buffer in which this function retrieves the formatted time string.</param>
/// <param name="cchTime">
/// Size, in TCHAR values, for the time string buffer indicated by lpTimeStr. Alternatively, the application can set this parameter to 0. In this case,
/// the function returns the required size for the time string buffer, and does not use the lpTimeStr parameter.
/// </param>
/// <returns>
/// <para>
/// Returns the number of TCHAR values retrieved in the buffer indicated by lpTimeStr. If the cchTime parameter is set to 0, the function returns the
/// size of the buffer required to hold the formatted time string, including a terminating null character.
/// </para>
/// <para>
/// This function returns 0 if it does not succeed. To get extended error information, the application can call <c>GetLastError</c>, which can return one
/// of the following error codes:
/// </para>
/// </returns>
// int GetTimeFormat( _In_ LCID Locale, _In_ DWORD dwFlags, _In_opt_ const SYSTEMTIME *lpTime, _In_opt_ LPCTSTR lpFormat, _Out_opt_ LPTSTR lpTimeStr,
// _In_ int cchTime); https://msdn.microsoft.com/en-us/library/windows/desktop/dd318130(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)]
[PInvokeData("Datetimeapi.h", MSDNShortId = "dd318130")]
public static extern int GetTimeFormat(uint Locale, TIME_FORMAT dwFlags, [In] ref SYSTEMTIME lpTime, [In] string lpFormat, [Out] StringBuilder lpTimeStr, int cchTime);
/// <summary>Formats time as a time string for a locale specified by name. The function formats either a specified time or the local system time.</summary>
/// <param name="lpLocaleName">Pointer to a locale name, or one of the following predefined values.</param>
/// <param name="dwFlags">
/// <para>Flags specifying time format options. The application can specify a combination of the following values and LOCALE_USE_CP_ACP or LOCALE_NOUSEROVERRIDE.</para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Value</term>
/// <term>Meaning</term>
/// </listheader>
/// <item>
/// <term>TIME_NOMINUTESORSECONDS</term>
/// <term>Do not use minutes or seconds.</term>
/// </item>
/// <item>
/// <term>TIME_NOSECONDS</term>
/// <term>Do not use seconds.</term>
/// </item>
/// <item>
/// <term>TIME_NOTIMEMARKER</term>
/// <term>Do not use a time marker.</term>
/// </item>
/// <item>
/// <term>TIME_FORCE24HOURFORMAT</term>
/// <term>Always use a 24-hour time format.</term>
/// </item>
/// </list>
/// </para>
/// </param>
/// <param name="lpTime">
/// Pointer to a <c>SYSTEMTIME</c> structure that contains the time information to format. The application can set this parameter to <c>NULL</c> if the
/// function is to use the current local system time.
/// </param>
/// <param name="lpFormat">
/// Pointer to a format picture to use to format the time string. If the application sets this parameter to <c>NULL</c>, the function formats the string
/// according to the time format of the specified locale. If the application does not set the parameter to <c>NULL</c>, the function uses the locale only
/// for information not specified in the format picture string, for example, the locale-specific time markers. For information about the format picture
/// string, see the Remarks section.
/// </param>
/// <param name="lpTimeStr">Pointer to a buffer in which this function retrieves the formatted time string.</param>
/// <param name="cchTime">
/// Size, in characters, for the time string buffer indicated by lpTimeStr. Alternatively, the application can set this parameter to 0. In this case, the
/// function returns the required size for the time string buffer, and does not use the lpTimeStr parameter.
/// </param>
/// <returns>
/// <para>
/// Returns the number of characters retrieved in the buffer indicated by lpTimeStr. If the cchTime parameter is set to 0, the function returns the size
/// of the buffer required to hold the formatted time string, including a terminating null character.
/// </para>
/// <para>
/// This function returns 0 if it does not succeed. To get extended error information, the application can call <c>GetLastError</c>, which can return one
/// of the following error codes:
/// </para>
/// </returns>
// int GetTimeFormatEx( _In_opt_ LPCWSTR lpLocaleName, _In_ DWORD dwFlags, _In_opt_ const SYSTEMTIME *lpTime, _In_opt_ LPCWSTR lpFormat, _Out_opt_ LPWSTR
// lpTimeStr, _In_ int cchTime); https://msdn.microsoft.com/en-us/library/windows/desktop/dd318131(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
[PInvokeData("Datetimeapi.h", MSDNShortId = "dd318131")]
public static extern int GetTimeFormatEx(string lpLocaleName, TIME_FORMAT dwFlags, [In] ref SYSTEMTIME lpTime, [In] string lpFormat, [Out] StringBuilder lpTimeStr, int cchTime);
}
}

View File

@ -0,0 +1,585 @@
using System;
using System.Runtime.InteropServices;
namespace Vanara.PInvoke
{
public static partial class Kernel32
{
/// <summary>A pointer to the starting address of the thread.</summary>
/// <param name="lpThreadParameter">
/// A pointer to a variable to be passed as the lpParameter parameter to the function pointed to by the lpCallbackAddress parameter.
/// </param>
/// <returns>Zero if successfull. Otherwise, returns an error code.</returns>
public delegate uint PTHREAD_START_ROUTINE(IntPtr lpThreadParameter);
/// <summary>The options to continue the thread that reported the debugging event.</summary>
public enum DEBUG_CONTINUE : uint
{
/// <summary>
/// If the thread specified by the dwThreadId parameter previously reported an EXCEPTION_DEBUG_EVENT debugging event, the function stops all
/// exception processing and continues the thread and the exception is marked as handled. For any other debugging event, this flag simply continues
/// the thread.
/// </summary>
DBG_CONTINUE = 0x00010002,
/// <summary>
/// If the thread specified by dwThreadId previously reported an EXCEPTION_DEBUG_EVENT debugging event, the function continues exception processing.
/// If this is a first-chance exception event, the search and dispatch logic of the structured exception handler is used; otherwise, the process is
/// terminated. For any other debugging event, this flag simply continues the thread.
/// </summary>
DBG_EXCEPTION_NOT_HANDLED = 0x80010001,
/// <summary>
/// Supported in Windows 10, version 1507 or above, this flag causes dwThreadId to replay the existing breaking event after the target continues. By
/// calling the SuspendThread API against dwThreadId, a debugger can resume other threads in the process and later return to the breaking.
/// </summary>
DBG_REPLY_LATER = 0x40010001,
}
/// <summary>The code that identifies the type of debugging event.</summary>
public enum DEBUG_EVENT_CODE : uint
{
/// <summary>Reports a create-process debugging event. The value of u.CreateProcessInfo specifies a CREATE_PROCESS_DEBUG_INFO structure.</summary>
CREATE_PROCESS_DEBUG_EVENT = 3,
/// <summary>Reports a create-thread debugging event. The value of u.CreateThread specifies a CREATE_THREAD_DEBUG_INFO structure.</summary>
CREATE_THREAD_DEBUG_EVENT = 2,
/// <summary>Reports an exception debugging event. The value of u.Exception specifies an EXCEPTION_DEBUG_INFO structure.</summary>
EXCEPTION_DEBUG_EVENT = 1,
/// <summary>Reports an exit-process debugging event. The value of u.ExitProcess specifies an EXIT_PROCESS_DEBUG_INFO structure.</summary>
EXIT_PROCESS_DEBUG_EVENT = 5,
/// <summary>Reports an exit-thread debugging event. The value of u.ExitThread specifies an EXIT_THREAD_DEBUG_INFO structure.</summary>
EXIT_THREAD_DEBUG_EVENT = 4,
/// <summary>Reports a load-dynamic-link-library (DLL) debugging event. The value of u.LoadDll specifies a LOAD_DLL_DEBUG_INFO structure.</summary>
LOAD_DLL_DEBUG_EVENT = 6,
/// <summary>Reports an output-debugging-string debugging event. The value of u.DebugString specifies an OUTPUT_DEBUG_STRING_INFO structure.</summary>
OUTPUT_DEBUG_STRING_EVENT = 8,
/// <summary>Reports a RIP-debugging event (system debugging error). The value of u.RipInfo specifies a RIP_INFO structure.</summary>
RIP_EVENT = 9,
/// <summary>Reports an unload-DLL debugging event. The value of u.UnloadDll specifies an UNLOAD_DLL_DEBUG_INFO structure.</summary>
UNLOAD_DLL_DEBUG_EVENT = 7,
}
/// <summary>Determines whether the specified process is being debugged.</summary>
/// <param name="hProcess">A handle to the process.</param>
/// <param name="pbDebuggerPresent">
/// A pointer to a variable that the function sets to <c>TRUE</c> if the specified process is being debugged, or <c>FALSE</c> otherwise.
/// </param>
/// <returns>
/// <para>If the function succeeds, the return value is nonzero.</para>
/// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// BOOL WINAPI CheckRemoteDebuggerPresent( _In_ HANDLE hProcess, _Inout_ PBOOL pbDebuggerPresent); https://msdn.microsoft.com/en-us/library/windows/desktop/ms679280(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms679280")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool CheckRemoteDebuggerPresent([In] IntPtr hProcess, [MarshalAs(UnmanagedType.Bool)] ref bool pbDebuggerPresent);
/// <summary>Enables a debugger to continue a thread that previously reported a debugging event.</summary>
/// <param name="dwProcessId">The process identifier of the process to continue.</param>
/// <param name="dwThreadId">
/// The thread identifier of the thread to continue. The combination of process identifier and thread identifier must identify a thread that has
/// previously reported a debugging event.
/// </param>
/// <param name="dwContinueStatus">
/// <para>The options to continue the thread that reported the debugging event.</para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Value</term>
/// <term>Meaning</term>
/// </listheader>
/// <item>
/// <term>DBG_CONTINUE0x00010002L</term>
/// <term>
/// If the thread specified by the dwThreadId parameter previously reported an EXCEPTION_DEBUG_EVENT debugging event, the function stops all exception
/// processing and continues the thread and the exception is marked as handled. For any other debugging event, this flag simply continues the thread.
/// </term>
/// </item>
/// <item>
/// <term>DBG_EXCEPTION_NOT_HANDLED0x80010001L</term>
/// <term>
/// If the thread specified by dwThreadId previously reported an EXCEPTION_DEBUG_EVENT debugging event, the function continues exception processing. If
/// this is a first-chance exception event, the search and dispatch logic of the structured exception handler is used; otherwise, the process is
/// terminated. For any other debugging event, this flag simply continues the thread.
/// </term>
/// </item>
/// <item>
/// <term>DBG_REPLY_LATER0x40010001L</term>
/// <term>
/// Supported in Windows 10, version 1507 or above, this flag causes dwThreadId to replay the existing breaking event after the target continues. By
/// calling the SuspendThread API against dwThreadId, a debugger can resume other threads in the process and later return to the breaking.
/// </term>
/// </item>
/// </list>
/// </para>
/// </param>
/// <returns>
/// <para>If the function succeeds, the return value is nonzero.</para>
/// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// BOOL WINAPI ContinueDebugEvent( _In_ DWORD dwProcessId, _In_ DWORD dwThreadId, _In_ DWORD dwContinueStatus); https://msdn.microsoft.com/en-us/library/windows/desktop/ms679285(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms679285")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool ContinueDebugEvent(uint dwProcessId, uint dwThreadId, DEBUG_CONTINUE dwContinueStatus);
/// <summary>Enables a debugger to attach to an active process and debug it.</summary>
/// <param name="dwProcessId">
/// The identifier for the process to be debugged. The debugger is granted debugging access to the process as if it created the process with the
/// <c>DEBUG_ONLY_THIS_PROCESS</c> flag. For more information, see the Remarks section of this topic.
/// </param>
/// <returns>
/// <para>If the function succeeds, the return value is nonzero.</para>
/// <para>If the function fails, the return value is 0 (zero). To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// BOOL WINAPI DebugActiveProcess( _In_ DWORD dwProcessId); https://msdn.microsoft.com/en-us/library/windows/desktop/ms679295(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms679295")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool DebugActiveProcess(uint dwProcessId);
/// <summary>Stops the debugger from debugging the specified process.</summary>
/// <param name="dwProcessId">The identifier of the process to stop debugging.</param>
/// <returns>
/// <para>If the function succeeds, the return value is nonzero.</para>
/// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// BOOL WINAPI DebugActiveProcessStop( _In_ DWORD dwProcessId); https://msdn.microsoft.com/en-us/library/windows/desktop/ms679296(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms679296")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool DebugActiveProcessStop(uint dwProcessId);
/// <summary>
/// <para>Causes a breakpoint exception to occur in the current process. This allows the calling thread to signal the debugger to handle the exception.</para>
/// <para>To cause a breakpoint exception in another process, use the <c>DebugBreakProcess</c> function.</para>
/// </summary>
/// <returns>This function does not return a value.</returns>
// void WINAPI DebugBreak(void); https://msdn.microsoft.com/en-us/library/windows/desktop/ms679297(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms679297")]
public static extern void DebugBreak();
/// <summary>Determines whether the calling process is being debugged by a user-mode debugger.</summary>
/// <returns>
/// <para>If the current process is running in the context of a debugger, the return value is nonzero.</para>
/// <para>If the current process is not running in the context of a debugger, the return value is zero.</para>
/// </returns>
// BOOL WINAPI IsDebuggerPresent(void); https://msdn.microsoft.com/en-us/library/windows/desktop/ms680345(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms680345")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool IsDebuggerPresent();
/// <summary>Sends a string to the debugger for display.</summary>
/// <param name="lpOutputString">The null-terminated string to be displayed.</param>
/// <returns>This function does not return a value.</returns>
// void WINAPI OutputDebugString( _In_opt_ LPCTSTR lpOutputString); https://msdn.microsoft.com/en-us/library/windows/desktop/aa363362(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, CharSet = CharSet.Auto)]
[PInvokeData("WinBase.h", MSDNShortId = "aa363362")]
public static extern void OutputDebugString([In] string lpOutputString);
/// <summary>Waits for a debugging event to occur in a process being debugged.</summary>
/// <param name="lpDebugEvent">A pointer to a <c>DEBUG_EVENT</c> structure that receives information about the debugging event.</param>
/// <param name="dwMilliseconds">
/// The number of milliseconds to wait for a debugging event. If this parameter is zero, the function tests for a debugging event and returns
/// immediately. If the parameter is INFINITE, the function does not return until a debugging event has occurred.
/// </param>
/// <returns>
/// <para>If the function succeeds, the return value is nonzero.</para>
/// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// BOOL WINAPI WaitForDebugEvent( _Out_ LPDEBUG_EVENT lpDebugEvent, _In_ DWORD dwMilliseconds); https://msdn.microsoft.com/en-us/library/windows/desktop/ms681423(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms681423")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool WaitForDebugEvent(out DEBUG_EVENT lpDebugEvent, uint dwMilliseconds);
/// <summary>
/// <para>
/// [Some information relates to pre-released product which may be substantially modified before it's commercially released. Microsoft makes no
/// warranties, express or implied, with respect to the information provided here.]
/// </para>
/// <para>Waits for a debugging event to occur in a process being debugged.</para>
/// </summary>
/// <param name="lpDebugEvent">A pointer to a <c>DEBUG_EVENT</c> structure that receives information about the debugging event.</param>
/// <param name="dwMilliseconds">
/// The number of milliseconds to wait for a debugging event. If this parameter is zero, the function tests for a debugging event and returns
/// immediately. If the parameter is INFINITE, the function does not return until a debugging event has occurred.
/// </param>
/// <returns>
/// <para>If the function succeeds, the return value is nonzero.</para>
/// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// BOOL WINAPI WaitForDebugEventEx( _Out_ LPDEBUG_EVENT lpDebugEvent, _In_ DWORD dwMilliseconds); https://msdn.microsoft.com/en-us/library/windows/desktop/mt171594(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "mt171594")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool WaitForDebugEventEx(out DEBUG_EVENT lpDebugEvent, uint dwMilliseconds);
/// <summary>Describes a debugging event.</summary>
// typedef struct _DEBUG_EVENT { DWORD dwDebugEventCode; DWORD dwProcessId; DWORD dwThreadId; union { EXCEPTION_DEBUG_INFO Exception;
// CREATE_THREAD_DEBUG_INFO CreateThread; CREATE_PROCESS_DEBUG_INFO CreateProcessInfo; EXIT_THREAD_DEBUG_INFO ExitThread; EXIT_PROCESS_DEBUG_INFO
// ExitProcess; LOAD_DLL_DEBUG_INFO LoadDll; UNLOAD_DLL_DEBUG_INFO UnloadDll; OUTPUT_DEBUG_STRING_INFO DebugString; RIP_INFO RipInfo; } u;} DEBUG_EVENT,
// *LPDEBUG_EVENT;// https://msdn.microsoft.com/en-us/library/windows/desktop/ms679308(v=vs.85).aspx
[PInvokeData("WinBase.h", MSDNShortId = "ms679308")]
[StructLayout(LayoutKind.Sequential)]
public struct DEBUG_EVENT
{
/// <summary>
/// <para>Type: <c>DWORD</c></para>
/// <para>The code that identifies the type of debugging event. This member can be one of the following values.</para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Value</term>
/// <term>Meaning</term>
/// </listheader>
/// <item>
/// <term>CREATE_PROCESS_DEBUG_EVENT3</term>
/// <term>Reports a create-process debugging event. The value of u.CreateProcessInfo specifies a CREATE_PROCESS_DEBUG_INFO structure.</term>
/// </item>
/// <item>
/// <term>CREATE_THREAD_DEBUG_EVENT2</term>
/// <term>Reports a create-thread debugging event. The value of u.CreateThread specifies a CREATE_THREAD_DEBUG_INFO structure.</term>
/// </item>
/// <item>
/// <term>EXCEPTION_DEBUG_EVENT1</term>
/// <term>Reports an exception debugging event. The value of u.Exception specifies an EXCEPTION_DEBUG_INFO structure.</term>
/// </item>
/// <item>
/// <term>EXIT_PROCESS_DEBUG_EVENT5</term>
/// <term>Reports an exit-process debugging event. The value of u.ExitProcess specifies an EXIT_PROCESS_DEBUG_INFO structure.</term>
/// </item>
/// <item>
/// <term>EXIT_THREAD_DEBUG_EVENT4</term>
/// <term>Reports an exit-thread debugging event. The value of u.ExitThread specifies an EXIT_THREAD_DEBUG_INFO structure.</term>
/// </item>
/// <item>
/// <term>LOAD_DLL_DEBUG_EVENT6</term>
/// <term>Reports a load-dynamic-link-library (DLL) debugging event. The value of u.LoadDll specifies a LOAD_DLL_DEBUG_INFO structure.</term>
/// </item>
/// <item>
/// <term>OUTPUT_DEBUG_STRING_EVENT8</term>
/// <term>Reports an output-debugging-string debugging event. The value of u.DebugString specifies an OUTPUT_DEBUG_STRING_INFO structure.</term>
/// </item>
/// <item>
/// <term>RIP_EVENT9</term>
/// <term>Reports a RIP-debugging event (system debugging error). The value of u.RipInfo specifies a RIP_INFO structure.</term>
/// </item>
/// <item>
/// <term>UNLOAD_DLL_DEBUG_EVENT7</term>
/// <term>Reports an unload-DLL debugging event. The value of u.UnloadDll specifies an UNLOAD_DLL_DEBUG_INFO structure.</term>
/// </item>
/// </list>
/// </para>
/// </summary>
public DEBUG_EVENT_CODE dwDebugEventCode;
/// <summary>
/// <para>Type: <c>DWORD</c></para>
/// <para>
/// The identifier of the process in which the debugging event occurred. A debugger uses this value to locate the debugger's per-process structure.
/// These values are not necessarily small integers that can be used as table indices.
/// </para>
/// </summary>
public uint dwProcessId;
/// <summary>
/// <para>Type: <c>DWORD</c></para>
/// <para>
/// The identifier of the thread in which the debugging event occurred. A debugger uses this value to locate the debugger's per-thread structure.
/// These values are not necessarily small integers that can be used as table indices.
/// </para>
/// </summary>
public uint dwThreadId;
/// <summary>
/// Any additional information relating to the debugging event. This union takes on the type and value appropriate to the type of debugging event, as
/// described in the <c>dwDebugEventCode</c> member.
/// </summary>
public EXCEPTION_INFO u;
/// <summary>This union takes on the type and value appropriate to the type of debugging event, as described in the <c>dwDebugEventCode</c> member.</summary>
[PInvokeData("WinBase.h", MSDNShortId = "ms679308")]
[StructLayout(LayoutKind.Explicit)]
public struct EXCEPTION_INFO
{
/// <summary>If the dwDebugEventCode is EXCEPTION_DEBUG_EVENT (1), u.Exception specifies an EXCEPTION_DEBUG_INFO structure.</summary>
[FieldOffset(0)]
public EXCEPTION_DEBUG_INFO Exception;
/// <summary>If the dwDebugEventCode is CREATE_THREAD_DEBUG_EVENT (2), u.CreateThread specifies an CREATE_THREAD_DEBUG_INFO structure.</summary>
[FieldOffset(0)]
public CREATE_THREAD_DEBUG_INFO CreateThread;
/// <summary>If the dwDebugEventCode is CREATE_PROCESS_DEBUG_EVENT (3), u.CreateProcessInfo specifies an CREATE_PROCESS_DEBUG_INFO structure.</summary>
[FieldOffset(0)]
public CREATE_PROCESS_DEBUG_INFO CreateProcessInfo;
/// <summary>If the dwDebugEventCode is EXIT_THREAD_DEBUG_EVENT (4), u.ExitThread specifies an EXIT_THREAD_DEBUG_INFO structure.</summary>
[FieldOffset(0)]
public EXIT_THREAD_DEBUG_INFO ExitThread;
/// <summary>If the dwDebugEventCode is EXIT_PROCESS_DEBUG_EVENT (5), u.ExitProcess specifies an EXIT_PROCESS_DEBUG_INFO structure.</summary>
[FieldOffset(0)]
public EXIT_PROCESS_DEBUG_INFO ExitProcess;
/// <summary>If the dwDebugEventCode is LOAD_DLL_DEBUG_EVENT (6), u.LoadDll specifies an LOAD_DLL_DEBUG_INFO structure.</summary>
[FieldOffset(0)]
public LOAD_DLL_DEBUG_INFO LoadDll;
/// <summary>If the dwDebugEventCode is UNLOAD_DLL_DEBUG_EVENT (7), u.UnloadDll specifies an UNLOAD_DLL_DEBUG_INFO structure.</summary>
[FieldOffset(0)]
public UNLOAD_DLL_DEBUG_INFO UnloadDll;
/// <summary>If the dwDebugEventCode is OUTPUT_DEBUG_STRING_EVENT (8), u.DebugString specifies an OUTPUT_DEBUG_STRING_INFO structure.</summary>
[FieldOffset(0)]
public OUTPUT_DEBUG_STRING_INFO DebugString;
/// <summary>If the dwDebugEventCode is RIP_EVENT (9), u.RipInfo specifies an RIP_INFO structure.</summary>
[FieldOffset(0)]
public RIP_INFO RipInfo;
/// <summary>Contains exception information that can be used by a debugger.</summary>
// typedef struct _EXCEPTION_DEBUG_INFO { EXCEPTION_RECORD ExceptionRecord; DWORD dwFirstChance;} EXCEPTION_DEBUG_INFO, *LPEXCEPTION_DEBUG_INFO; https://msdn.microsoft.com/en-us/library/windows/desktop/ms679326(v=vs.85).aspx
[PInvokeData("WinBase.h", MSDNShortId = "ms679326")]
[StructLayout(LayoutKind.Sequential)]
public struct EXCEPTION_DEBUG_INFO
{
/// <summary>
/// An <c>EXCEPTION_RECORD</c> structure with information specific to the exception. This includes the exception code, flags, address, a
/// pointer to a related exception, extra parameters, and so on.
/// </summary>
public EXCEPTION_RECORD ExceptionRecord;
/// <summary>
/// A value that indicates whether the debugger has previously encountered the exception specified by the <c>ExceptionRecord</c> member. If
/// the <c>dwFirstChance</c> member is nonzero, this is the first time the debugger has encountered the exception. Debuggers typically handle
/// breakpoint and single-step exceptions when they are first encountered. If this member is zero, the debugger has previously encountered
/// the exception. This occurs only if, during the search for structured exception handlers, either no handler was found or the exception was continued.
/// </summary>
public uint dwFirstChance;
}
/// <summary>Contains thread-creation information that can be used by a debugger.</summary>
// typedef struct _CREATE_THREAD_DEBUG_INFO { HANDLE hThread; LPVOID lpThreadLocalBase; LPTHREAD_START_ROUTINE lpStartAddress;} CREATE_THREAD_DEBUG_INFO,
// *LPCREATE_THREAD_DEBUG_INFO; https://msdn.microsoft.com/en-us/library/windows/desktop/ms679287(v=vs.85).aspx
[PInvokeData("WinBase.h", MSDNShortId = "ms679287")]
[StructLayout(LayoutKind.Sequential)]
public struct CREATE_THREAD_DEBUG_INFO
{
/// <summary>
/// A handle to the thread whose creation caused the debugging event. If this member is <c>NULL</c>, the handle is not valid. Otherwise, the
/// debugger has THREAD_GET_CONTEXT, THREAD_SET_CONTEXT, and THREAD_SUSPEND_RESUME access to the thread, allowing the debugger to read from
/// and write to the registers of the thread and control execution of the thread.
/// </summary>
public IntPtr hThread;
/// <summary>
/// A pointer to a block of data. At offset 0x2C into this block is another pointer, called ThreadLocalStoragePointer, that points to an
/// array of per-module thread local storage blocks. This gives a debugger access to per-thread data in the threads of the process being
/// debugged using the same algorithms that a compiler would use.
/// </summary>
public IntPtr lpThreadLocalBase;
/// <summary>
/// A pointer to the starting address of the thread. This value may only be an approximation of the thread's starting address, because any
/// application with appropriate access to the thread can change the thread's context by using the <c>SetThreadContext</c> function.
/// </summary>
public PTHREAD_START_ROUTINE lpStartAddress;
}
/// <summary>Contains process creation information that can be used by a debugger.</summary>
// typedef struct _CREATE_PROCESS_DEBUG_INFO { HANDLE hFile; HANDLE hProcess; HANDLE hThread; LPVOID lpBaseOfImage; DWORD dwDebugInfoFileOffset;
// DWORD nDebugInfoSize; LPVOID lpThreadLocalBase; LPTHREAD_START_ROUTINE lpStartAddress; LPVOID lpImageName; WORD fUnicode;}
// CREATE_PROCESS_DEBUG_INFO, *LPCREATE_PROCESS_DEBUG_INFO;
[PInvokeData("WinBase.h", MSDNShortId = "ms679286")]
[StructLayout(LayoutKind.Sequential)]
public struct CREATE_PROCESS_DEBUG_INFO
{
/// <summary>
/// <para>
/// A handle to the process's image file. If this member is <c>NULL</c>, the handle is not valid. Otherwise, the debugger can use the member
/// to read from and write to the image file.
/// </para>
/// <para>When the debugger is finished with this file, it should close the handle using the <c>CloseHandle</c> function.</para>
/// </summary>
public IntPtr hFile;
/// <summary>
/// A handle to the process. If this member is <c>NULL</c>, the handle is not valid. Otherwise, the debugger can use the member to read from
/// and write to the process's memory.
/// </summary>
public IntPtr hProcess;
/// <summary>
/// A handle to the initial thread of the process identified by the <c>hProcess</c> member. If <c>hThread</c> param is <c>NULL</c>, the
/// handle is not valid. Otherwise, the debugger has <c>THREAD_GET_CONTEXT</c>, <c>THREAD_SET_CONTEXT</c>, and <c>THREAD_SUSPEND_RESUME</c>
/// access to the thread, allowing the debugger to read from and write to the registers of the thread and to control execution of the thread.
/// </summary>
public IntPtr hThread;
/// <summary>The base address of the executable image that the process is running.</summary>
public IntPtr lpBaseOfImage;
/// <summary>The offset to the debugging information in the file identified by the <c>hFile</c> member.</summary>
public uint dwDebugInfoFileOffset;
/// <summary>The size of the debugging information in the file, in bytes. If this value is zero, there is no debugging information.</summary>
public uint nDebugInfoSize;
/// <summary>
/// A pointer to a block of data. At offset 0x2C into this block is another pointer, called , that points to an array of per-module thread
/// local storage blocks. This gives a debugger access to per-thread data in the threads of the process being debugged using the same
/// algorithms that a compiler would use.
/// </summary>
public IntPtr lpThreadLocalBase;
/// <summary>
/// A pointer to the starting address of the thread. This value may only be an approximation of the thread's starting address, because any
/// application with appropriate access to the thread can change the thread's context by using the <c>SetThreadContext</c> function.
/// </summary>
public PTHREAD_START_ROUTINE lpStartAddress;
/// <summary>
/// <para>
/// A pointer to the file name associated with the <c>hFile</c> member. This parameter may be <c>NULL</c>, or it may contain the address of a
/// string pointer in the address space of the process being debugged. That address may, in turn, either be <c>NULL</c> or point to the
/// actual filename. If <c>fUnicode</c> is a nonzero value, the name string is Unicode; otherwise, it is ANSI.
/// </para>
/// <para>
/// This member is strictly optional. Debuggers must be prepared to handle the case where <c>lpImageName</c> is <c>NULL</c> or *
/// <c>lpImageName</c> (in the address space of the process being debugged) is <c>NULL</c>. Specifically, the system does not provide an
/// image name for a create process event, and will not likely pass an image name for the first DLL event. The system also does not provide
/// this information in the case of debug events that originate from a call to the <c>DebugActiveProcess</c> function.
/// </para>
/// </summary>
public IntPtr lpImageName;
/// <summary>
/// A value that indicates whether a file name specified by the <c>lpImageName</c> member is Unicode or ANSI. A nonzero value indicates
/// Unicode; zero indicates ANSI.
/// </summary>
public ushort fUnicode;
}
/// <summary>Contains the exit code for a terminating process.</summary>
// typedef struct _EXIT_PROCESS_DEBUG_INFO { DWORD dwExitCode;} EXIT_PROCESS_DEBUG_INFO, *LPEXIT_PROCESS_DEBUG_INFO; https://msdn.microsoft.com/en-us/library/windows/desktop/ms679334(v=vs.85).aspx
[PInvokeData("WinBase.h", MSDNShortId = "ms679334")]
[StructLayout(LayoutKind.Sequential)]
public struct EXIT_PROCESS_DEBUG_INFO
{
/// <summary>The exit code for the process.</summary>
public uint dwExitCode;
}
/// <summary>Contains the exit code for a terminating thread.</summary>
// typedef struct _EXIT_THREAD_DEBUG_INFO { DWORD dwExitCode;} EXIT_THREAD_DEBUG_INFO, *LPEXIT_THREAD_DEBUG_INFO; https://msdn.microsoft.com/en-us/library/windows/desktop/ms679335(v=vs.85).aspx
[PInvokeData("WinBase.h", MSDNShortId = "ms679335")]
[StructLayout(LayoutKind.Sequential)]
public struct EXIT_THREAD_DEBUG_INFO
{
/// <summary>The exit code for the thread.</summary>
public uint dwExitCode;
}
/// <summary>Contains information about a dynamic-link library (DLL) that has just been loaded.</summary>
// typedef struct _LOAD_DLL_DEBUG_INFO { HANDLE hFile; LPVOID lpBaseOfDll; DWORD dwDebugInfoFileOffset; DWORD nDebugInfoSize; LPVOID lpImageName;
// WORD fUnicode;} LOAD_DLL_DEBUG_INFO, *LPLOAD_DLL_DEBUG_INFO; https://msdn.microsoft.com/en-us/library/windows/desktop/ms680351(v=vs.85).aspx
[PInvokeData("WinBase.h", MSDNShortId = "ms680351")]
[StructLayout(LayoutKind.Sequential)]
public struct LOAD_DLL_DEBUG_INFO
{
/// <summary>
/// <para>
/// A handle to the loaded DLL. If this member is <c>NULL</c>, the handle is not valid. Otherwise, the member is opened for reading and
/// read-sharing in the context of the debugger.
/// </para>
/// <para>When the debugger is finished with this file, it should close the handle using the <c>CloseHandle</c> function.</para>
/// </summary>
public IntPtr hFile;
/// <summary>A pointer to the base address of the DLL in the address space of the process loading the DLL.</summary>
public IntPtr lpBaseOfDll;
/// <summary>
/// The offset to the debugging information in the file identified by the <c>hFile</c> member, in bytes. The system expects the debugging
/// information to be in CodeView 4.0 format. This format is currently a derivative of Common Object File Format (COFF).
/// </summary>
public uint dwDebugInfoFileOffset;
/// <summary>The size of the debugging information in the file, in bytes. If this member is zero, there is no debugging information.</summary>
public uint nDebugInfoSize;
/// <summary>
/// <para>
/// A pointer to the file name associated with <c>hFile</c>. This member may be <c>NULL</c>, or it may contain the address of a string
/// pointer in the address space of the process being debugged. That address may, in turn, either be <c>NULL</c> or point to the actual
/// filename. If <c>fUnicode</c> is a nonzero value, the name string is Unicode; otherwise, it is ANSI.
/// </para>
/// <para>
/// This member is strictly optional. Debuggers must be prepared to handle the case where <c>lpImageName</c> is <c>NULL</c> or *
/// <c>lpImageName</c> (in the address space of the process being debugged) is <c>NULL</c>. Specifically, the system will never provide an
/// image name for a create process event, and it will not likely pass an image name for the first DLL event. The system will also never
/// provide this information in the case of debugging events that originate from a call to the <c>DebugActiveProcess</c> function.
/// </para>
/// </summary>
public IntPtr lpImageName;
/// <summary>
/// A value that indicates whether a filename specified by <c>lpImageName</c> is Unicode or ANSI. A nonzero value for this member indicates
/// Unicode; zero indicates ANSI.
/// </summary>
public ushort fUnicode;
}
/// <summary>Contains information about a dynamic-link library (DLL) that has just been unloaded.</summary>
// typedef struct _UNLOAD_DLL_DEBUG_INFO { LPVOID lpBaseOfDll;} UNLOAD_DLL_DEBUG_INFO, *LPUNLOAD_DLL_DEBUG_INFO; https://msdn.microsoft.com/en-us/library/windows/desktop/ms681403(v=vs.85).aspx
[PInvokeData("WinBase.h", MSDNShortId = "ms681403")]
[StructLayout(LayoutKind.Sequential)]
public struct UNLOAD_DLL_DEBUG_INFO
{
/// <summary>A pointer to the base address of the DLL in the address space of the process unloading the DLL.</summary>
public IntPtr lpBaseOfDll;
}
/// <summary>Contains the address, format, and length, in bytes, of a debugging string.</summary>
// typedef struct _OUTPUT_DEBUG_STRING_INFO { LPSTR lpDebugStringData; WORD fUnicode; WORD nDebugStringLength;} OUTPUT_DEBUG_STRING_INFO,
// *LPOUTPUT_DEBUG_STRING_INFO;// https://msdn.microsoft.com/en-us/library/windows/desktop/ms680545(v=vs.85).aspx
[PInvokeData("WinBase.h", MSDNShortId = "ms680545")]
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public struct OUTPUT_DEBUG_STRING_INFO
{
/// <summary>
/// The debugging string in the calling process's address space. The debugger can use the <c>ReadProcessMemory</c> function to retrieve the
/// value of the string.
/// </summary>
public string lpDebugStringData;
/// <summary>
/// The format of the debugging string. If this member is zero, the debugging string is ANSI; if it is nonzero, the string is Unicode.
/// </summary>
public ushort fUnicode;
/// <summary>The size of the debugging string, in characters. The length includes the string's terminating null character.</summary>
public ushort nDebugStringLength;
}
/// <summary>Contains the error that caused the RIP debug event.</summary>
// typedef struct _RIP_INFO { DWORD dwError; DWORD dwType;} RIP_INFO, *LPRIP_INFO; https://msdn.microsoft.com/en-us/library/windows/desktop/ms680587(v=vs.85).aspx
[PInvokeData("WinBase.h", MSDNShortId = "ms680587")]
[StructLayout(LayoutKind.Sequential)]
public struct RIP_INFO
{
/// <summary>The error that caused the RIP debug event. For more information, see Error Handling.</summary>
public uint dwError;
/// <summary>
/// <para>Any additional information about the type of error that caused the RIP debug event. This member can be one of the following values.</para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Value</term>
/// <term>Meaning</term>
/// </listheader>
/// <item>
/// <term>SLE_ERROR = 0x00000001</term>
/// <term>Indicates that invalid data was passed to the function that failed. This caused the application to fail.</term>
/// </item>
/// <item>
/// <term>SLE_MINORERROR = 0x00000002</term>
/// <term>Indicates that invalid data was passed to the function, but the error probably will not cause the application to fail.</term>
/// </item>
/// <item>
/// <term>SLE_WARNING = 0x00000003</term>
/// <term>Indicates that potentially invalid data was passed to the function, but the function completed processing.</term>
/// </item>
/// <item>
/// <term>0</term>
/// <term>Indicates that only dwError was set.</term>
/// </item>
/// </list>
/// </para>
/// </summary>
public uint dwType;
}
}
}
}
}

View File

@ -0,0 +1,440 @@
using System;
using System.Runtime.InteropServices;
namespace Vanara.PInvoke
{
public static partial class Kernel32
{
/// <summary>Used by the <see cref="CallEnclave"/> function.</summary>
/// <param name="lpThreadParameter">The thread parameter.</param>
/// <returns>The return thread parameter.</returns>
[PInvokeData("MinWinBase.h")]
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
public delegate IntPtr PENCLAVE_ROUTINE(IntPtr lpThreadParameter);
/// <summary>A flag that indicates whether the enclave permits debugging.</summary>
public enum ENCLAVE_VBS_FLAG : uint
{
/// <summary>The enclave does not permit debugging.</summary>
ENCLAVE_VBS_FLAG_NODEBUG = 0x00000000,
/// <summary>The enclave permits debugging.</summary>
ENCLAVE_VBS_FLAG_DEBUG = 0x00000001,
}
/// <summary>The architecture type of the enclave that you want to create.</summary>
[Flags]
public enum EnclaveType : uint
{
/// <summary>An enclave for the Intel Software Guard Extensions (SGX) architecture extension.</summary>
ENCLAVE_TYPE_SGX = 0x00000001,
/// <summary>A VBS enclave.</summary>
ENCLAVE_TYPE_VBS = 0x00000010,
}
/// <summary>Calls a function within an enclave. <c>CallEnclave</c> can also be called within an enclave to call a function outside of the enclave.</summary>
/// <param name="lpRoutine">The address of the function that you want to call.</param>
/// <param name="lpParameter">The parameter than you want to pass to the function.</param>
/// <param name="fWaitForThread">
/// <para>
/// <c>TRUE</c> if the call to the specified function should block execution until an idle enclave thread becomes available when no idle enclave thread
/// is available. <c>FALSE</c> if the call to the specified function should fail when no idle enclave thread is available.
/// </para>
/// <para>This parameter is ignored when you use <c>CallEnclave</c> within an enclave to call a function that is not in any enclave.</para>
/// </param>
/// <param name="lpReturnValue">The return value of the function, if it is called successfully.</param>
/// <returns><c>TRUE</c> if the specified function was called successfully; otherwise <c>FALSE</c>. To get extended error information, call <c>GetLastError</c>.</returns>
// BOOL WINAPI CallEnclave( _In_ LPENCLAVE_ROUTINE lpRoutine, _In_ LPVOID lpParameter, _In_ BOOL fWaitForThread, _Out_ LPVOID *lpReturnValue); https://msdn.microsoft.com/en-us/library/windows/desktop/mt844231(v=vs.85).aspx
[DllImport(Lib.VertDll, SetLastError = true, ExactSpelling = true)]
[PInvokeData("Enclaveapi.h", MSDNShortId = "mt844231")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool CallEnclave(PENCLAVE_ROUTINE lpRoutine, IntPtr lpParameter, [MarshalAs(UnmanagedType.Bool)] bool fWaitForThread, out IntPtr lpReturnValue);
/// <summary>
/// Creates a new uninitialized enclave. An enclave is an isolated region of code and data within the address space for an application. Only code that
/// runs within the enclave can access data within the same enclave.
/// </summary>
/// <param name="hProcess">A handle to the process for which you want to create an enclave.</param>
/// <param name="lpAddress">The preferred base address of the enclave. Specify <c>NULL</c> to have the operating system assign the base address.</param>
/// <param name="dwSize">The size of the enclave that you want to create, including the size of the code that you will load into the enclave, in bytes.</param>
/// <param name="dwInitialCommittment">
/// <para>The amount of memory to commit for the enclave, in bytes.</para>
/// <para>
/// If the amount of enclave memory available is not sufficient to commit this number of bytes, enclave creation fails. Any memory that remains unused
/// when you initialize the enclave by calling <c>InitializeEnclave</c> is returned to the list of free pages.
/// </para>
/// <para>The value of the dwInitialCommittment parameter must not exceed the value of the dwSize parameter.</para>
/// <para>This parameter is not used for virtualization-based security (VBS) enclaves.</para>
/// </param>
/// <param name="flEnclaveType">
/// <para>The architecture type of the enclave that you want to create. To verify that an enclave type is supported, call <c>IsEnclaveTypeSupported</c>.</para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Value</term>
/// <term>Meaning</term>
/// </listheader>
/// <item>
/// <term>ENCLAVE_TYPE_SGX0x00000001</term>
/// <term>An enclave for the Intel Software Guard Extensions (SGX) architecture extension.</term>
/// </item>
/// <item>
/// <term>ENCLAVE_TYPE_VBS0x00000010</term>
/// <term>A VBS enclave.</term>
/// </item>
/// </list>
/// </para>
/// </param>
/// <param name="lpEnclaveInformation">
/// <para>A pointer to the architecture-specific information to use to create the enclave.</para>
/// <para>For the <c>ENCLAVE_TYPE_SGX</c> enclave type, you must specify a pointer to an <c>ENCLAVE_CREATE_INFO_SGX</c> structure.</para>
/// <para>For the <c>ENCLAVE_TYPE_VBS</c> enclave type, you must specify a pointer to an <c>ENCLAVE_CREATE_INFO_VBS</c> structure.</para>
/// </param>
/// <param name="dwInfoLength">
/// The length of the structure that the lpEnclaveInformation parameter points to, in bytes. For the <c>ENCLAVE_TYPE_SGX</c> enclave type, this value
/// must be 4096. For the <c>ENCLAVE_TYPE_VBS</c> enclave type, this value must be , which is 36 bytes.
/// </param>
/// <param name="lpEnclaveError">
/// An optional pointer to a variable that receives an enclave error code that is architecture-specific. For the <c>ENCLAVE_TYPE_SGX</c> and
/// <c>ENCLAVE_TYPE_VBS</c> enclave types, the lpEnclaveError parameter is not used.
/// </param>
/// <returns>
/// <para>If the function succeeds, the return value is the base address of the created enclave.</para>
/// <para>If the function fails, the return value is <c>NULL</c>. To get extended error information, call <c>GetLastError</c>.</para>
/// <para>For a list of common error codes, see System Error Codes. The following error codes also apply for this function.</para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Return code</term>
/// <term>Description</term>
/// </listheader>
/// <item>
/// <term>ERROR_NOT_SUPPORTED</term>
/// <term>An unsupported enclave type was specified.</term>
/// </item>
/// <item>
/// <term>ERROR_BAD_LENGTH</term>
/// <term>The value of the dwInfoLength parameter did not match the value expected based on the value specified for the lpEnclaveInformation parameter.</term>
/// </item>
/// </list>
/// </para>
/// </returns>
// PVOID WINAPI CreateEnclave( _In_ HANDLE hProcess, _In_opt_ LPVOID lpAddress, _In_ SIZE_T dwSize, _In_ SIZE_T dwInitialCommittment, _In_ DWORD
// flEnclaveType, _In_ LPCVOID lpEnclaveInformation, _In_ DWORD dwInfoLength, _Out_opt_ LPDWORD lpEnclaveError); https://msdn.microsoft.com/en-us/library/windows/desktop/mt592866(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("Enclaveapi.h", MSDNShortId = "mt592866")]
public static extern void CreateEnclave(IntPtr hProcess, IntPtr lpAddress, SizeT dwSize, SizeT dwInitialCommittment, EnclaveType flEnclaveType, IntPtr lpEnclaveInformation, uint dwInfoLength, out uint lpEnclaveError);
/// <summary>Deletes the specified enclave.</summary>
/// <param name="lpAddress">The base address of the enclave that you want to delete.</param>
/// <returns>
/// <para><c>TRUE</c> if the enclave was deleted successfully; otherwise <c>FALSE</c>. To get extended error information, call <c>GetLastError</c>.</para>
/// <para>For a list of common error codes, see System Error Codes. The following error codes also apply for this function.</para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Return code</term>
/// <term>Description</term>
/// </listheader>
/// <item>
/// <term>ERROR_ENCLAVE_NOT_TERMINATED</term>
/// <term>
/// The execution of threads running with the enclave was not ended, because either TerminateEnclave was not called, or the execution of the threads has
/// not yet ended in response to an earlier call to TerminateEnclave.
/// </term>
/// </item>
/// </list>
/// </para>
/// </returns>
// BOOL WINAPI DeleteEnclave( _In_ LPVOID lpAddress); https://msdn.microsoft.com/en-us/library/windows/desktop/mt844232(v=vs.85).aspx
[DllImport(Lib.VertDll, SetLastError = true, ExactSpelling = true)]
[PInvokeData("Enclaveapi.h", MSDNShortId = "mt844232")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool DeleteEnclave(IntPtr lpAddress);
/// <summary>Initializes an enclave that you created and loaded with data.</summary>
/// <param name="hProcess">A handle to the process for which the enclave was created.</param>
/// <param name="lpAddress">Any address within the enclave.</param>
/// <param name="lpEnclaveInformation">
/// <para>A pointer to architecture-specific information to use to initialize the enclave.</para>
/// <para>For the <c>ENCLAVE_TYPE_SGX</c> enclave type, specify a pointer to an <c>ENCLAVE_INIT_INFO_SGX</c> structure.</para>
/// <para>For the <c>ENCLAVE_TYPE_VBS</c> enclave type, specify a pointer to an <c>ENCLAVE_INIT_INFO_VBS</c> structure.</para>
/// </param>
/// <param name="dwInfoLength">
/// The length of the structure that the lpEnclaveInformation parameter points to, in bytes. For the <c>ENCLAVE_TYPE_SGX</c> enclave type, this value
/// must be 4096. For the <c>ENCLAVE_TYPE_VBS</c> enclave type, this value must be , which is 8 bytes.
/// </param>
/// <param name="lpEnclaveError">
/// <para>An optional pointer to a variable that receives an enclave error code that is architecture-specific.</para>
/// <para>
/// For the <c>ENCLAVE_TYPE_SGX</c> enclave type, the lpEnclaveError parameter contains the error that the EINIT instruction generated if the function
/// fails and . <c>GetLastError</c> returns <c>ERROR_ENCLAVE_FAILURE</c>.
/// </para>
/// <para>For the <c>ENCLAVE_TYPE_VBS</c> enclave type, the lpEnclaveError parameter is not used.</para>
/// </param>
/// <returns>
/// <para>
/// If the function succeeds, the return value is nonzero. If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.
/// </para>
/// <para>For a list of common error codes, see System Error Codes. The following error codes also apply for this function.</para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Return code</term>
/// <term>Description</term>
/// </listheader>
/// <item>
/// <term>ERROR_ENCLAVE_FAILURE</term>
/// <term>
/// An failure specific to the underlying enclave architecture occurred. The value for the lpEnclaveError parameter contains the architecture-specific
/// error. For the ENCLAVE_TYPE_SGX enclave type, the EINIT instruction that the ENCLAVE_INIT_INFO_SGX structure specified generated an error. The value
/// of the lpEnclaveError parameter contains the error that the instruction generated.
/// </term>
/// </item>
/// <item>
/// <term>ERROR_BAD_LENGTH</term>
/// <term>The value of the dwInfoLength parameter did not match the value expected based on the value specified for the lpEnclaveInformation parameter.</term>
/// </item>
/// <item>
/// <term>ERROR_RETRY</term>
/// <term>The processor was not able to initialize the enclave in a timely fashion. Try to initialize the enclave again.</term>
/// </item>
/// </list>
/// </para>
/// </returns>
// BOOL WINAPI InitializeEnclave( _In_ HANDLE hProcess, _In_ LPVOID lpAddress, _In_ LPVOID lpEnclaveInformation, _In_ DWORD dwInfoLength, _In_ LPDWORD
// lpEnclaveError); https://msdn.microsoft.com/en-us/library/windows/desktop/mt592869(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("Enclaveapi.h", MSDNShortId = "mt592869")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool InitializeEnclave(IntPtr hProcess, IntPtr lpAddress, IntPtr lpEnclaveInformation, uint dwInfoLength, ref uint lpEnclaveError);
/// <summary>Retrieves whether the specified type of enclave is supported.</summary>
/// <param name="flEnclaveType">
/// <para>The type of enclave to check.</para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Value</term>
/// <term>Meaning</term>
/// </listheader>
/// <item>
/// <term>ENCLAVE_TYPE_SGX0x00000001</term>
/// <term>An enclave for the Intel Software Guard Extensions (SGX) architecture extension.</term>
/// </item>
/// <item>
/// <term>ENCLAVE_TYPE_VBS0x00000010</term>
/// <term>A virtualization-based security (VBS) enclave.</term>
/// </item>
/// </list>
/// </para>
/// </param>
/// <returns>
/// <para>
/// If the function succeeds, the return value is nonzero. If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.
/// </para>
/// <para>For a list of common error codes, see System Error Codes. The following error codes also apply for this function.</para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Return code</term>
/// <term>Description</term>
/// </listheader>
/// <item>
/// <term>ERROR_NOT_SUPPORTED</term>
/// <term>An unsupported enclave type was specified.</term>
/// </item>
/// </list>
/// </para>
/// </returns>
// BOOL WINAPI IsEnclaveTypeSupported( _In_ DWORD flEnclaveType); https://msdn.microsoft.com/en-us/library/windows/desktop/mt592870(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("Enclaveapi.h", MSDNShortId = "mt592870")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool IsEnclaveTypeSupported(EnclaveType flEnclaveType);
/// <summary>Loads data into an uninitialized enclave that you created by calling <c>CreateEnclave</c>.</summary>
/// <param name="hProcess">A handle to the process for which the enclave was created.</param>
/// <param name="lpAddress">The address in the enclave where you want to load the data.</param>
/// <param name="lpBuffer">A pointer to the data the you want to load into the enclave.</param>
/// <param name="nSize">
/// The size of the data that you want to load into the enclave, in bytes. This value must be a whole-number multiple of the page size.
/// </param>
/// <param name="flProtect">
/// <para>
/// The memory protection to use for the pages that you want to add to the enclave. For a list of memory protection values, see memory protection
/// constants. This value must not include the following constants:
/// </para>
/// <para>This value can include the enclave specific constants that the following table describes.</para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Constant</term>
/// <term>Description</term>
/// </listheader>
/// <item>
/// <term>PAGE_ENCLAVE_THREAD_CONTROL</term>
/// <term>The page contains a thread control structure (TCS).</term>
/// </item>
/// <item>
/// <term>PAGE_ENCLAVE_UNVALIDATED</term>
/// <term>
/// The page contents that you supply are excluded from measurement with the EEXTEND instruction of the Intel Software Guard Extensions programming model.
/// </term>
/// </item>
/// </list>
/// </para>
/// </param>
/// <param name="lpPageInformation">
/// A pointer to information that describes the pages that you want to add to the enclave. The lpPageInformation parameter is not used.
/// </param>
/// <param name="dwInfoLength">The length of the structure that the lpPageInformation parameter points to, in bytes. This value must be 0.</param>
/// <param name="lpNumberOfBytesWritten">A pointer to a variable that receives the number of bytes that <c>LoadEnclaveData</c> copied into the enclave.</param>
/// <param name="lpEnclaveError">
/// An optional pointer to a variable that receives an enclave error code that is architecture-specific. The lpEnclaveError parameter is not used.
/// </param>
/// <returns>
/// <para>
/// If all of the data is loaded into the enclave successfully, the return value is nonzero. Otherwise, the return value is zero. To get extended error
/// information, call <c>GetLastError</c>.
/// </para>
/// <para>For a list of common error codes, see System Error Codes. The following error codes also apply for this function.</para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Return code</term>
/// <term>Description</term>
/// </listheader>
/// <item>
/// <term>ERROR_BAD_LENGTH</term>
/// <term>The value of the dwInfoLength parameter did not match the value expected based on the value specified for the lpPageInformation parameter.</term>
/// </item>
/// </list>
/// </para>
/// </returns>
// BOOL WINAPI LoadEnclaveData( _In_ HANDLE hProcess, _In_ LPVOID lpAddress, _In_ LPCVOID lpBuffer, _In_ SIZE_T nSize, _In_ DWORD flProtect, _In_ LPCVOID
// lpPageInformation, _In_ DWORD dwInfoLength, _Out_ PSIZE_T lpNumberOfBytesWritten, _Out_opt_ LPDWORD lpEnclaveError); https://msdn.microsoft.com/en-us/library/windows/desktop/mt592871(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("Enclaveapi.h", MSDNShortId = "mt592871")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool LoadEnclaveData(IntPtr hProcess, IntPtr lpAddress, IntPtr lpBuffer, SizeT nSize, MEM_PROTECTION flProtect, IntPtr lpPageInformation, uint dwInfoLength, out SizeT lpNumberOfBytesWritten, out uint lpEnclaveError);
/// <summary>Loads an image and all of its imports into an enclave.</summary>
/// <param name="lpEnclaveAddress">The base address of the image into which to load the image.</param>
/// <param name="lpImageName">A NULL-terminated string that contains the name of the image to load.</param>
/// <returns><c>TRUE</c> if the function succeeds; otherwise <c>FALSE</c>. To get extended error information, call <c>GetLastError</c>.</returns>
// BOOL WINAPI LoadEnclaveImage( _In_ LPVOID lpEnclaveAddress, _In_ LPCSTR lpImageName); https://msdn.microsoft.com/en-us/library/windows/desktop/mt844248(v=vs.85).aspx
[DllImport(Lib.VertDll, SetLastError = true, CharSet = CharSet.Auto)]
[PInvokeData("Enclaveapi.h", MSDNShortId = "mt844248")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool LoadEnclaveImage(IntPtr lpEnclaveAddress, string lpImageName);
/// <summary>Ends the execution of the threads that are running within an enclave.</summary>
/// <param name="lpAddress">The base address of the enclave in which to end the execution of the threads.</param>
/// <param name="fWait">
/// <c>TRUE</c> if <c>TerminateEnclave</c> should not return until all of the threads in the enclave end execution. <c>FALSE</c> if
/// <c>TerminateEnclave</c> should return immediately.
/// </param>
/// <returns><c>TRUE</c> if the function succeeds; otherwise <c>FALSE</c>. To get extended error information, call <c>GetLastError</c>.</returns>
// BOOL WINAPI TerminateEnclave( _In_ LPVOID lpAddress, _In_ BOOL fWait); https://msdn.microsoft.com/en-us/library/windows/desktop/mt844249(v=vs.85).aspx
[DllImport(Lib.VertDll, SetLastError = true, ExactSpelling = true)]
[PInvokeData("Enclaveapi.h", MSDNShortId = "mt844249")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool TerminateEnclave(IntPtr lpAddress, [MarshalAs(UnmanagedType.Bool)] bool fWait);
/// <summary>
/// Contains architecture-specific information to use to create an enclave when the enclave type is <c>ENCLAVE_TYPE_SGX</c>, which specifies an enclave
/// for the Intel Software Guard Extensions (SGX) architecture extension.
/// </summary>
// typedef struct _ENCLAVE_CREATE_INFO_SGX { UCHAR Secs[4096];} ENCLAVE_CREATE_INFO_SGX, *PENCLAVE_CREATE_INFO_SGX; https://msdn.microsoft.com/en-us/library/windows/desktop/mt592867(v=vs.85).aspx
[PInvokeData("Winnt.h", MSDNShortId = "mt592867")]
[StructLayout(LayoutKind.Sequential)]
public struct ENCLAVE_CREATE_INFO_SGX
{
/// <summary>The SGX enclave control structure ( <c>SECS</c>) to use to create the enclave.</summary>
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 4096)]
public byte[] Secs;
}
/// <summary>
/// Contains architecture-specific information to use to create an enclave when the enclave type is <c>ENCLAVE_TYPE_VBS</c>, which specifies a
/// virtualization-based security (VBS) enclave.
/// </summary>
// typedef struct _ENCLAVE_CREATE_INFO_VBS { ULONG Flags; UCHAR OwnerID[32]; } ENCLAVE_CREATE_INFO_VBS, *PENCLAVE_CREATE_INFO_VBS; https://msdn.microsoft.com/en-us/library/windows/desktop/mt844238(v=vs.85).aspx
[PInvokeData("Winnt.h", MSDNShortId = "mt844238")]
[StructLayout(LayoutKind.Sequential)]
public struct ENCLAVE_CREATE_INFO_VBS
{
/// <summary>
/// <para>A flag that indicates whether the enclave permits debugging.</para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Value</term>
/// <term>Meaning</term>
/// </listheader>
/// <item>
/// <term>ENCLAVE_VBS_FLAG_DEBUG0x00000001</term>
/// <term>The enclave permits debugging.</term>
/// </item>
/// <item>
/// <term>0x00000000</term>
/// <term>The enclave does not permit debugging.</term>
/// </item>
/// </list>
/// </para>
/// </summary>
public ENCLAVE_VBS_FLAG Flags;
/// <summary>The identifier of the owner of the enclave.</summary>
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)]
public byte[] OwnerID;
}
/// <summary>
/// Contains architecture-specific information to use to initialize an enclave when the enclave type is <c>ENCLAVE_TYPE_SGX</c>, which specifies an
/// enclave for the Intel Software Guard Extensions (SGX) architecture extension.
/// </summary>
// typedef struct _ENCLAVE_INIT_INFO_SGX { UCHAR SigStruct[1808]; UCHAR Reserved1[240]; UCHAR EInitToken[304]; UCHAR Reserved2[744];}
// ENCLAVE_INIT_INFO_SGX, *PENCLAVE_INIT_INFO_SGX; https://msdn.microsoft.com/en-us/library/windows/desktop/mt592868(v=vs.85).aspx
[PInvokeData("Winnt.h", MSDNShortId = "mt592868")]
[StructLayout(LayoutKind.Sequential)]
public struct ENCLAVE_INIT_INFO_SGX
{
/// <summary>
/// The enclave signature structure ( <c>SIGSTRUCT</c>) to use to initialize the enclave. This structure specifies information about the enclave from
/// the enclave signer.
/// </summary>
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 1808)]
public byte[] SigStruct;
/// <summary>Not used.</summary>
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 240)]
public byte[] Reserved1;
/// <summary>
/// The EINIT token structure ( <c>EINITTOKEN</c>) to use to initialize the enclave. The initialization operation uses this structure to verify that
/// the enclave has permission to start.
/// </summary>
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 304)]
public byte[] EInitToken;
/// <summary>Not used.</summary>
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 1744)]
public byte[] Reserved2;
}
/// <summary>
/// Contains architecture-specific information to use to initialize an enclave when the enclave type is <c>ENCLAVE_TYPE_VBS</c>, which specifies a
/// virtualization-based security (VBS) enclave.
/// </summary>
// typedef struct ENCLAVE_INIT_INFO_VBS { ULONG Length; ULONG ThreadCount; }; https://msdn.microsoft.com/en-us/library/windows/desktop/mt844241(v=vs.85).aspx
[PInvokeData("Winnt.h", MSDNShortId = "mt844241")]
[StructLayout(LayoutKind.Sequential)]
public struct ENCLAVE_INIT_INFO_VBS
{
/// <summary>The total length of the <c>ENCLAVE_INIT_INFO_VBS</c> structure, in bytes.</summary>
public uint Length;
/// <summary>
/// Upon entry to the <c>InitializeEnclave</c> function, specifies the number of threads to create in the enclave. Upon successful return from
/// <c>InitializeEnclave</c>, contains the number of threads the function actually created.
/// </summary>
public uint ThreadCount;
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,106 @@
using System;
using System.Runtime.InteropServices;
namespace Vanara.PInvoke
{
public static partial class Kernel32
{
/// <summary>Indicates that FlsAlloc cannout allocate an index.</summary>
public const uint FLS_OUT_OF_INDEXES = 0xFFFFFFFF;
/// <summary>
/// An application-defined function. If the FLS slot is in use, FlsCallback is called on fiber deletion, thread exit, and when an FLS index is freed.
/// Specify this function when calling the FlsAlloc function. The PFLS_CALLBACK_FUNCTION type defines a pointer to this callback function. FlsCallback is
/// a placeholder for the application-defined function name.
/// </summary>
/// <param name="lpFlsData">The value stored in the FLS slot for the calling fiber.</param>
public delegate void PFLS_CALLBACK_FUNCTION(IntPtr lpFlsData);
/// <summary>
/// Allocates a fiber local storage (FLS) index. Any fiber in the process can subsequently use this index to store and retrieve values that are local to
/// the fiber.
/// </summary>
/// <param name="lpCallback">
/// A pointer to the application-defined callback function of type <c>PFLS_CALLBACK_FUNCTION</c>. This parameter is optional. For more information, see <c>FlsCallback</c>.
/// </param>
/// <returns>
/// <para>If the function succeeds, the return value is an FLS index initialized to zero.</para>
/// <para>If the function fails, the return value is FLS_OUT_OF_INDEXES. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// DWORD WINAPI FlsAlloc( _In_ PFLS_CALLBACK_FUNCTION lpCallback);
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms682664(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms682664")]
public static extern uint FlsAlloc(PFLS_CALLBACK_FUNCTION lpCallback);
/// <summary>Releases a fiber local storage (FLS) index, making it available for reuse.</summary>
/// <param name="dwFlsIndex">The FLS index that was allocated by the <c>FlsAlloc</c> function.</param>
/// <returns>
/// <para>If the function succeeds, the return value is nonzero.</para>
/// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// BOOL WINAPI FlsFree( _In_ DWORD dwFlsIndex);
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms682667(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms682667")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool FlsFree(uint dwFlsIndex);
/// <summary>
/// Retrieves the value in the calling fiber's fiber local storage (FLS) slot for the specified FLS index. Each fiber has its own slot for each FLS index.
/// </summary>
/// <param name="dwFlsIndex">The FLS index that was allocated by the <c>FlsAlloc</c> function.</param>
/// <returns>
/// <para>If the function succeeds, the return value is the value stored in the calling fiber's FLS slot associated with the specified index.</para>
/// <para>If the function fails, the return value is NULL. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// PVOID WINAPI FlsGetValue( _In_ DWORD dwFlsIndex);
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms683141(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms683141")]
public static extern IntPtr FlsGetValue(uint dwFlsIndex);
/// <summary>
/// Stores a value in the calling fiber's fiber local storage (FLS) slot for the specified FLS index. Each fiber has its own slot for each FLS index.
/// </summary>
/// <param name="dwFlsIndex">The FLS index that was allocated by the <c>FlsAlloc</c> function.</param>
/// <param name="lpFlsData">The value to be stored in the FLS slot for the calling fiber.</param>
/// <returns>
/// <para>If the function succeeds, the return value is nonzero.</para>
/// <para>
/// If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>. The following errors can be returned.
/// </para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Return code</term>
/// <term>Description</term>
/// </listheader>
/// <item>
/// <term>ERROR_INVALID_PARAMETER</term>
/// <term>The index is not in range.</term>
/// </item>
/// <item>
/// <term>ERROR_NO_MEMORY</term>
/// <term>The FLS array has not been allocated.</term>
/// </item>
/// </list>
/// </para>
/// </returns>
// BOOL WINAPI FlsSetValue( _In_ DWORD dwFlsIndex, _In_opt_ PVOID lpFlsData);
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms683146(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms683146")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool FlsSetValue(uint dwFlsIndex, IntPtr lpFlsData);
/// <summary>Determines whether the current thread is a fiber.</summary>
/// <returns>The function returns <c>TRUE</c> if the thread is a fiber and <c>FALSE</c> otherwise.</returns>
// BOOL WINAPI IsThreadAFiber(void);
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms684131(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms684131")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool IsThreadAFiber();
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,203 @@
using System;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
namespace Vanara.PInvoke
{
public static partial class Kernel32
{
/// <summary>Optional actions.</summary>
[Flags]
public enum DUPLICATE_HANDLE_OPTIONS : uint
{
/// <summary>Closes the source handle. This occurs regardless of any error status returned.</summary>
DUPLICATE_CLOSE_SOURCE = 0x00000001,
/// <summary>Ignores the dwDesiredAccess parameter. The duplicate handle has the same access as the source handle.</summary>
DUPLICATE_SAME_ACCESS = 0x00000002,
}
/// <summary>A set of bit flags that specify properties of the object handle.</summary>
[Flags]
public enum HANDLE_FLAG
{
/// <summary>None.</summary>
NONE = 0,
/// <summary>
/// If this flag is set, a child process created with the bInheritHandles parameter of CreateProcess set to TRUE will inherit the object handle.
/// </summary>
HANDLE_FLAG_INHERIT = 1,
/// <summary>If this flag is set, calling the CloseHandle function will not close the object handle.</summary>
HANDLE_FLAG_PROTECT_FROM_CLOSE = 2
}
/// <summary>Closes an open object handle.</summary>
/// <param name="hObject">A valid handle to an open object.</param>
/// <returns>
/// <para>If the function succeeds, the return value is nonzero.</para>
/// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para>
/// <para>
/// If the application is running under a debugger, the function will throw an exception if it receives either a handle value that is not valid or a
/// pseudo-handle value. This can happen if you close a handle twice, or if you call <c>CloseHandle</c> on a handle returned by the <c>FindFirstFile</c>
/// function instead of calling the <c>FindClose</c> function.
/// </para>
/// </returns>
// BOOL WINAPI CloseHandle( _In_ HANDLE hObject); https://msdn.microsoft.com/en-us/library/windows/desktop/ms724211(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[PInvokeData("Winbase.h", MSDNShortId = "ms724211")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool CloseHandle(IntPtr hObject);
/// <summary>Compares two object handles to determine if they refer to the same underlying kernel object.</summary>
/// <param name="hFirstObjectHandle">The first object handle to compare.</param>
/// <param name="hSecondObjectHandle">The second object handle to compare.</param>
/// <returns>A Boolean value that indicates if the two handles refer to the same underlying kernel object. TRUE if the same, otherwise FALSE.</returns>
// BOOL WINAPI CompareObjectHandles( _In_ HANDLE hFirstObjectHandle, _In_ HANDLE hSecondObjectHandle); https://msdn.microsoft.com/en-us/library/windows/desktop/mt438733(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)]
[PInvokeData("Handleapi.h", MSDNShortId = "mt438733")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool CompareObjectHandles(IntPtr hFirstObjectHandle, IntPtr hSecondObjectHandle);
/// <summary>Duplicates an object handle.</summary>
/// <param name="hSourceProcessHandle">
/// <para>A handle to the process with the handle to be duplicated.</para>
/// <para>The handle must have the PROCESS_DUP_HANDLE access right. For more information, see Process Security and Access Rights.</para>
/// </param>
/// <param name="hSourceHandle">
/// The handle to be duplicated. This is an open object handle that is valid in the context of the source process. For a list of objects whose handles
/// can be duplicated, see the following Remarks section.
/// </param>
/// <param name="hTargetProcessHandle">
/// A handle to the process that is to receive the duplicated handle. The handle must have the PROCESS_DUP_HANDLE access right.
/// </param>
/// <param name="lpTargetHandle">
/// <para>A pointer to a variable that receives the duplicate handle. This handle value is valid in the context of the target process.</para>
/// <para>
/// If hSourceHandle is a pseudo handle returned by <c>GetCurrentProcess</c> or <c>GetCurrentThread</c>, <c>DuplicateHandle</c> converts it to a real
/// handle to a process or thread, respectively.
/// </para>
/// <para>
/// If lpTargetHandle is <c>NULL</c>, the function duplicates the handle, but does not return the duplicate handle value to the caller. This behavior
/// exists only for backward compatibility with previous versions of this function. You should not use this feature, as you will lose system resources
/// until the target process terminates.
/// </para>
/// </param>
/// <param name="dwDesiredAccess">
/// <para>The access requested for the new handle. For the flags that can be specified for each object type, see the following Remarks section.</para>
/// <para>
/// This parameter is ignored if the dwOptions parameter specifies the DUPLICATE_SAME_ACCESS flag. Otherwise, the flags that can be specified depend on
/// the type of object whose handle is to be duplicated.
/// </para>
/// </param>
/// <param name="bInheritHandle">
/// A variable that indicates whether the handle is inheritable. If <c>TRUE</c>, the duplicate handle can be inherited by new processes created by the
/// target process. If <c>FALSE</c>, the new handle cannot be inherited.
/// </param>
/// <param name="dwOptions">
/// <para>Optional actions. This parameter can be zero, or any combination of the following values.</para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Value</term>
/// <term>Meaning</term>
/// </listheader>
/// <item>
/// <term>DUPLICATE_CLOSE_SOURCE0x00000001</term>
/// <term>Closes the source handle. This occurs regardless of any error status returned.</term>
/// </item>
/// <item>
/// <term>DUPLICATE_SAME_ACCESS0x00000002</term>
/// <term>Ignores the dwDesiredAccess parameter. The duplicate handle has the same access as the source handle.</term>
/// </item>
/// </list>
/// </para>
/// </param>
/// <returns>
/// <para>If the function succeeds, the return value is nonzero.</para>
/// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// BOOL WINAPI DuplicateHandle( _In_ HANDLE hSourceProcessHandle, _In_ HANDLE hSourceHandle, _In_ HANDLE hTargetProcessHandle, _Out_ LPHANDLE
// lpTargetHandle, _In_ DWORD dwDesiredAccess, _In_ BOOL bInheritHandle, _In_ DWORD dwOptions); https://msdn.microsoft.com/en-us/library/windows/desktop/ms724251(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("Winbase.h", MSDNShortId = "ms724251")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool DuplicateHandle(
[In] IntPtr hSourceProcessHandle, [In] IntPtr hSourceHandle, [In] IntPtr hTargetProcessHandle, out IntPtr lpTargetHandle, uint dwDesiredAccess,
[MarshalAs(UnmanagedType.Bool)] bool bInheritHandle, DUPLICATE_HANDLE_OPTIONS dwOptions);
/// <summary>Retrieves certain properties of an object handle.</summary>
/// <param name="hObject">
/// <para>A handle to an object whose information is to be retrieved.</para>
/// <para>
/// You can specify a handle to one of the following types of objects: access token, console input buffer, console screen buffer, event, file, file
/// mapping, job, mailslot, mutex, pipe, printer, process, registry key, semaphore, serial communication device, socket, thread, or waitable timer.
/// </para>
/// </param>
/// <param name="lpdwFlags">
/// <para>A pointer to a variable that receives a set of bit flags that specify properties of the object handle or 0. The following values are defined.</para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Value</term>
/// <term>Meaning</term>
/// </listheader>
/// <item>
/// <term>HANDLE_FLAG_INHERIT0x00000001</term>
/// <term>If this flag is set, a child process created with the bInheritHandles parameter of CreateProcess set to TRUE will inherit the object handle.</term>
/// </item>
/// <item>
/// <term>HANDLE_FLAG_PROTECT_FROM_CLOSE0x00000002</term>
/// <term>If this flag is set, calling the CloseHandle function will not close the object handle.</term>
/// </item>
/// </list>
/// </para>
/// </param>
/// <returns>
/// <para>If the function succeeds, the return value is nonzero.</para>
/// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// BOOL WINAPI GetHandleInformation( _In_ HANDLE hObject, _Out_ LPDWORD lpdwFlags); https://msdn.microsoft.com/en-us/library/windows/desktop/ms724329(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("Winbase.h", MSDNShortId = "ms724329")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetHandleInformation([In] IntPtr hObject, out HANDLE_FLAG lpdwFlags);
/// <summary>Sets certain properties of an object handle.</summary>
/// <param name="hObject">
/// <para>A handle to an object whose information is to be set.</para>
/// <para>
/// You can specify a handle to one of the following types of objects: access token, console input buffer, console screen buffer, event, file, file
/// mapping, job, mailslot, mutex, pipe, printer, process, registry key, semaphore, serial communication device, socket, thread, or waitable timer.
/// </para>
/// </param>
/// <param name="dwMask">A mask that specifies the bit flags to be changed. Use the same constants shown in the description of dwFlags.</param>
/// <param name="dwFlags">
/// <para>Set of bit flags that specifies properties of the object handle. This parameter can be 0 or one or more of the following values.</para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Value</term>
/// <term>Meaning</term>
/// </listheader>
/// <item>
/// <term>HANDLE_FLAG_INHERIT0x00000001</term>
/// <term>If this flag is set, a child process created with the bInheritHandles parameter of CreateProcess set to TRUE will inherit the object handle.</term>
/// </item>
/// <item>
/// <term>HANDLE_FLAG_PROTECT_FROM_CLOSE0x00000002</term>
/// <term>If this flag is set, calling the CloseHandle function will not close the object handle.</term>
/// </item>
/// </list>
/// </para>
/// </param>
/// <returns>
/// <para>If the function succeeds, the return value is nonzero.</para>
/// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// BOOL WINAPI SetHandleInformation( _In_ HANDLE hObject, _In_ DWORD dwMask, _In_ DWORD dwFlags);// https://msdn.microsoft.com/en-us/library/windows/desktop/ms724935(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("Winbase.h", MSDNShortId = "ms724935")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetHandleInformation([In] IntPtr hObject, HANDLE_FLAG dwMask, HANDLE_FLAG dwFlags);
}
}

View File

@ -6,27 +6,80 @@ namespace Vanara.PInvoke
{
public static partial class Kernel32
{
/// <summary>Specifies the class of heap information to be set or retrieved.</summary>
// typedef enum _HEAP_INFORMATION_CLASS { HeapCompatibilityInformation = 0, HeapEnableTerminationOnCorruption = 1} HEAP_INFORMATION_CLASS; https://msdn.microsoft.com/en-us/library/windows/desktop/dn280633(v=vs.85).aspx
[PInvokeData("WinNT.h", MSDNShortId = "dn280633")]
public enum HEAP_INFORMATION_CLASS
{
/// <summary>
/// <para>
/// The heap features that are enabled. The available features vary based on operating system. Depending on the HeapInformation parameter in the
/// <c>HeapQueryInformation</c> or <c>HeapSetInformation</c> functions, specifying this enumeration value can indicate one of the following features:
/// </para>
/// <para>For more information about look-aside lists, see the Remarks section.</para>
/// </summary>
HeapCompatibilityInformation = 0,
/// <summary>
/// <para>
/// The terminate-on-corruption feature. If the heap manager detects an error in any heap used by the process, it calls the Windows Error Reporting
/// service and terminates the process.
/// </para>
/// <para>After a process enables this feature, it cannot be disabled.</para>
/// </summary>
HeapEnableTerminationOnCorruption = 1,
/// <summary>
/// If HeapSetInformation is called with HeapHandle set to NULL, then all heaps in the process with a low-fragmentation heap (LFH) will have their
/// caches optimized, and the memory will be decommitted if possible.
/// <para>If a heap pointer is supplied in HeapHandle, then only that heap will be optimized.</para>
/// <para>Note that the HEAP_OPTIMIZE_RESOURCES_INFORMATION structure passed in HeapInformation must be properly initialized.</para>
/// <para>Note This value was added in Windows 8.1.</para>
/// </summary>
HeapOptimizeResources = 3
}
/// <summary>Flags for Head functions</summary>
[PInvokeData("HeapApi.h")]
[Flags]
public enum HeapFlags
{
/// <summary>Serialized access will not be used for this allocation. For more information, see Remarks.
/// <para>To ensure that serialized access is disabled for all calls to this function, specify HEAP_NO_SERIALIZE in the call to HeapCreate. In this case, it is not necessary to additionally specify HEAP_NO_SERIALIZE in this function call.</para>
/// <para>This value should not be specified when accessing the process's default heap. The system may create additional threads within the application's process, such as a CTRL+C handler, that simultaneously access the process's default heap.</para></summary>
/// <summary>
/// Serialized access will not be used for this allocation. For more information, see Remarks.
/// <para>
/// To ensure that serialized access is disabled for all calls to this function, specify HEAP_NO_SERIALIZE in the call to HeapCreate. In this case,
/// it is not necessary to additionally specify HEAP_NO_SERIALIZE in this function call.
/// </para>
/// <para>
/// This value should not be specified when accessing the process's default heap. The system may create additional threads within the application's
/// process, such as a CTRL+C handler, that simultaneously access the process's default heap.
/// </para>
/// </summary>
HEAP_NO_SERIALIZE = 0x00000001,
HEAP_GROWABLE = 0x00000002,
/// <summary>The system will raise an exception to indicate a function failure, such as an out-of-memory condition, instead of returning NULL.
/// <para>To ensure that exceptions are generated for all calls to this function, specify HEAP_GENERATE_EXCEPTIONS in the call to HeapCreate. In this case, it is not necessary to additionally specify HEAP_GENERATE_EXCEPTIONS in this function call.</para></summary>
/// <summary>
/// The system will raise an exception to indicate a function failure, such as an out-of-memory condition, instead of returning NULL.
/// <para>
/// To ensure that exceptions are generated for all calls to this function, specify HEAP_GENERATE_EXCEPTIONS in the call to HeapCreate. In this case,
/// it is not necessary to additionally specify HEAP_GENERATE_EXCEPTIONS in this function call.
/// </para>
/// </summary>
HEAP_GENERATE_EXCEPTIONS = 0x00000004,
/// <summary>The allocated memory will be initialized to zero. Otherwise, the memory is not initialized to zero.</summary>
HEAP_ZERO_MEMORY = 0x00000008,
/// <summary>
/// There can be no movement when reallocating a memory block. If this value is not specified, the function may move the block to a new location. If
/// this value is specified and the block cannot be resized without moving, the function fails, leaving the original memory block unchanged.
/// </summary>
HEAP_REALLOC_IN_PLACE_ONLY = 0x00000010,
HEAP_TAIL_CHECKING_ENABLED = 0x00000020,
HEAP_FREE_CHECKING_ENABLED = 0x00000040,
HEAP_DISABLE_COALESCE_ON_FREE = 0x00000080,
HEAP_CREATE_ALIGN_16 = 0x00010000,
HEAP_CREATE_ENABLE_TRACING = 0x00020000,
/// <summary>All memory blocks that are allocated from this heap allow code execution, if the hardware enforces data execution prevention. Use this flag heap in applications that run code from the heap. If HEAP_CREATE_ENABLE_EXECUTE is not specified and an application attempts to run code from a protected page, the application receives an exception with the status code STATUS_ACCESS_VIOLATION.</summary>
/// <summary>
/// All memory blocks that are allocated from this heap allow code execution, if the hardware enforces data execution prevention. Use this flag heap
/// in applications that run code from the heap. If HEAP_CREATE_ENABLE_EXECUTE is not specified and an application attempts to run code from a
/// protected page, the application receives an exception with the status code STATUS_ACCESS_VIOLATION.
/// </summary>
HEAP_CREATE_ENABLE_EXECUTE = 0x00040000,
HEAP_MAXIMUM_TAG = 0x0FFF,
HEAP_PSEUDO_TAG_FLAG = 0x8000,
@ -35,65 +88,722 @@ namespace Vanara.PInvoke
HEAP_CREATE_HARDENED = 0x00000200,
}
/// <summary>The properties of the heap element.</summary>
[Flags]
public enum PROCESS_HEAP : ushort
{
/// <summary>
/// The heap element is located at the beginning of a region of contiguous virtual memory in use by the heap.The lpData member of the structure
/// points to the first virtual address used by the region; the cbData member specifies the total size, in bytes, of the address space that is
/// reserved for this region; and the cbOverhead member specifies the size, in bytes, of the heap control structures that describe the region.The
/// Region structure becomes valid. The dwCommittedSize, dwUnCommittedSize, lpFirstBlock, and lpLastBlock members of the structure contain additional
/// information about the region.
/// </summary>
PROCESS_HEAP_REGION = 1,
/// <summary>
/// The heap element is located in a range of uncommitted memory within the heap region.The lpData member points to the beginning of the range of
/// uncommitted memory; the cbData member specifies the size, in bytes, of the range of uncommitted memory; and the cbOverhead member specifies the
/// size, in bytes, of the control structures that describe this uncommitted range.
/// </summary>
PROCESS_HEAP_UNCOMMITTED_RANGE = 2,
/// <summary>
/// The heap element is an allocated block.If PROCESS_HEAP_ENTRY_MOVEABLE is also specified, the Block structure becomes valid. The hMem member of
/// the Block structure contains a handle to the allocated, moveable memory block.
/// </summary>
PROCESS_HEAP_ENTRY_BUSY = 4,
/// <summary>
/// This value must be used with PROCESS_HEAP_ENTRY_BUSY, indicating that the heap element is an allocated block.The block was allocated with
/// LMEM_MOVEABLE or GMEM_MOVEABLE, and the Block structure becomes valid. The hMem member of the Block structure contains a handle to the allocated,
/// moveable memory block.
/// </summary>
PROCESS_HEAP_ENTRY_MOVEABLE = 16,
/// <summary>This value must be used with PROCESS_HEAP_ENTRY_BUSY, indicating that the heap element is an allocated block.</summary>
PROCESS_HEAP_ENTRY_DDESHARE = 32,
}
/// <summary>Retrieves a handle to the default heap of the calling process. This handle can then be used in subsequent calls to the heap functions.</summary>
/// <returns>If the function succeeds, the return value is a handle to the calling process's heap. If the function fails, the return value is NULL. To get extended error information, call GetLastError.</returns>
/// <returns>
/// If the function succeeds, the return value is a handle to the calling process's heap. If the function fails, the return value is NULL. To get
/// extended error information, call GetLastError.
/// </returns>
[PInvokeData("HeapApi.h", MSDNShortId = "aa366569")]
[DllImport(Lib.Kernel32, ExactSpelling = true, SetLastError = true)]
public static extern IntPtr GetProcessHeap();
/// <summary>Returns the number of active heaps and retrieves handles to all of the active heaps for the calling process.</summary>
/// <param name="NumberOfHeaps">The maximum number of heap handles that can be stored into the buffer pointed to by ProcessHeaps.</param>
/// <param name="ProcessHeaps">A pointer to a buffer that receives an array of heap handles.</param>
/// <returns>
/// <para>The return value is the number of handles to heaps that are active for the calling process.</para>
/// <para>
/// If the return value is less than or equal to NumberOfHeaps, the function has stored that number of heap handles in the buffer pointed to by ProcessHeaps.
/// </para>
/// <para>
/// If the return value is greater than NumberOfHeaps, the buffer pointed to by ProcessHeaps is too small to hold all the heap handles for the calling
/// process, and the function stores NumberOfHeaps handles in the buffer. Use the return value to allocate a buffer that is large enough to receive all
/// of the handles, and call the function again.
/// </para>
/// <para>
/// If the return value is zero, the function has failed because every process has at least one active heap, the default heap for the process. To get
/// extended error information, call <c>GetLastError</c>.
/// </para>
/// </returns>
// DWORD WINAPI GetProcessHeaps( _In_ DWORD NumberOfHeaps, _Out_ PHANDLE ProcessHeaps);// https://msdn.microsoft.com/en-us/library/windows/desktop/aa366571(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("HeapApi.h", MSDNShortId = "aa366571")]
public static extern uint GetProcessHeaps(uint NumberOfHeaps, out IntPtr ProcessHeaps);
/// <summary>Allocates a block of memory from a heap. The allocated memory is not movable.</summary>
/// <param name="hHeap">A handle to the heap from which the memory will be allocated. This handle is returned by the HeapCreate or GetProcessHeap function.</param>
/// <param name="dwFlags">The heap allocation options. Specifying any of these values will override the corresponding value specified when the heap was created with HeapCreate. This parameter can be one or more of the following values: HEAP_GENERATE_EXCEPTIONS, HEAP_NO_SERIALIZE and HEAP_ZERO_MEMORY.</param>
/// <param name="dwBytes">The number of bytes to be allocated. If the heap specified by the hHeap parameter is a "non-growable" heap, dwBytes must be less than 0x7FFF8. You create a non-growable heap by calling the HeapCreate function with a nonzero value.</param>
/// <returns>If the function succeeds, the return value is a pointer to the allocated memory block.
/// <param name="dwFlags">
/// The heap allocation options. Specifying any of these values will override the corresponding value specified when the heap was created with
/// HeapCreate. This parameter can be one or more of the following values: HEAP_GENERATE_EXCEPTIONS, HEAP_NO_SERIALIZE and HEAP_ZERO_MEMORY.
/// </param>
/// <param name="dwBytes">
/// The number of bytes to be allocated. If the heap specified by the hHeap parameter is a "non-growable" heap, dwBytes must be less than 0x7FFF8. You
/// create a non-growable heap by calling the HeapCreate function with a nonzero value.
/// </param>
/// <returns>
/// If the function succeeds, the return value is a pointer to the allocated memory block.
/// <para>If the function fails and you have not specified HEAP_GENERATE_EXCEPTIONS, the return value is NULL.</para>
/// <para>If the function fails and you have specified HEAP_GENERATE_EXCEPTIONS, the function may generate either of the exceptions listed in the following table. The particular exception depends upon the nature of the heap corruption. For more information, see GetExceptionCode.</para></returns>
/// <para>
/// If the function fails and you have specified HEAP_GENERATE_EXCEPTIONS, the function may generate either of the exceptions listed in the following
/// table. The particular exception depends upon the nature of the heap corruption. For more information, see GetExceptionCode.
/// </para>
/// </returns>
[PInvokeData("HeapApi.h", MSDNShortId = "aa366597")]
[DllImport(Lib.Kernel32, ExactSpelling = true)]
public static extern IntPtr HeapAlloc(IntPtr hHeap, HeapFlags dwFlags, [MarshalAs(UnmanagedType.SysInt)] IntPtr dwBytes);
/// <summary>Creates a private heap object that can be used by the calling process. The function reserves space in the virtual address space of the process and allocates physical storage for a specified initial portion of this block.</summary>
/// <param name="flOptions">The heap allocation options. These options affect subsequent access to the new heap through calls to the heap functions. This parameter can be 0 or one or more of the following values: HEAP_CREATE_ENABLE_EXECUTE, HEAP_GENERATE_EXCEPTIONS, HEAP_NO_SERIALIZE.</param>
/// <param name="dwInitialSize">The initial size of the heap, in bytes. This value determines the initial amount of memory that is committed for the heap. The value is rounded up to a multiple of the system page size. The value must be smaller than dwMaximumSize.
/// <para>If this parameter is 0, the function commits one page. To determine the size of a page on the host computer, use the GetSystemInfo function.</para></param>
/// <param name="dwMaximumSize">The maximum size of the heap, in bytes. The HeapCreate function rounds dwMaximumSize up to a multiple of the system page size and then reserves a block of that size in the process's virtual address space for the heap. If allocation requests made by the HeapAlloc or HeapReAlloc functions exceed the size specified by dwInitialSize, the system commits additional pages of memory for the heap, up to the heap's maximum size.
/// <para>If dwMaximumSize is not zero, the heap size is fixed and cannot grow beyond the maximum size. Also, the largest memory block that can be allocated from the heap is slightly less than 512 KB for a 32-bit process and slightly less than 1,024 KB for a 64-bit process. Requests to allocate larger blocks fail, even if the maximum size of the heap is large enough to contain the block.</para>
/// <para>If dwMaximumSize is 0, the heap can grow in size. The heap's size is limited only by the available memory. Requests to allocate memory blocks larger than the limit for a fixed-size heap do not automatically fail; instead, the system calls the VirtualAlloc function to obtain the memory that is needed for large blocks. Applications that need to allocate large memory blocks should set dwMaximumSize to 0.</para></param>
/// <returns>If the function succeeds, the return value is a handle to the newly created heap. If the function fails, the return value is NULL. To get extended error information, call GetLastError.</returns>
/// <summary>
/// Returns the size of the largest committed free block in the specified heap. If the Disable heap coalesce on free global flag is set, this function
/// also coalesces adjacent free blocks of memory in the heap.
/// </summary>
/// <param name="hHeap">A handle to the heap. This handle is returned by either the <c>HeapCreate</c> or <c>GetProcessHeap</c> function.</param>
/// <param name="dwFlags">
/// <para>The heap access options. This parameter can be the following value.</para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Value</term>
/// <term>Meaning</term>
/// </listheader>
/// <item>
/// <term>HEAP_NO_SERIALIZE0x00000001</term>
/// <term>
/// Serialized access will not be used. For more information, see Remarks.To ensure that serialized access is disabled for all calls to this function,
/// specify HEAP_NO_SERIALIZE in the call to HeapCreate. In this case, it is not necessary to additionally specify HEAP_NO_SERIALIZE in this function
/// call.Do not specify this value when accessing the process heap. The system may create additional threads within the application&amp;#39;s process,
/// such as a CTRL+C handler, that simultaneously access the process heap.
/// </term>
/// </item>
/// </list>
/// </para>
/// </param>
/// <returns>
/// <para>If the function succeeds, the return value is the size of the largest committed free block in the heap, in bytes.</para>
/// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para>
/// <para>
/// In the unlikely case that there is absolutely no space available in the heap, the function return value is zero, and <c>GetLastError</c> returns the
/// value NO_ERROR.
/// </para>
/// </returns>
// SIZE_T WINAPI HeapCompact( _In_ HANDLE hHeap, _In_ DWORD dwFlags);// https://msdn.microsoft.com/en-us/library/windows/desktop/aa366598(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("HeapApi.h", MSDNShortId = "aa366598")]
public static extern SizeT HeapCompact([In] IntPtr hHeap, HeapFlags dwFlags);
/// <summary>
/// Creates a private heap object that can be used by the calling process. The function reserves space in the virtual address space of the process and
/// allocates physical storage for a specified initial portion of this block.
/// </summary>
/// <param name="flOptions">
/// The heap allocation options. These options affect subsequent access to the new heap through calls to the heap functions. This parameter can be 0 or
/// one or more of the following values: HEAP_CREATE_ENABLE_EXECUTE, HEAP_GENERATE_EXCEPTIONS, HEAP_NO_SERIALIZE.
/// </param>
/// <param name="dwInitialSize">
/// The initial size of the heap, in bytes. This value determines the initial amount of memory that is committed for the heap. The value is rounded up to
/// a multiple of the system page size. The value must be smaller than dwMaximumSize.
/// <para>If this parameter is 0, the function commits one page. To determine the size of a page on the host computer, use the GetSystemInfo function.</para>
/// </param>
/// <param name="dwMaximumSize">
/// The maximum size of the heap, in bytes. The HeapCreate function rounds dwMaximumSize up to a multiple of the system page size and then reserves a
/// block of that size in the process's virtual address space for the heap. If allocation requests made by the HeapAlloc or HeapReAlloc functions exceed
/// the size specified by dwInitialSize, the system commits additional pages of memory for the heap, up to the heap's maximum size.
/// <para>
/// If dwMaximumSize is not zero, the heap size is fixed and cannot grow beyond the maximum size. Also, the largest memory block that can be allocated
/// from the heap is slightly less than 512 KB for a 32-bit process and slightly less than 1,024 KB for a 64-bit process. Requests to allocate larger
/// blocks fail, even if the maximum size of the heap is large enough to contain the block.
/// </para>
/// <para>
/// If dwMaximumSize is 0, the heap can grow in size. The heap's size is limited only by the available memory. Requests to allocate memory blocks larger
/// than the limit for a fixed-size heap do not automatically fail; instead, the system calls the VirtualAlloc function to obtain the memory that is
/// needed for large blocks. Applications that need to allocate large memory blocks should set dwMaximumSize to 0.
/// </para>
/// </param>
/// <returns>
/// If the function succeeds, the return value is a handle to the newly created heap. If the function fails, the return value is NULL. To get extended
/// error information, call GetLastError.
/// </returns>
[PInvokeData("HeapApi.h", MSDNShortId = "aa366599")]
[DllImport(Lib.Kernel32, ExactSpelling = true, SetLastError = true)]
public static extern SafePrivateHeapHandle HeapCreate(HeapFlags flOptions, [MarshalAs(UnmanagedType.SysInt)] IntPtr dwInitialSize, [MarshalAs(UnmanagedType.SysInt)] IntPtr dwMaximumSize);
/// <summary>Destroys the specified heap object. It decommits and releases all the pages of a private heap object, and it invalidates the handle to the heap.</summary>
/// <param name="hHeap">A handle to the heap to be destroyed. This handle is returned by the HeapCreate function. Do not use the handle to the process heap returned by the GetProcessHeap function.</param>
/// <returns>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.</returns>
/// <summary>
/// Destroys the specified heap object. It decommits and releases all the pages of a private heap object, and it invalidates the handle to the heap.
/// </summary>
/// <param name="hHeap">
/// A handle to the heap to be destroyed. This handle is returned by the HeapCreate function. Do not use the handle to the process heap returned by the
/// GetProcessHeap function.
/// </param>
/// <returns>
/// 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.
/// </returns>
[PInvokeData("HeapApi.h", MSDNShortId = "aa366700")]
[DllImport(Lib.Kernel32, ExactSpelling = true, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool HeapDestroy(IntPtr hHeap);
/// <summary>Frees a memory block allocated from a heap by the HeapAlloc or HeapReAlloc function.</summary>
/// <param name="hHeap">A handle to the heap whose memory block is to be freed. This handle is returned by either the HeapCreate or GetProcessHeap function.</param>
/// <param name="dwFlags">The heap free options. Specifying the following value overrides the corresponding value specified in the flOptions parameter when the heap was created by using the HeapCreate function: HEAP_NO_SERIALIZE</param>
/// <param name="lpMem">A pointer to the memory block to be freed. This pointer is returned by the HeapAlloc or HeapReAlloc function. If this pointer is NULL, the behavior is undefined.</param>
/// <returns>If the function succeeds, the return value is nonzero. If the function fails, the return value is zero.An application can call GetLastError for extended error information.</returns>
/// <param name="hHeap">
/// A handle to the heap whose memory block is to be freed. This handle is returned by either the HeapCreate or GetProcessHeap function.
/// </param>
/// <param name="dwFlags">
/// The heap free options. Specifying the following value overrides the corresponding value specified in the flOptions parameter when the heap was
/// created by using the HeapCreate function: HEAP_NO_SERIALIZE
/// </param>
/// <param name="lpMem">
/// A pointer to the memory block to be freed. This pointer is returned by the HeapAlloc or HeapReAlloc function. If this pointer is NULL, the behavior
/// is undefined.
/// </param>
/// <returns>
/// If the function succeeds, the return value is nonzero. If the function fails, the return value is zero.An application can call GetLastError for
/// extended error information.
/// </returns>
[PInvokeData("HeapApi.h", MSDNShortId = "aa366701")]
[DllImport(Lib.Kernel32, ExactSpelling = true, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool HeapFree(IntPtr hHeap, HeapFlags dwFlags, IntPtr lpMem);
/// <summary>Attempts to acquire the critical section object, or lock, that is associated with a specified heap.</summary>
/// <param name="hHeap">A handle to the heap to be locked. This handle is returned by either the <c>HeapCreate</c> or <c>GetProcessHeap</c> function.</param>
/// <returns>
/// <para>If the function succeeds, the return value is nonzero.</para>
/// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// BOOL WINAPI HeapLock( _In_ HANDLE hHeap);// https://msdn.microsoft.com/en-us/library/windows/desktop/aa366702(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("HeapApi.h", MSDNShortId = "aa366702")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool HeapLock([In] IntPtr hHeap);
/// <summary>Retrieves information about the specified heap.</summary>
/// <param name="HeapHandle">
/// A handle to the heap whose information is to be retrieved. This handle is returned by either the <c>HeapCreate</c> or <c>GetProcessHeap</c> function.
/// </param>
/// <param name="HeapInformationClass">
/// <para>The class of information to be retrieved. This parameter can be the following value from the <c>HEAP_INFORMATION_CLASS</c> enumeration type.</para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Value</term>
/// <term>Meaning</term>
/// </listheader>
/// <item>
/// <term>HeapCompatibilityInformation0</term>
/// <term>
/// Indicates the heap features that are enabled. The HeapInformation parameter is a pointer to a ULONG variable.If HeapInformation is 0, the heap is a
/// standard heap that does not support look-aside lists.If HeapInformation is 1, the heap supports look-aside lists. For more information, see
/// Remarks.If HeapInformation is 2, the low-fragmentation heap (LFH) has been enabled for the heap. Enabling the LFH disables look-aside lists.
/// </term>
/// </item>
/// </list>
/// </para>
/// </param>
/// <param name="HeapInformation">
/// A pointer to a buffer that receives the heap information. The format of this data depends on the value of the HeapInformationClass parameter.
/// </param>
/// <param name="HeapInformationLength">The size of the heap information being queried, in bytes.</param>
/// <param name="ReturnLength">
/// <para>
/// A pointer to a variable that receives the length of data written to the HeapInformation buffer. If the buffer is too small, the function fails and
/// ReturnLength specifies the minimum size required for the buffer.
/// </para>
/// <para>If you do not want to receive this information, specify <c>NULL</c>.</para>
/// </param>
/// <returns>
/// <para>If the function succeeds, the return value is nonzero.</para>
/// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// BOOL WINAPI HeapQueryInformation( _In_opt_ HANDLE HeapHandle, _In_ HEAP_INFORMATION_CLASS HeapInformationClass, _Out_ PVOID HeapInformation, _In_
// SIZE_T HeapInformationLength, _Out_opt_ PSIZE_T ReturnLength);// https://msdn.microsoft.com/en-us/library/windows/desktop/aa366703(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("HeapApi.h", MSDNShortId = "aa366703")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool HeapQueryInformation([In] IntPtr HeapHandle, HEAP_INFORMATION_CLASS HeapInformationClass, IntPtr HeapInformation, SizeT HeapInformationLength, out SizeT ReturnLength);
/// <summary>
/// Reallocates a block of memory from a heap. This function enables you to resize a memory block and change other memory block properties. The allocated
/// memory is not movable.
/// </summary>
/// <param name="hHeap">
/// A handle to the heap from which the memory is to be reallocated. This handle is a returned by either the <c>HeapCreate</c> or <c>GetProcessHeap</c> function.
/// </param>
/// <param name="dwFlags">
/// <para>
/// The heap reallocation options. Specifying a value overrides the corresponding value specified in the flOptions parameter when the heap was created by
/// using the <c>HeapCreate</c> function. This parameter can be one or more of the following values.
/// </para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Value</term>
/// <term>Meaning</term>
/// </listheader>
/// <item>
/// <term>HEAP_GENERATE_EXCEPTIONS0x00000004</term>
/// <term>
/// The operating-system raises an exception to indicate a function failure, such as an out-of-memory condition, instead of returning NULL.To ensure that
/// exceptions are generated for all calls to this function, specify HEAP_GENERATE_EXCEPTIONS in the call to HeapCreate. In this case, it is not
/// necessary to additionally specify HEAP_GENERATE_EXCEPTIONS in this function call.
/// </term>
/// </item>
/// <item>
/// <term>HEAP_NO_SERIALIZE0x00000001</term>
/// <term>
/// Serialized access will not be used. For more information, see Remarks.To ensure that serialized access is disabled for all calls to this function,
/// specify HEAP_NO_SERIALIZE in the call to HeapCreate. In this case, it is not necessary to additionally specify HEAP_NO_SERIALIZE in this function
/// call.This value should not be specified when accessing the process heap. The system may create additional threads within the application&amp;#39;s
/// process, such as a CTRL+C handler, that simultaneously access the process heap.
/// </term>
/// </item>
/// <item>
/// <term>HEAP_REALLOC_IN_PLACE_ONLY0x00000010</term>
/// <term>
/// There can be no movement when reallocating a memory block. If this value is not specified, the function may move the block to a new location. If this
/// value is specified and the block cannot be resized without moving, the function fails, leaving the original memory block unchanged.
/// </term>
/// </item>
/// <item>
/// <term>HEAP_ZERO_MEMORY0x00000008</term>
/// <term>
/// If the reallocation request is for a larger size, the additional region of memory beyond the original size be initialized to zero. The contents of
/// the memory block up to its original size are unaffected.
/// </term>
/// </item>
/// </list>
/// </para>
/// </param>
/// <param name="lpMem">
/// A pointer to the block of memory that the function reallocates. This pointer is returned by an earlier call to the <c>HeapAlloc</c> or
/// <c>HeapReAlloc</c> function.
/// </param>
/// <param name="dwBytes">
/// <para>The new size of the memory block, in bytes. A memory block's size can be increased or decreased by using this function.</para>
/// <para>
/// If the heap specified by the hHeap parameter is a "non-growable" heap, dwBytes must be less than 0x7FFF8. You create a non-growable heap by calling
/// the <c>HeapCreate</c> function with a nonzero value.
/// </para>
/// </param>
/// <returns>
/// <para>If the function succeeds, the return value is a pointer to the reallocated memory block.</para>
/// <para>If the function fails and you have not specified <c>HEAP_GENERATE_EXCEPTIONS</c>, the return value is <c>NULL</c>.</para>
/// <para>
/// If the function fails and you have specified <c>HEAP_GENERATE_EXCEPTIONS</c>, the function may generate either of the exceptions listed in the
/// following table. For more information, see <c>GetExceptionCode</c>.
/// </para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Exception code</term>
/// <term>Description</term>
/// </listheader>
/// <item>
/// <term>STATUS_NO_MEMORY</term>
/// <term>The allocation attempt failed because of a lack of available memory or heap corruption.</term>
/// </item>
/// <item>
/// <term>STATUS_ACCESS_VIOLATION</term>
/// <term>The allocation attempt failed because of heap corruption or improper function parameters.</term>
/// </item>
/// </list>
/// </para>
/// <para>If the function fails, it does not call <c>SetLastError</c>. An application cannot call <c>GetLastError</c> for extended error information.</para>
/// </returns>
// LPVOID WINAPI HeapReAlloc( _In_ HANDLE hHeap, _In_ DWORD dwFlags, _In_ LPVOID lpMem, _In_ SIZE_T dwBytes);// https://msdn.microsoft.com/en-us/library/windows/desktop/aa366704(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("HeapApi.h", MSDNShortId = "aa366704")]
public static extern IntPtr HeapReAlloc(IntPtr hHeap, HeapFlags dwFlags, IntPtr lpMem, SizeT dwBytes);
/// <summary>Enables features for a specified heap.</summary>
/// <param name="HeapHandle">
/// A handle to the heap where information is to be set. This handle is returned by either the <c>HeapCreate</c> or <c>GetProcessHeap</c> function.
/// </param>
/// <param name="HeapInformationClass">
/// <para>The class of information to be set. This parameter can be one of the following values from the <c>HEAP_INFORMATION_CLASS</c> enumeration type.</para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Value</term>
/// <term>Meaning</term>
/// </listheader>
/// <item>
/// <term>HeapCompatibilityInformation0</term>
/// <term>
/// Enables heap features. Only the low-fragmentation heap (LFH) is supported. However, it is not necessary for applications to enable the LFH because
/// the system uses the LFH as needed to service memory allocation requests. Windows XP and Windows Server 2003: The LFH is not enabled by default. To
/// enable the LFH for the specified heap, set the variable pointed to by the HeapInformation parameter to 2. After the LFH is enabled for a heap, it
/// cannot be disabled.The LFH cannot be enabled for heaps created with HEAP_NO_SERIALIZE or for heaps created with a fixed size. The LFH also cannot be
/// enabled if you are using the heap debugging tools in Debugging Tools for Windows or Microsoft Application Verifier.When a process is run under any
/// debugger, certain heap debug options are automatically enabled for all heaps in the process. These heap debug options prevent the use of the LFH. To
/// enable the low-fragmentation heap when running under a debugger, set the _NO_DEBUG_HEAP environment variable to 1.
/// </term>
/// </item>
/// <item>
/// <term>HeapEnableTerminationOnCorruption1</term>
/// <term>
/// Enables the terminate-on-corruption feature. If the heap manager detects an error in any heap used by the process, it calls the Windows Error
/// Reporting service and terminates the process.After a process enables this feature, it cannot be disabled.Windows Server 2003 and Windows XP: This
/// value is not supported until Windows Vista and Windows XP with SP3. The function succeeds but the HeapEnableTerminationOnCorruption value is ignored.
/// </term>
/// </item>
/// <item>
/// <term>HeapOptimizeResources3</term>
/// <term>
/// If HeapSetInformation is called with HeapHandle set to NULL, then all heaps in the process with a low-fragmentation heap (LFH) will have their caches
/// optimized, and the memory will be decommitted if possible. If a heap pointer is supplied in HeapHandle, then only that heap will be optimized.Note
/// that the HEAP_OPTIMIZE_RESOURCES_INFORMATION structure passed in HeapInformation must be properly initialized.Note This value was added in Windows 8.1.
/// </term>
/// </item>
/// </list>
/// </para>
/// </param>
/// <param name="HeapInformation">
/// <para>The heap information buffer. The format of this data depends on the value of the HeapInformationClass parameter.</para>
/// <para>
/// If the HeapInformationClass parameter is <c>HeapCompatibilityInformation</c>, the HeapInformation parameter is a pointer to a <c>ULONG</c> variable.
/// </para>
/// <para>
/// If the HeapInformationClass parameter is <c>HeapEnableTerminationOnCorruption</c>, the HeapInformation parameter should be <c>NULL</c> and
/// HeapInformationLength should be 0
/// </para>
/// </param>
/// <param name="HeapInformationLength">The size of the HeapInformation buffer, in bytes.</param>
/// <returns>
/// <para>If the function succeeds, the return value is nonzero.</para>
/// <para>If the function fails, the return value is 0 (zero). To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// BOOL WINAPI HeapSetInformation( _In_opt_ HANDLE HeapHandle, _In_ HEAP_INFORMATION_CLASS HeapInformationClass, _In_ PVOID HeapInformation, _In_ SIZE_T
// HeapInformationLength);// https://msdn.microsoft.com/en-us/library/windows/desktop/aa366705(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("HeapApi.h", MSDNShortId = "aa366705")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool HeapSetInformation([In] IntPtr HeapHandle, HEAP_INFORMATION_CLASS HeapInformationClass, [In] IntPtr HeapInformation, uint HeapInformationLength);
/// <summary>Retrieves the size of a memory block allocated from a heap by the HeapAlloc or HeapReAlloc function.</summary>
/// <param name="hHeap">A handle to the heap in which the memory block resides. This handle is returned by either the HeapCreate or GetProcessHeap function.</param>
/// <param name="dwFlags">The heap size options. Specifying the following value overrides the corresponding value specified in the flOptions parameter when the heap was created by using the HeapCreate function.</param>
/// <param name="lpMem">A pointer to the memory block whose size the function will obtain. This is a pointer returned by the HeapAlloc or HeapReAlloc function. The memory block must be from the heap specified by the hHeap parameter.</param>
/// <returns>If the function succeeds, the return value is the requested size of the allocated memory block, in bytes.
/// <para>If the function fails, the return value is (SIZE_T)-1. The function does not call SetLastError. An application cannot call GetLastError for extended error information.</para>
/// <para>If the lpMem parameter refers to a heap allocation that is not in the heap specified by the hHeap parameter, the behavior of the HeapSize function is undefined.</para></returns>
/// <param name="hHeap">
/// A handle to the heap in which the memory block resides. This handle is returned by either the HeapCreate or GetProcessHeap function.
/// </param>
/// <param name="dwFlags">
/// The heap size options. Specifying the following value overrides the corresponding value specified in the flOptions parameter when the heap was
/// created by using the HeapCreate function.
/// </param>
/// <param name="lpMem">
/// A pointer to the memory block whose size the function will obtain. This is a pointer returned by the HeapAlloc or HeapReAlloc function. The memory
/// block must be from the heap specified by the hHeap parameter.
/// </param>
/// <returns>
/// If the function succeeds, the return value is the requested size of the allocated memory block, in bytes.
/// <para>
/// If the function fails, the return value is (SIZE_T)-1. The function does not call SetLastError. An application cannot call GetLastError for extended
/// error information.
/// </para>
/// <para>
/// If the lpMem parameter refers to a heap allocation that is not in the heap specified by the hHeap parameter, the behavior of the HeapSize function is undefined.
/// </para>
/// </returns>
[PInvokeData("HeapApi.h", MSDNShortId = "aa366706")]
[DllImport(Lib.Kernel32, ExactSpelling = true, SetLastError = true)]
[return: MarshalAs(UnmanagedType.SysInt)]
public static extern IntPtr HeapSize(IntPtr hHeap, HeapFlags dwFlags, IntPtr lpMem);
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("HeapApi.h", MSDNShortId = "")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool HeapSummary([In] IntPtr hHeap, HeapFlags dwFlags, out HEAP_SUMMARY lpSummary);
/// <summary>
/// Releases ownership of the critical section object, or lock, that is associated with a specified heap. It reverses the action of the <c>HeapLock</c> function.
/// </summary>
/// <param name="hHeap">A handle to the heap to be unlocked. This handle is returned by either the <c>HeapCreate</c> or <c>GetProcessHeap</c> function.</param>
/// <returns>
/// <para>If the function succeeds, the return value is nonzero.</para>
/// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// BOOL WINAPI HeapUnlock( _In_ HANDLE hHeap);// https://msdn.microsoft.com/en-us/library/windows/desktop/aa366707(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("HeapApi.h", MSDNShortId = "aa366707")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool HeapUnlock([In] IntPtr hHeap);
/// <summary>
/// Validates the specified heap. The function scans all the memory blocks in the heap and verifies that the heap control structures maintained by the
/// heap manager are in a consistent state. You can also use the <c>HeapValidate</c> function to validate a single memory block within a specified heap
/// without checking the validity of the entire heap.
/// </summary>
/// <param name="hHeap">A handle to the heap to be validated. This handle is returned by either the <c>HeapCreate</c> or <c>GetProcessHeap</c> function.</param>
/// <param name="dwFlags">
/// <para>The heap access options. This parameter can be the following value.</para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Value</term>
/// <term>Meaning</term>
/// </listheader>
/// <item>
/// <term>HEAP_NO_SERIALIZE0x00000001</term>
/// <term>
/// Serialized access will not be used. For more information, see Remarks.To ensure that serialized access is disabled for all calls to this function,
/// specify HEAP_NO_SERIALIZE in the call to HeapCreate. In this case, it is not necessary to additionally specify HEAP_NO_SERIALIZE in this function
/// call.This value should not be specified when accessing the process default heap. The system may create additional threads within the
/// application&amp;#39;s process, such as a CTRL+C handler, that simultaneously access the process default heap.
/// </term>
/// </item>
/// </list>
/// </para>
/// </param>
/// <param name="lpMem">
/// <para>A pointer to a memory block within the specified heap. This parameter may be <c>NULL</c>.</para>
/// <para>If this parameter is <c>NULL</c>, the function attempts to validate the entire heap specified by hHeap.</para>
/// <para>
/// If this parameter is not <c>NULL</c>, the function attempts to validate the memory block pointed to by lpMem. It does not attempt to validate the
/// rest of the heap.
/// </para>
/// </param>
/// <returns>
/// <para>If the specified heap or memory block is valid, the return value is nonzero.</para>
/// <para>
/// If the specified heap or memory block is invalid, the return value is zero. On a system set up for debugging, the <c>HeapValidate</c> function then
/// displays debugging messages that describe the part of the heap or memory block that is invalid, and stops at a hard-coded breakpoint so that you can
/// examine the system to determine the source of the invalidity. The <c>HeapValidate</c> function does not set the thread's last error value. There is
/// no extended error information for this function; do not call <c>GetLastError</c>.
/// </para>
/// </returns>
// BOOL WINAPI HeapValidate( _In_ HANDLE hHeap, _In_ DWORD dwFlags, _In_opt_ LPCVOID lpMem);// https://msdn.microsoft.com/en-us/library/windows/desktop/aa366708(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("HeapApi.h", MSDNShortId = "aa366708")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool HeapValidate([In] IntPtr hHeap, HeapFlags dwFlags, [In] IntPtr lpMem);
/// <summary>Enumerates the memory blocks in the specified heap.</summary>
/// <param name="hHeap">A handle to the heap. This handle is returned by either the <c>HeapCreate</c> or <c>GetProcessHeap</c> function.</param>
/// <param name="lpEntry">
/// <para>A pointer to a <c>PROCESS_HEAP_ENTRY</c> structure that maintains state information for a particular heap enumeration.</para>
/// <para>
/// If the <c>HeapWalk</c> function succeeds, returning the value <c>TRUE</c>, this structure's members contain information about the next memory block
/// in the heap.
/// </para>
/// <para>
/// To initiate a heap enumeration, set the <c>lpData</c> field of the <c>PROCESS_HEAP_ENTRY</c> structure to <c>NULL</c>. To continue a particular heap
/// enumeration, call the <c>HeapWalk</c> function repeatedly, with no changes to hHeap, lpEntry, or any of the members of the <c>PROCESS_HEAP_ENTRY</c> structure.
/// </para>
/// </param>
/// <returns>
/// <para>If the function succeeds, the return value is nonzero.</para>
/// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para>
/// <para>
/// If the heap enumeration terminates successfully by reaching the end of the heap, the function returns <c>FALSE</c>, and <c>GetLastError</c> returns
/// the error code <c>ERROR_NO_MORE_ITEMS</c>.
/// </para>
/// </returns>
// BOOL WINAPI HeapWalk( _In_ HANDLE hHeap, _Inout_ LPPROCESS_HEAP_ENTRY lpEntry);// https://msdn.microsoft.com/en-us/library/windows/desktop/aa366710(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("HeapApi.h", MSDNShortId = "aa366710")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool HeapWalk([In] IntPtr hHeap, ref PROCESS_HEAP_ENTRY lpEntry);
/// <summary>Specifies flags for a HeapOptimizeResources operation initiated with HeapSetInformation.</summary>
[StructLayout(LayoutKind.Sequential)]
public struct HEAP_OPTIMIZE_RESOURCES_INFORMATION
{
/// <summary>The version</summary>
public uint Version;
/// <summary>The flags</summary>
public uint Flags;
}
[StructLayout(LayoutKind.Sequential)]
public struct HEAP_SUMMARY
{
public uint cb;
public SizeT cbAllocated;
public SizeT cbCommitted;
public SizeT cbReserved;
public SizeT cbMaxReserve;
}
/// <summary>
/// Contains information about a heap element. The <c>HeapWalk</c> function uses a <c>PROCESS_HEAP_ENTRY</c> structure to enumerate the elements of a heap.
/// </summary>
// typedef struct _PROCESS_HEAP_ENTRY { PVOID lpData; DWORD cbData; BYTE cbOverhead; BYTE iRegionIndex; WORD wFlags; union { struct { HANDLE hMem; DWORD
// dwReserved[3]; } Block; struct { DWORD dwCommittedSize; DWORD dwUnCommittedSize; LPVOID lpFirstBlock; LPVOID lpLastBlock; } Region; };}
// PROCESS_HEAP_ENTRY, *LPPROCESS_HEAP_ENTRY; https://msdn.microsoft.com/en-us/library/windows/desktop/aa366798(v=vs.85).aspx
[PInvokeData("WinBase.h", MSDNShortId = "aa366798")]
[StructLayout(LayoutKind.Sequential)]
public struct PROCESS_HEAP_ENTRY
{
/// <summary>
/// <para>A pointer to the data portion of the heap element.</para>
/// <para>To initiate a <c>HeapWalk</c> heap enumeration, set <c>lpData</c> to <c>NULL</c>.</para>
/// <para>If <c>PROCESS_HEAP_REGION</c> is used in the <c>wFlags</c> member, <c>lpData</c> points to the first virtual address used by the region.</para>
/// <para>If <c>PROCESS_HEAP_UNCOMMITTED_RANGE</c> is used in <c>wFlags</c>, <c>lpData</c> points to the beginning of the range of uncommitted memory.</para>
/// </summary>
public IntPtr lpData;
/// <summary>
/// <para>The size of the data portion of the heap element, in bytes.</para>
/// <para>
/// If <c>PROCESS_HEAP_REGION</c> is used in <c>wFlags</c>, <c>cbData</c> specifies the total size, in bytes, of the address space that is reserved
/// for this region.
/// </para>
/// <para>
/// If <c>PROCESS_HEAP_UNCOMMITTED_RANGE</c> is used in <c>wFlags</c>, <c>cbData</c> specifies the size, in bytes, of the range of uncommitted memory.
/// </para>
/// </summary>
public uint cbData;
/// <summary>
/// <para>
/// The size of the data used by the system to maintain information about the heap element, in bytes. These overhead bytes are in addition to the
/// <c>cbData</c> bytes of the data portion of the heap element.
/// </para>
/// <para>
/// If <c>PROCESS_HEAP_REGION</c> is used in <c>wFlags</c>, <c>cbOverhead</c> specifies the size, in bytes, of the heap control structures that
/// describe the region.
/// </para>
/// <para>
/// If <c>PROCESS_HEAP_UNCOMMITTED_RANGE</c> is used in <c>wFlags</c>, <c>cbOverhead</c> specifies the size, in bytes, of the control structures that
/// describe this uncommitted range.
/// </para>
/// </summary>
public byte cbOverhead;
/// <summary>
/// <para>
/// A handle to the heap region that contains the heap element. A heap consists of one or more regions of virtual memory, each with a unique region index.
/// </para>
/// <para>
/// In the first heap entry returned for most heap regions, <c>HeapWalk</c> uses the <c>PROCESS_HEAP_REGION</c> in the <c>wFlags</c> member. When
/// this value is used, the members of the <c>Region</c> structure contain additional information about the region.
/// </para>
/// <para>
/// The <c>HeapAlloc</c> function sometimes uses the <c>VirtualAlloc</c> function to allocate large blocks from a growable heap. The heap manager
/// treats such a large block allocation as a separate region with a unique region index. <c>HeapWalk</c> does not use <c>PROCESS_HEAP_REGION</c> in
/// the heap entry returned for a large block region, so the members of the <c>Region</c> structure are not valid. You can use the
/// <c>VirtualQuery</c> function to get additional information about a large block region.
/// </para>
/// </summary>
public byte iRegionIndex;
/// <summary>
/// <para>
/// The properties of the heap element. Some values affect the meaning of other members of this <c>PROCESS_HEAP_ENTRY</c> data structure. The
/// following values are defined.
/// </para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Value</term>
/// <term>Meaning</term>
/// </listheader>
/// <item>
/// <term>PROCESS_HEAP_ENTRY_BUSY0x0004</term>
/// <term>
/// The heap element is an allocated block.If PROCESS_HEAP_ENTRY_MOVEABLE is also specified, the Block structure becomes valid. The hMem member of
/// the Block structure contains a handle to the allocated, moveable memory block.
/// </term>
/// </item>
/// <item>
/// <term>PROCESS_HEAP_ENTRY_DDESHARE0x0020</term>
/// <term>This value must be used with PROCESS_HEAP_ENTRY_BUSY, indicating that the heap element is an allocated block.</term>
/// </item>
/// <item>
/// <term>PROCESS_HEAP_ENTRY_MOVEABLE0x0010</term>
/// <term>
/// This value must be used with PROCESS_HEAP_ENTRY_BUSY, indicating that the heap element is an allocated block.The block was allocated with
/// LMEM_MOVEABLE or GMEM_MOVEABLE, and the Block structure becomes valid. The hMem member of the Block structure contains a handle to the allocated,
/// moveable memory block.
/// </term>
/// </item>
/// <item>
/// <term>PROCESS_HEAP_REGION0x0001</term>
/// <term>
/// The heap element is located at the beginning of a region of contiguous virtual memory in use by the heap.The lpData member of the structure
/// points to the first virtual address used by the region; the cbData member specifies the total size, in bytes, of the address space that is
/// reserved for this region; and the cbOverhead member specifies the size, in bytes, of the heap control structures that describe the region.The
/// Region structure becomes valid. The dwCommittedSize, dwUnCommittedSize, lpFirstBlock, and lpLastBlock members of the structure contain additional
/// information about the region.
/// </term>
/// </item>
/// <item>
/// <term>PROCESS_HEAP_UNCOMMITTED_RANGE0x0002</term>
/// <term>
/// The heap element is located in a range of uncommitted memory within the heap region.The lpData member points to the beginning of the range of
/// uncommitted memory; the cbData member specifies the size, in bytes, of the range of uncommitted memory; and the cbOverhead member specifies the
/// size, in bytes, of the control structures that describe this uncommitted range.
/// </term>
/// </item>
/// </list>
/// </para>
/// </summary>
public PROCESS_HEAP wFlags;
/// <summary>A union</summary>
public BLOCK_REGION_UNION union;
/// <summary>Union of child structures.</summary>
[StructLayout(LayoutKind.Explicit)]
public struct BLOCK_REGION_UNION
{
/// <summary>
/// This structure is valid only if both the <c>PROCESS_HEAP_ENTRY_BUSY</c> and <c>PROCESS_HEAP_ENTRY_MOVEABLE</c> are specified in <c>wFlags</c>.
/// </summary>
[FieldOffset(0)]
public BLOCK_DATA Block;
/// <summary>This structure is valid only if the <c>wFlags</c> member specifies <c>PROCESS_HEAP_REGION</c>.</summary>
[FieldOffset(0)]
public REGION_DATA Region;
/// <summary>
/// This structure is valid only if both the <c>PROCESS_HEAP_ENTRY_BUSY</c> and <c>PROCESS_HEAP_ENTRY_MOVEABLE</c> are specified in <c>wFlags</c>.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct BLOCK_DATA
{
/// <summary>Handle to the allocated, moveable memory block.</summary>
public IntPtr hMem;
/// <summary>Reserved; not used.</summary>
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 3, ArraySubType = UnmanagedType.U4)]
public uint[] dwReserved;
}
/// <summary>This structure is valid only if the <c>wFlags</c> member specifies <c>PROCESS_HEAP_REGION</c>.</summary>
[StructLayout(LayoutKind.Sequential)]
public struct REGION_DATA
{
/// <summary>
/// Number of bytes in the heap region that are currently committed as free memory blocks, busy memory blocks, or heap control structures.
/// This is an optional field that is set to zero if the number of committed bytes is not available.
/// </summary>
public uint dwCommittedSize;
/// <summary>
/// Number of bytes in the heap region that are currently uncommitted. This is an optional field that is set to zero if the number of
/// uncommitted bytes is not available.
/// </summary>
public uint dwUnCommittedSize;
/// <summary>Pointer to the first valid memory block in this heap region.</summary>
public IntPtr lpFirstBlock;
/// <summary>Pointer to the first invalid memory block in this heap region.</summary>
public IntPtr lpLastBlock;
}
}
}
/// <summary>Safe handle for memory heaps.</summary>
/// <seealso cref="Vanara.InteropServices.GenericSafeHandle"/>
public class SafePrivateHeapBlockHandle : GenericSafeHandle
@ -112,7 +822,9 @@ namespace Vanara.PInvoke
this.hHeap = hHeap;
}
/// <summary>Initializes a new instance of the <see cref="SafePrivateHeapBlockHandle"/> class and allocates the specified amount of memory from the process heap.</summary>
/// <summary>
/// Initializes a new instance of the <see cref="SafePrivateHeapBlockHandle"/> class and allocates the specified amount of memory from the process heap.
/// </summary>
/// <param name="hHeap">A handle to a heap created using <see cref="HeapCreate"/>.</param>
/// <param name="size">The size. This value cannot be zero.</param>
public SafePrivateHeapBlockHandle(SafePrivateHeapHandle hHeap, int size) : this(hHeap, HeapAlloc(hHeap, HeapFlags.HEAP_ZERO_MEMORY, (IntPtr)size)) { }
@ -122,27 +834,6 @@ namespace Vanara.PInvoke
public long Size => HeapSize(hHeap, 0, handle).ToInt64();
}
/// <summary>Safe handle for memory heaps.</summary>
/// <seealso cref="Vanara.InteropServices.GenericSafeHandle"/>
public class SafeProcessHeapBlockHandle : GenericSafeHandle
{
/// <summary>Initializes a new instance of the <see cref="SafeProcessHeapBlockHandle"/> class.</summary>
public SafeProcessHeapBlockHandle() : this(IntPtr.Zero) { }
/// <summary>Initializes a new instance of the <see cref="SafeProcessHeapBlockHandle"/> class.</summary>
/// <param name="ptr">The handle created by <see cref="HeapAlloc"/>.</param>
/// <param name="own">if set to <c>true</c> this safe handle disposes the handle when done.</param>
public SafeProcessHeapBlockHandle(IntPtr ptr, bool own = true) : base(ptr, h => HeapFree(GetProcessHeap(), 0, h), own) { }
/// <summary>Initializes a new instance of the <see cref="SafeProcessHeapBlockHandle"/> class and allocates the specified amount of memory from the process heap.</summary>
/// <param name="size">The size. This value cannot be zero.</param>
public SafeProcessHeapBlockHandle(ulong size) : this(HeapAlloc(GetProcessHeap(), HeapFlags.HEAP_ZERO_MEMORY, (IntPtr)size)) { }
/// <summary>Retrieves the size of this memory block.</summary>
/// <value>The size in bytes of this memory block.</value>
public long Size => HeapSize(GetProcessHeap(), 0, handle).ToInt64();
}
/// <summary>Safe handle for memory heaps.</summary>
/// <seealso cref="Vanara.InteropServices.GenericSafeHandle"/>
public class SafePrivateHeapHandle : GenericSafeHandle
@ -160,5 +851,28 @@ namespace Vanara.PInvoke
/// <returns>A safe handle for the memory that will call HeapFree on disposal.</returns>
public SafePrivateHeapBlockHandle GetBlock(int size) => new SafePrivateHeapBlockHandle(this, size);
}
/// <summary>Safe handle for memory heaps.</summary>
/// <seealso cref="Vanara.InteropServices.GenericSafeHandle"/>
public class SafeProcessHeapBlockHandle : GenericSafeHandle
{
/// <summary>Initializes a new instance of the <see cref="SafeProcessHeapBlockHandle"/> class.</summary>
public SafeProcessHeapBlockHandle() : this(IntPtr.Zero) { }
/// <summary>Initializes a new instance of the <see cref="SafeProcessHeapBlockHandle"/> class.</summary>
/// <param name="ptr">The handle created by <see cref="HeapAlloc"/>.</param>
/// <param name="own">if set to <c>true</c> this safe handle disposes the handle when done.</param>
public SafeProcessHeapBlockHandle(IntPtr ptr, bool own = true) : base(ptr, h => HeapFree(GetProcessHeap(), 0, h), own) { }
/// <summary>
/// Initializes a new instance of the <see cref="SafeProcessHeapBlockHandle"/> class and allocates the specified amount of memory from the process heap.
/// </summary>
/// <param name="size">The size. This value cannot be zero.</param>
public SafeProcessHeapBlockHandle(ulong size) : this(HeapAlloc(GetProcessHeap(), HeapFlags.HEAP_ZERO_MEMORY, (IntPtr)size)) { }
/// <summary>Retrieves the size of this memory block.</summary>
/// <value>The size in bytes of this memory block.</value>
public long Size => HeapSize(GetProcessHeap(), 0, handle).ToInt64();
}
}
}

View File

@ -0,0 +1,83 @@
using System;
using System.Runtime.InteropServices;
namespace Vanara.PInvoke
{
public static partial class Kernel32
{
/// <summary>Initializes the head of a singly linked list.</summary>
/// <param name="ListHead">
/// A pointer to an <c>SLIST_HEADER</c> structure that represents the head of a singly linked list. This structure is for system use only.
/// </param>
/// <returns>This function does not return a value.</returns>
// void WINAPI InitializeSListHead( _Inout_ PSLIST_HEADER ListHead); https://msdn.microsoft.com/en-us/library/windows/desktop/ms683482(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms683482")]
public static extern void InitializeSListHead(IntPtr ListHead);
/// <summary>Removes all items from a singly linked list. Access to the list is synchronized on a multiprocessor system.</summary>
/// <param name="ListHead">
/// Pointer to an <c>SLIST_HEADER</c> structure that represents the head of the singly linked list. This structure is for system use only.
/// </param>
/// <returns>The return value is a pointer to the items removed from the list. If the list is empty, the return value is <c>NULL</c>.</returns>
// PSLIST_ENTRY WINAPI InterlockedFlushSList( _Inout_ PSLIST_HEADER ListHead); https://msdn.microsoft.com/en-us/library/windows/desktop/ms683612(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms683612")]
public static extern IntPtr InterlockedFlushSList(IntPtr ListHead);
/// <summary>Removes an item from the front of a singly linked list. Access to the list is synchronized on a multiprocessor system.</summary>
/// <param name="ListHead">Pointer to an <c>SLIST_HEADER</c> structure that represents the head of a singly linked list.</param>
/// <returns>The return value is a pointer to the item removed from the list. If the list is empty, the return value is <c>NULL</c>.</returns>
// PSLIST_ENTRY WINAPI InterlockedPopEntrySList( _Inout_ PSLIST_HEADER ListHead); https://msdn.microsoft.com/en-us/library/windows/desktop/ms683648(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms683648")]
public static extern IntPtr InterlockedPopEntrySList(IntPtr ListHead);
/// <summary>Inserts an item at the front of a singly linked list. Access to the list is synchronized on a multiprocessor system.</summary>
/// <param name="ListHead">Pointer to an <c>SLIST_HEADER</c> structure that represents the head of a singly linked list.</param>
/// <param name="ListEntry">Pointer to an <c>SLIST_ENTRY</c> structure that represents an item in a singly linked list.</param>
/// <returns>The return value is the previous first item in the list. If the list was previously empty, the return value is <c>NULL</c>.</returns>
// PSLIST_ENTRY WINAPI InterlockedPushEntrySList( _Inout_ PSLIST_HEADER ListHead, _Inout_ PSLIST_ENTRY ListEntry); https://msdn.microsoft.com/en-us/library/windows/desktop/ms684020(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms684020")]
public static extern IntPtr InterlockedPushEntrySList(IntPtr ListHead, IntPtr ListEntry);
/// <summary>
/// Inserts a singly-linked list at the front of another singly linked list. Access to the lists is synchronized on a multiprocessor system. This version
/// of the method does not use the __fastcall calling convention.
/// </summary>
/// <param name="ListHead">
/// Pointer to an <c>SLIST_HEADER</c> structure that represents the head of a singly linked list. The list specified by the List and ListEnd parameters
/// is inserted at the front of this list.
/// </param>
/// <param name="List">Pointer to an <c>SLIST_ENTRY</c> structure that represents the first item in the list to be inserted.</param>
/// <param name="ListEnd">Pointer to an <c>SLIST_ENTRY</c> structure that represents the last item in the list to be inserted.</param>
/// <param name="Count">The number of items in the list to be inserted.</param>
/// <returns>
/// The return value is the previous first item in the list specified by the ListHead parameter. If the list was previously empty, the return value is <c>NULL</c>.
/// </returns>
// PSLIST_ENTRY WINAPI InterlockedPushListSListEx( _Inout_ PSLIST_HEADER ListHead, _Inout_ PSLIST_ENTRY List, _Inout_ PSLIST_ENTRY ListEnd, _In_ ULONG
// Count); https://msdn.microsoft.com/en-us/library/windows/desktop/hh972673(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)]
[PInvokeData("Interlockedapi.h", MSDNShortId = "hh972673")]
public static extern IntPtr InterlockedPushListSListEx(IntPtr ListHead, IntPtr List, IntPtr ListEnd, uint Count);
/// <summary>Retrieves the number of entries in the specified singly linked list.</summary>
/// <param name="ListHead">
/// <para>A pointer to an <c>SLIST_HEADER</c> structure that represents the head of a singly linked list. This structure is for system use only.</para>
/// <para>The list must be previously initialized with the <c>InitializeSListHead</c> function.</para>
/// </param>
/// <returns>The function returns the number of entries in the list, up to a maximum value of 65535.</returns>
// USHORT WINAPI QueryDepthSList( _In_ PSLIST_HEADER ListHead);// https://msdn.microsoft.com/en-us/library/windows/desktop/ms684916(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms684916")]
public static extern ushort QueryDepthSList(IntPtr ListHead);
/*[StructLayout(LayoutKind.Sequential)]
public struct SLIST_HEADER
{
private IntPtr Alignment;
private IntPtr Next;
}*/
}
}

View File

@ -14,9 +14,9 @@ namespace Vanara.InteropServices
public sealed class LocalMemoryMethods : IMemoryMethods
{
/// <summary>Gets the allocation method.</summary>
public Func<int, IntPtr> AllocMem => i => { var o = LocalAlloc(LocalMemoryFlags.LPTR, (UIntPtr)i); return o != IntPtr.Zero ? o : throw Win32Error.GetLastError().GetException(); };
public Func<int, IntPtr> AllocMem => i => { var o = LocalAlloc(LMEM.LPTR, (UIntPtr)i); return o != IntPtr.Zero ? o : throw Win32Error.GetLastError().GetException(); };
/// <summary>Gets the reallocation method.</summary>
public Func<IntPtr, int, IntPtr> ReAllocMem => (p, i) => { var o = LocalReAlloc(p, (UIntPtr)i, LocalMemoryFlags.LMEM_MOVEABLE); return o != IntPtr.Zero ? o : throw Win32Error.GetLastError().GetException(); };
public Func<IntPtr, int, IntPtr> ReAllocMem => (p, i) => { var o = LocalReAlloc(p, (UIntPtr)i, LMEM.LMEM_MOVEABLE); return o != IntPtr.Zero ? o : throw Win32Error.GetLastError().GetException(); };
/// <summary>Gets the free method.</summary>
public Action<IntPtr> FreeMem => p => LocalFree(p);
/// <summary>Gets the Unicode string allocation method.</summary>

View File

@ -6,9 +6,6 @@ using System.Threading;
using Vanara.Extensions;
using Vanara.InteropServices;
// ReSharper disable FieldCanBeMadeReadOnly.Global
// ReSharper disable InconsistentNaming
namespace Vanara.PInvoke
{
public static partial class Kernel32
@ -126,7 +123,8 @@ namespace Vanara.PInvoke
}
/// <summary>
/// Starts the asynchronous operation of sending a control code directly to a specified device driver, causing the corresponding device to perform the corresponding operation.
/// Starts the asynchronous operation of sending a control code directly to a specified device driver, causing the corresponding device to perform the
/// corresponding operation.
/// </summary>
/// <typeparam name="TIn">The type of the <paramref name="inVal"/>.</typeparam>
/// <typeparam name="TOut">The type of the <paramref name="outVal"/>.</typeparam>
@ -134,11 +132,17 @@ namespace Vanara.PInvoke
/// A handle to the device on which the operation is to be performed. The device is typically a volume, directory, file, or stream. To retrieve a device
/// handle, use the CreateFile function. For more information, see Remarks.
/// </param>
/// <param name="dwIoControlCode">The control code for the operation. This value identifies the specific operation to be performed and the type of device on which to perform it.</param>
/// <param name="inVal">A pointer to the input buffer that contains the data required to perform the operation. The format of this data depends on the value of the dwIoControlCode parameter.
/// <param name="dwIoControlCode">
/// The control code for the operation. This value identifies the specific operation to be performed and the type of device on which to perform it.
/// </param>
/// <param name="inVal">
/// A pointer to the input buffer that contains the data required to perform the operation. The format of this data depends on the value of the
/// dwIoControlCode parameter.
/// <para>This parameter can be NULL if dwIoControlCode specifies an operation that does not require input data.</para>
/// </param>
/// <param name="outVal">A pointer to the output buffer that is to receive the data returned by the operation. The format of this data depends on the value of the dwIoControlCode parameter.
/// <param name="outVal">
/// A pointer to the output buffer that is to receive the data returned by the operation. The format of this data depends on the value of the
/// dwIoControlCode parameter.
/// <para>This parameter can be NULL if dwIoControlCode specifies an operation that does not return data.</para>
/// </param>
/// <param name="userCallback">An AsyncCallback delegate that references the method to invoke when the operation is complete.</param>
@ -150,24 +154,180 @@ namespace Vanara.PInvoke
return BeginDeviceIoControl<TIn, TOut>(hDevice, dwIoControlCode, buffer, userCallback, null);
}
/// <summary>
/// <para>
/// Cancels all pending input and output (I/O) operations that are issued by the calling thread for the specified file. The function does not cancel I/O
/// operations that other threads issue for a file handle.
/// </para>
/// <para>To cancel I/O operations from another thread, use the <c>CancelIoEx</c> function.</para>
/// </summary>
/// <param name="hFile">
/// <para>A handle to the file.</para>
/// <para>The function cancels all pending I/O operations for this file handle.</para>
/// </param>
/// <returns>
/// <para>
/// If the function succeeds, the return value is nonzero. The cancel operation for all pending I/O operations issued by the calling thread for the
/// specified file handle was successfully requested. The thread can use the <c>GetOverlappedResult</c> function to determine when the I/O operations
/// themselves have been completed.
/// </para>
/// <para>If the function fails, the return value is zero (0). To get extended error information, call the <c>GetLastError</c> function.</para>
/// </returns>
// BOOL WINAPI CancelIo( _In_ HANDLE hFile);// https://msdn.microsoft.com/en-us/library/windows/desktop/aa363791(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("IoAPI.h", MSDNShortId = "aa363791")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool CancelIo([In] SafeFileHandle hFile);
/// <summary>
/// Marks any outstanding I/O operations for the specified file handle. The function only cancels I/O operations in the current process, regardless of
/// which thread created the I/O operation.
/// </summary>
/// <param name="hFile">A handle to the file.</param>
/// <param name="lpOverlapped">
/// <para>A pointer to an <c>OVERLAPPED</c> data structure that contains the data used for asynchronous I/O.</para>
/// <para>If this parameter is <c>NULL</c>, all I/O requests for the hFile parameter are canceled.</para>
/// <para>
/// If this parameter is not <c>NULL</c>, only those specific I/O requests that were issued for the file with the specified lpOverlapped overlapped
/// structure are marked as canceled, meaning that you can cancel one or more requests, while the <c>CancelIo</c> function cancels all outstanding
/// requests on a file handle.
/// </para>
/// </param>
/// <returns>
/// <para>
/// If the function succeeds, the return value is nonzero. The cancel operation for all pending I/O operations issued by the calling process for the
/// specified file handle was successfully requested. The application must not free or reuse the <c>OVERLAPPED</c> structure associated with the canceled
/// I/O operations until they have completed. The thread can use the <c>GetOverlappedResult</c> function to determine when the I/O operations themselves
/// have been completed.
/// </para>
/// <para>If the function fails, the return value is 0 (zero). To get extended error information, call the <c>GetLastError</c> function.</para>
/// <para>If this function cannot find a request to cancel, the return value is 0 (zero), and <c>GetLastError</c> returns <c>ERROR_NOT_FOUND</c>.</para>
/// </returns>
// BOOL WINAPI CancelIoEx( _In_ HANDLE hFile, _In_opt_ LPOVERLAPPED lpOverlapped);// https://msdn.microsoft.com/en-us/library/windows/desktop/aa363792(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("IoAPI.h", MSDNShortId = "aa363792")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern unsafe bool CancelIoEx([In] SafeFileHandle hFile, [In] NativeOverlapped* lpOverlapped);
/// <summary>Marks pending synchronous I/O operations that are issued by the specified thread as canceled.</summary>
/// <param name="hThread">A handle to the thread.</param>
/// <returns>
/// <para>If the function succeeds, the return value is nonzero.</para>
/// <para>If the function fails, the return value is 0 (zero). To get extended error information, call the <c>GetLastError</c> function.</para>
/// <para>If this function cannot find a request to cancel, the return value is 0 (zero), and <c>GetLastError</c> returns <c>ERROR_NOT_FOUND</c>.</para>
/// </returns>
// BOOL WINAPI CancelSynchronousIo( _In_ HANDLE hThread); https://msdn.microsoft.com/en-us/library/windows/desktop/aa363794(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("IoAPI.h", MSDNShortId = "aa363794")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern unsafe bool CancelSynchronousIo([In] IntPtr hThread);
/// <summary>
/// <para>
/// Creates an input/output (I/O) completion port and associates it with a specified file handle, or creates an I/O completion port that is not yet
/// associated with a file handle, allowing association at a later time.
/// </para>
/// <para>
/// Associating an instance of an opened file handle with an I/O completion port allows a process to receive notification of the completion of
/// asynchronous I/O operations involving that file handle.
/// </para>
/// </summary>
/// <param name="FileHandle">
/// <para>An open file handle or <c>INVALID_HANDLE_VALUE</c>.</para>
/// <para>The handle must be to an object that supports overlapped I/O.</para>
/// <para>
/// If a handle is provided, it has to have been opened for overlapped I/O completion. For example, you must specify the <c>FILE_FLAG_OVERLAPPED</c> flag
/// when using the <c>CreateFile</c> function to obtain the handle.
/// </para>
/// <para>
/// If <c>INVALID_HANDLE_VALUE</c> is specified, the function creates an I/O completion port without associating it with a file handle. In this case, the
/// ExistingCompletionPort parameter must be <c>NULL</c> and the CompletionKey parameter is ignored.
/// </para>
/// </param>
/// <param name="ExistingCompletionPort">
/// <para>A handle to an existing I/O completion port or <c>NULL</c>.</para>
/// <para>
/// If this parameter specifies an existing I/O completion port, the function associates it with the handle specified by the FileHandle parameter. The
/// function returns the handle of the existing I/O completion port if successful; it does not create a new I/O completion port.
/// </para>
/// <para>
/// If this parameter is <c>NULL</c>, the function creates a new I/O completion port and, if the FileHandle parameter is valid, associates it with the
/// new I/O completion port. Otherwise no file handle association occurs. The function returns the handle to the new I/O completion port if successful.
/// </para>
/// </param>
/// <param name="CompletionKey">
/// The per-handle user-defined completion key that is included in every I/O completion packet for the specified file handle. For more information, see
/// the Remarks section.
/// </param>
/// <param name="NumberOfConcurrentThreads">
/// <para>
/// The maximum number of threads that the operating system can allow to concurrently process I/O completion packets for the I/O completion port. This
/// parameter is ignored if the ExistingCompletionPort parameter is not <c>NULL</c>.
/// </para>
/// <para>If this parameter is zero, the system allows as many concurrently running threads as there are processors in the system.</para>
/// </param>
/// <returns>
/// <para>If the function succeeds, the return value is the handle to an I/O completion port:</para>
/// <para>If the function fails, the return value is <c>NULL</c>. To get extended error information, call the <c>GetLastError</c> function.</para>
/// </returns>
// HANDLE WINAPI CreateIoCompletionPort( _In_ HANDLE FileHandle, _In_opt_ HANDLE ExistingCompletionPort, _In_ ULONG_PTR CompletionKey, _In_ DWORD
// NumberOfConcurrentThreads); https://msdn.microsoft.com/en-us/library/windows/desktop/aa363862(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("IoAPI.h", MSDNShortId = "aa363862")]
public static extern IntPtr CreateIoCompletionPort([In] SafeFileHandle FileHandle, [In] IntPtr ExistingCompletionPort, UIntPtr CompletionKey, uint NumberOfConcurrentThreads);
/// <summary>This macro is used to create a unique system I/O control code (IOCTL).</summary>
/// <param name="deviceType">Defines the type of device for the given IOCTL. This parameter can be no bigger then a WORD value. The values used by Microsoft are in the range 0-32767 and the values 32768-65535 are reserved for use by OEMs and IHVs.</param>
/// <param name="function">Defines an action within the device category. That function codes 0-2047 are reserved for Microsoft, and 2048-4095 are reserved for OEMs and IHVs. The function code can be no larger then 4095.</param>
/// <param name="method">Defines the method codes for how buffers are passed for I/O and file system controls. The following list shows the possible values for this parameter:
/// <param name="deviceType">
/// Defines the type of device for the given IOCTL. This parameter can be no bigger then a WORD value. The values used by Microsoft are in the range
/// 0-32767 and the values 32768-65535 are reserved for use by OEMs and IHVs.
/// </param>
/// <param name="function">
/// Defines an action within the device category. That function codes 0-2047 are reserved for Microsoft, and 2048-4095 are reserved for OEMs and IHVs.
/// The function code can be no larger then 4095.
/// </param>
/// <param name="method">
/// Defines the method codes for how buffers are passed for I/O and file system controls. The following list shows the possible values for this parameter:
/// <list type="bullet">
/// <item><description>METHOD_BUFFERED</description></item>
/// <item><description>METHOD_IN_DIRECT</description></item>
/// <item><description>METHOD_OUT_DIRECT</description></item>
/// <item><description>METHOD_NEITHER</description></item>
/// <item>
/// <description>METHOD_BUFFERED</description>
/// </item>
/// <item>
/// <description>METHOD_IN_DIRECT</description>
/// </item>
/// <item>
/// <description>METHOD_OUT_DIRECT</description>
/// </item>
/// <item>
/// <description>METHOD_NEITHER</description>
/// </item>
/// </list>
/// <para>This field is ignored under Windows CE and you should always use the METHOD_BUFFERED value unless compatibility with the desktop is required using a different Method value.</para></param>
/// <param name="access">Defines the access check value for any access. The following table shows the possible flags for this parameter. The FILE_ACCESS_ANY is generally the correct value.
/// <para>
/// This field is ignored under Windows CE and you should always use the METHOD_BUFFERED value unless compatibility with the desktop is required using a
/// different Method value.
/// </para>
/// </param>
/// <param name="access">
/// Defines the access check value for any access. The following table shows the possible flags for this parameter. The FILE_ACCESS_ANY is generally the
/// correct value.
/// <list type="table">
/// <listheader><term>Flag</term><term>Description</term></listheader>
/// <item><term>FILE_ANY_ACCESS</term><term>Request all access.</term></item>
/// <item><term>FILE_READ_ACCESS</term><term>Request read access. Can be used with FILE_WRITE_ACCESS.</term></item>
/// <item><term>FILE_WRITE_ACCESS</term><term>Request write access. Can be used with FILE_READ_ACCESS.</term></item>
/// </list></param>
/// <listheader>
/// <term>Flag</term>
/// <term>Description</term>
/// </listheader>
/// <item>
/// <term>FILE_ANY_ACCESS</term>
/// <term>Request all access.</term>
/// </item>
/// <item>
/// <term>FILE_READ_ACCESS</term>
/// <term>Request read access. Can be used with FILE_WRITE_ACCESS.</term>
/// </item>
/// <item>
/// <term>FILE_WRITE_ACCESS</term>
/// <term>Request write access. Can be used with FILE_READ_ACCESS.</term>
/// </item>
/// </list>
/// </param>
/// <returns>The resulting I/O control code.</returns>
public static uint CTL_CODE(ushort deviceType, ushort function, byte method, byte access)
{
@ -177,10 +337,21 @@ namespace Vanara.PInvoke
}
/// <summary>This macro is used to create a unique system I/O control code (IOCTL).</summary>
/// <param name="deviceType">Defines the type of device for the given IOCTL. This parameter can be no bigger then a WORD value. The values used by Microsoft are in the range 0-32767 and the values 32768-65535 are reserved for use by OEMs and IHVs.</param>
/// <param name="function">Defines an action within the device category. That function codes 0-2047 are reserved for Microsoft, and 2048-4095 are reserved for OEMs and IHVs. The function code can be no larger then 4095.</param>
/// <param name="method">Defines the method codes for how buffers are passed for I/O and file system controls.
/// <para>This field is ignored under Windows CE and you should always use the METHOD_BUFFERED value unless compatibility with the desktop is required using a different Method value.</para></param>
/// <param name="deviceType">
/// Defines the type of device for the given IOCTL. This parameter can be no bigger then a WORD value. The values used by Microsoft are in the range
/// 0-32767 and the values 32768-65535 are reserved for use by OEMs and IHVs.
/// </param>
/// <param name="function">
/// Defines an action within the device category. That function codes 0-2047 are reserved for Microsoft, and 2048-4095 are reserved for OEMs and IHVs.
/// The function code can be no larger then 4095.
/// </param>
/// <param name="method">
/// Defines the method codes for how buffers are passed for I/O and file system controls.
/// <para>
/// This field is ignored under Windows CE and you should always use the METHOD_BUFFERED value unless compatibility with the desktop is required using a
/// different Method value.
/// </para>
/// </param>
/// <param name="access">Defines the access check value for any access.</param>
/// <returns>The resulting I/O control code.</returns>
public static uint CTL_CODE(DEVICE_TYPE deviceType, ushort function, IOMethod method, IOAccess access) =>
@ -191,17 +362,26 @@ namespace Vanara.PInvoke
/// A handle to the device on which the operation is to be performed. The device is typically a volume, directory, file, or stream. To retrieve a device
/// handle, use the CreateFile function. For more information, see Remarks.
/// </param>
/// <param name="dwIoControlCode">The control code for the operation. This value identifies the specific operation to be performed and the type of device on which to perform it.</param>
/// <param name="lpInBuffer">A pointer to the input buffer that contains the data required to perform the operation. The format of this data depends on the value of the dwIoControlCode parameter.
/// <param name="dwIoControlCode">
/// The control code for the operation. This value identifies the specific operation to be performed and the type of device on which to perform it.
/// </param>
/// <param name="lpInBuffer">
/// A pointer to the input buffer that contains the data required to perform the operation. The format of this data depends on the value of the
/// dwIoControlCode parameter.
/// <para>This parameter can be NULL if dwIoControlCode specifies an operation that does not require input data.</para>
/// </param>
/// <param name="nInBufferSize">The size of the input buffer, in bytes.</param>
/// <param name="lpOutBuffer">A pointer to the output buffer that is to receive the data returned by the operation. The format of this data depends on the value of the dwIoControlCode parameter.
/// <param name="lpOutBuffer">
/// A pointer to the output buffer that is to receive the data returned by the operation. The format of this data depends on the value of the
/// dwIoControlCode parameter.
/// <para>This parameter can be NULL if dwIoControlCode specifies an operation that does not return data.</para>
/// </param>
/// <param name="nOutBufferSize">The size of the output buffer, in bytes.</param>
/// <param name="lpBytesReturned">A pointer to a variable that receives the size of the data stored in the output buffer, in bytes.
/// <para>If the output buffer is too small to receive any data, the call fails, GetLastError returns ERROR_INSUFFICIENT_BUFFER, and lpBytesReturned is zero.</para>
/// <param name="lpBytesReturned">
/// A pointer to a variable that receives the size of the data stored in the output buffer, in bytes.
/// <para>
/// If the output buffer is too small to receive any data, the call fails, GetLastError returns ERROR_INSUFFICIENT_BUFFER, and lpBytesReturned is zero.
/// </para>
/// <para>
/// If the output buffer is too small to hold all of the data but can hold some entries, some drivers will return as much data as fits. In this case, the
/// call fails, GetLastError returns ERROR_MORE_DATA, and lpBytesReturned indicates the amount of data received. Your application should call
@ -361,16 +541,16 @@ namespace Vanara.PInvoke
public static extern unsafe bool DeviceIoControl(SafeFileHandle hDevice, uint dwIoControlCode, byte* lpInBuffer, uint nInBufferSize, byte* lpOutBuffer,
uint nOutBufferSize, out uint lpBytesReturned, NativeOverlapped* lpOverlapped);
/// <summary>
/// Sends a control code directly to a specified device driver, causing the corresponding device to perform the corresponding operation.
/// </summary>
/// <summary>Sends a control code directly to a specified device driver, causing the corresponding device to perform the corresponding operation.</summary>
/// <typeparam name="TIn">The type of the <paramref name="inVal"/>.</typeparam>
/// <typeparam name="TOut">The type of the <paramref name="outVal"/>.</typeparam>
/// <param name="hDev">
/// A handle to the device on which the operation is to be performed. The device is typically a volume, directory, file, or stream. To retrieve a device
/// handle, use the CreateFile function. For more information, see Remarks.
/// </param>
/// <param name="ioControlCode">The control code for the operation. This value identifies the specific operation to be performed and the type of device on which to perform it.</param>
/// <param name="ioControlCode">
/// The control code for the operation. This value identifies the specific operation to be performed and the type of device on which to perform it.
/// </param>
/// <param name="inVal">The data required to perform the operation. The format of this data depends on the value of the dwIoControlCode parameter.</param>
/// <param name="outVal">The data returned by the operation. The format of this data depends on the value of the dwIoControlCode parameter.</param>
/// <returns><c>true</c> if successful.</returns>
@ -385,15 +565,15 @@ namespace Vanara.PInvoke
}
}
/// <summary>
/// Sends a control code directly to a specified device driver, causing the corresponding device to perform the corresponding operation.
/// </summary>
/// <summary>Sends a control code directly to a specified device driver, causing the corresponding device to perform the corresponding operation.</summary>
/// <typeparam name="TOut">The type of the <paramref name="outVal"/>.</typeparam>
/// <param name="hDev">
/// A handle to the device on which the operation is to be performed. The device is typically a volume, directory, file, or stream. To retrieve a device
/// handle, use the CreateFile function. For more information, see Remarks.
/// </param>
/// <param name="ioControlCode">The control code for the operation. This value identifies the specific operation to be performed and the type of device on which to perform it.</param>
/// <param name="ioControlCode">
/// The control code for the operation. This value identifies the specific operation to be performed and the type of device on which to perform it.
/// </param>
/// <param name="outVal">The data returned by the operation. The format of this data depends on the value of the dwIoControlCode parameter.</param>
/// <returns><c>true</c> if successful.</returns>
[PInvokeData("Winbase.h", MSDNShortId = "aa363216")]
@ -407,15 +587,15 @@ namespace Vanara.PInvoke
}
}
/// <summary>
/// Sends a control code directly to a specified device driver, causing the corresponding device to perform the corresponding operation.
/// </summary>
/// <summary>Sends a control code directly to a specified device driver, causing the corresponding device to perform the corresponding operation.</summary>
/// <typeparam name="TIn">The type of the <paramref name="inVal"/>.</typeparam>
/// <param name="hDev">
/// A handle to the device on which the operation is to be performed. The device is typically a volume, directory, file, or stream. To retrieve a device
/// handle, use the CreateFile function. For more information, see Remarks.
/// </param>
/// <param name="ioControlCode">The control code for the operation. This value identifies the specific operation to be performed and the type of device on which to perform it.</param>
/// <param name="ioControlCode">
/// The control code for the operation. This value identifies the specific operation to be performed and the type of device on which to perform it.
/// </param>
/// <param name="inVal">The data required to perform the operation. The format of this data depends on the value of the dwIoControlCode parameter.</param>
/// <returns><c>true</c> if successful.</returns>
[PInvokeData("Winbase.h", MSDNShortId = "aa363216")]
@ -427,9 +607,7 @@ namespace Vanara.PInvoke
}
}
/// <summary>
/// Ends the asynchronous call to <see cref="BeginDeviceIoControl{TIn, TOut}(SafeFileHandle, uint, TIn?, TOut?, AsyncCallback)"/>.
/// </summary>
/// <summary>Ends the asynchronous call to <see cref="BeginDeviceIoControl{TIn, TOut}(SafeFileHandle, uint, TIn?, TOut?, AsyncCallback)"/>.</summary>
/// <typeparam name="TIn">The type of the input value.</typeparam>
/// <typeparam name="TOut">The type of the output value.</typeparam>
/// <param name="asyncResult">The asynchronous result returned from <see cref="BeginDeviceIoControl{TIn, TOut}(SafeFileHandle, uint, TIn?, TOut?, AsyncCallback)"/>.</param>
@ -441,6 +619,197 @@ namespace Vanara.PInvoke
return Unpack<TIn, TOut>(ret as byte[]).Item2;
}
/// <summary>
/// Retrieves the results of an overlapped operation on the specified file, named pipe, or communications device. To specify a timeout interval or wait
/// on an alertable thread, use <c>GetOverlappedResultEx</c>.
/// </summary>
/// <param name="hFile">
/// A handle to the file, named pipe, or communications device. This is the same handle that was specified when the overlapped operation was started by a
/// call to the <c>ReadFile</c>, <c>WriteFile</c>, <c>ConnectNamedPipe</c>, <c>TransactNamedPipe</c>, <c>DeviceIoControl</c>, or <c>WaitCommEvent</c> function.
/// </param>
/// <param name="lpOverlapped">A pointer to an <c>OVERLAPPED</c> structure that was specified when the overlapped operation was started.</param>
/// <param name="lpNumberOfBytesTransferred">
/// A pointer to a variable that receives the number of bytes that were actually transferred by a read or write operation. For a <c>TransactNamedPipe</c>
/// operation, this is the number of bytes that were read from the pipe. For a <c>DeviceIoControl</c> operation, this is the number of bytes of output
/// data returned by the device driver. For a <c>ConnectNamedPipe</c> or <c>WaitCommEvent</c> operation, this value is undefined.
/// </param>
/// <param name="bWait">
/// If this parameter is <c>TRUE</c>, and the <c>Internal</c> member of the lpOverlapped structure is <c>STATUS_PENDING</c>, the function does not return
/// until the operation has been completed. If this parameter is <c>FALSE</c> and the operation is still pending, the function returns <c>FALSE</c> and
/// the <c>GetLastError</c> function returns <c>ERROR_IO_INCOMPLETE</c>.
/// </param>
/// <returns>
/// <para>If the function succeeds, the return value is nonzero.</para>
/// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// BOOL WINAPI GetOverlappedResult( _In_ HANDLE hFile, _In_ LPOVERLAPPED lpOverlapped, _Out_ LPDWORD lpNumberOfBytesTransferred, _In_ BOOL bWait); https://msdn.microsoft.com/en-us/library/windows/desktop/ms683209(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms683209")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern unsafe bool GetOverlappedResult([In] SafeFileHandle hFile, [In] NativeOverlapped* lpOverlapped, out uint lpNumberOfBytesTransferred, [MarshalAs(UnmanagedType.Bool)] bool bWait);
/// <summary>
/// Retrieves the results of an overlapped operation on the specified file, named pipe, or communications device within the specified time-out interval.
/// The calling thread can perform an alertable wait.
/// </summary>
/// <param name="hFile">
/// A handle to the file, named pipe, or communications device. This is the same handle that was specified when the overlapped operation was started by a
/// call to the <c>ReadFile</c>, <c>WriteFile</c>, <c>ConnectNamedPipe</c>, <c>TransactNamedPipe</c>, <c>DeviceIoControl</c>, or <c>WaitCommEvent</c> function.
/// </param>
/// <param name="lpOverlapped">A pointer to an <c>OVERLAPPED</c> structure that was specified when the overlapped operation was started.</param>
/// <param name="lpNumberOfBytesTransferred">
/// A pointer to a variable that receives the number of bytes that were actually transferred by a read or write operation. For a <c>TransactNamedPipe</c>
/// operation, this is the number of bytes that were read from the pipe. For a <c>DeviceIoControl</c> operation, this is the number of bytes of output
/// data returned by the device driver. For a <c>ConnectNamedPipe</c> or <c>WaitCommEvent</c> operation, this value is undefined.
/// </param>
/// <param name="dwMilliseconds">
/// <para>The time-out interval, in milliseconds.</para>
/// <para>
/// If dwMilliseconds is zero and the operation is still in progress, the function returns immediately and the <c>GetLastError</c> function returns <c>ERROR_IO_INCOMPLETE</c>.
/// </para>
/// <para>
/// If dwMilliseconds is nonzero and the operation is still in progress, the function waits until the object is signaled, an I/O completion routine or
/// APC is queued, or the interval elapses before returning. Use <c>GetLastError</c> to get extended error information.
/// </para>
/// <para>If dwMilliseconds is <c>INFINITE</c>, the function returns only when the object is signaled or an I/O completion routine or APC is queued.</para>
/// </param>
/// <param name="bAlertable">
/// <para>
/// If this parameter is <c>TRUE</c> and the calling thread is in the waiting state, the function returns when the system queues an I/O completion
/// routine or APC. The calling thread then runs the routine or function. Otherwise, the function does not return, and the completion routine or APC
/// function is not executed.
/// </para>
/// <para>
/// A completion routine is queued when the <c>ReadFileEx</c> or <c>WriteFileEx</c> function in which it was specified has completed. The function
/// returns and the completion routine is called only if bAlertable is <c>TRUE</c>, and the calling thread is the thread that initiated the read or write
/// operation. An APC is queued when you call <c>QueueUserAPC</c>.
/// </para>
/// </param>
/// <returns>
/// <para>If the function succeeds, the return value is nonzero.</para>
/// <para>
/// If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>. Common error codes include the following:
/// </para>
/// </returns>
// WINBASEAPI BOOL WINAPI GetOverlappedResultEx( _In_ HANDLE hFile, _In_ LPOVERLAPPED lpOverlapped, _Out_ LPDWORD lpNumberOfBytesTransferred, _In_ DWORD
// dwMilliseconds, _In_ BOOL bAlertable); https://msdn.microsoft.com/en-us/library/windows/desktop/hh448542(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("Ioapiset.h", MSDNShortId = "hh448542")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern unsafe bool GetOverlappedResultEx([In] SafeFileHandle hFile, [In] NativeOverlapped* lpOverlapped, out uint lpNumberOfBytesTransferred, uint dwMilliseconds, [MarshalAs(UnmanagedType.Bool)] bool bAlertable);
/// <summary>
/// <para>
/// Attempts to dequeue an I/O completion packet from the specified I/O completion port. If there is no completion packet queued, the function waits for
/// a pending I/O operation associated with the completion port to complete.
/// </para>
/// <para>To dequeue multiple I/O completion packets at once, use the <c>GetQueuedCompletionStatusEx</c> function.</para>
/// </summary>
/// <param name="CompletionPort">A handle to the completion port. To create a completion port, use the <c>CreateIoCompletionPort</c> function.</param>
/// <param name="lpNumberOfBytes">A pointer to a variable that receives the number of bytes transferred during an I/O operation that has completed.</param>
/// <param name="lpCompletionKey">
/// A pointer to a variable that receives the completion key value associated with the file handle whose I/O operation has completed. A completion key is
/// a per-file key that is specified in a call to <c>CreateIoCompletionPort</c>.
/// </param>
/// <param name="lpOverlapped">
/// <para>
/// A pointer to a variable that receives the address of the <c>OVERLAPPED</c> structure that was specified when the completed I/O operation was started.
/// </para>
/// <para>
/// Even if you have passed the function a file handle associated with a completion port and a valid <c>OVERLAPPED</c> structure, an application can
/// prevent completion port notification. This is done by specifying a valid event handle for the <c>hEvent</c> member of the <c>OVERLAPPED</c>
/// structure, and setting its low-order bit. A valid event handle whose low-order bit is set keeps I/O completion from being queued to the completion port.
/// </para>
/// </param>
/// <param name="dwMilliseconds">
/// <para>
/// The number of milliseconds that the caller is willing to wait for a completion packet to appear at the completion port. If a completion packet does
/// not appear within the specified time, the function times out, returns <c>FALSE</c>, and sets *lpOverlapped to <c>NULL</c>.
/// </para>
/// <para>
/// If dwMilliseconds is <c>INFINITE</c>, the function will never time out. If dwMilliseconds is zero and there is no I/O operation to dequeue, the
/// function will time out immediately.
/// </para>
/// </param>
/// <returns>
/// <para>Returns nonzero ( <c>TRUE</c>) if successful or zero ( <c>FALSE</c>) otherwise.</para>
/// <para>To get extended error information, call <c>GetLastError</c>.</para>
/// <para>For more information, see the Remarks section.</para>
/// </returns>
// BOOL WINAPI GetQueuedCompletionStatus( _In_ HANDLE CompletionPort, _Out_ LPDWORD lpNumberOfBytes, _Out_ PULONG_PTR lpCompletionKey, _Out_ LPOVERLAPPED
// *lpOverlapped, _In_ DWORD dwMilliseconds); https://msdn.microsoft.com/en-us/library/windows/desktop/aa364986(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "aa364986")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern unsafe bool GetQueuedCompletionStatus([In] IntPtr CompletionPort, out uint lpNumberOfBytesTransferred, out uint lpCompletionKey, NativeOverlapped** lpOverlapped, uint dwMilliseconds);
/// <summary>
/// <para>
/// Retrieves multiple completion port entries simultaneously. It waits for pending I/O operations that are associated with the specified completion port
/// to complete.
/// </para>
/// <para>To dequeue I/O completion packets one at a time, use the <c>GetQueuedCompletionStatus</c> function.</para>
/// </summary>
/// <param name="CompletionPort">A handle to the completion port. To create a completion port, use the <c>CreateIoCompletionPort</c> function.</param>
/// <param name="lpCompletionPortEntries">
/// <para>On input, points to a pre-allocated array of <c>OVERLAPPED_ENTRY</c> structures.</para>
/// <para>On output, receives an array of <c>OVERLAPPED_ENTRY</c> structures that hold the entries. The number of array elements is provided by ulNumEntriesRemoved.</para>
/// <para>
/// The number of bytes transferred during each I/O, the completion key that indicates on which file each I/O occurred, and the overlapped structure
/// address used in each original I/O are all returned in the lpCompletionPortEntries array.
/// </para>
/// </param>
/// <param name="ulCount">The maximum number of entries to remove.</param>
/// <param name="ulNumEntriesRemoved">A pointer to a variable that receives the number of entries actually removed.</param>
/// <param name="dwMilliseconds">
/// <para>
/// The number of milliseconds that the caller is willing to wait for a completion packet to appear at the completion port. If a completion packet does
/// not appear within the specified time, the function times out and returns <c>FALSE</c>.
/// </para>
/// <para>
/// If dwMilliseconds is <c>INFINITE</c> (0xFFFFFFFF), the function will never time out. If dwMilliseconds is zero and there is no I/O operation to
/// dequeue, the function will time out immediately.
/// </para>
/// </param>
/// <param name="fAlertable">
/// <para>If this parameter is <c>FALSE</c>, the function does not return until the time-out period has elapsed or an entry is retrieved.</para>
/// <para>
/// If the parameter is <c>TRUE</c> and there are no available entries, the function performs an alertable wait. The thread returns when the system
/// queues an I/O completion routine or APC to the thread and the thread executes the function.
/// </para>
/// <para>
/// A completion routine is queued when the <c>ReadFileEx</c> or <c>WriteFileEx</c> function in which it was specified has completed, and the calling
/// thread is the thread that initiated the operation. An APC is queued when you call <c>QueueUserAPC</c>.
/// </para>
/// </param>
/// <returns>
/// <para>Returns nonzero ( <c>TRUE</c>) if successful or zero ( <c>FALSE</c>) otherwise.</para>
/// <para>To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// BOOL WINAPI GetQueuedCompletionStatusEx( _In_ HANDLE CompletionPort, _Out_ LPOVERLAPPED_ENTRY lpCompletionPortEntries, _In_ ULONG ulCount, _Out_
// PULONG ulNumEntriesRemoved, _In_ DWORD dwMilliseconds, _In_ BOOL fAlertable); https://msdn.microsoft.com/en-us/library/windows/desktop/aa364988(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("IoAPI.h", MSDNShortId = "aa364988")]
public static extern void GetQueuedCompletionStatusEx(IntPtr CompletionPort, IntPtr lpCompletionPortEntries, uint ulCount, out uint ulNumEntriesRemoved, uint dwMilliseconds, [MarshalAs(UnmanagedType.Bool)] bool fAlertable);
/// <summary>Posts an I/O completion packet to an I/O completion port.</summary>
/// <param name="CompletionPort">A handle to an I/O completion port to which the I/O completion packet is to be posted.</param>
/// <param name="dwNumberOfBytesTransferred">
/// The value to be returned through the lpNumberOfBytesTransferred parameter of the <c>GetQueuedCompletionStatus</c> function.
/// </param>
/// <param name="dwCompletionKey">The value to be returned through the lpCompletionKey parameter of the <c>GetQueuedCompletionStatus</c> function.</param>
/// <param name="lpOverlapped">The value to be returned through the lpOverlapped parameter of the <c>GetQueuedCompletionStatus</c> function.</param>
/// <returns>
/// <para>If the function succeeds, the return value is nonzero.</para>
/// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c> .</para>
/// </returns>
// BOOL WINAPI PostQueuedCompletionStatus( _In_ HANDLE CompletionPort, _In_ DWORD dwNumberOfBytesTransferred, _In_ ULONG_PTR dwCompletionKey, _In_opt_
// LPOVERLAPPED lpOverlapped); https://msdn.microsoft.com/en-us/library/windows/desktop/aa365458(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("IoAPI.h", MSDNShortId = "aa365458")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern unsafe bool PostQueuedCompletionStatus([In] IntPtr CompletionPort, uint dwNumberOfBytesTransferred, UIntPtr dwCompletionKey, NativeOverlapped* lpOverlapped);
private static unsafe IAsyncResult BeginDeviceIoControl<TIn, TOut>(SafeFileHandle hDevice, uint dwIoControlCode, byte[] buffer, AsyncCallback userCallback, object userState) where TIn : struct where TOut : struct
{
var ar = OverlappedAsync.SetupOverlappedFunction(hDevice, userCallback, buffer);
@ -639,6 +1008,7 @@ namespace Vanara.PInvoke
public static uint IOCTL_STORAGE_RESERVE
=> CTL_CODE(DEVICE_TYPE.IOCTL_STORAGE_BASE, 0x0204, IOMethod.METHOD_BUFFERED, IOAccess.FILE_READ_ACCESS);
public static uint IOCTL_STORAGE_RESET_BUS
=> CTL_CODE(DEVICE_TYPE.IOCTL_STORAGE_BASE, 0x0400, IOMethod.METHOD_BUFFERED, IOAccess.FILE_READ_ACCESS);
@ -650,8 +1020,10 @@ namespace Vanara.PInvoke
public static uint IOCTL_STORAGE_SET_HOTPLUG_INFO
=> CTL_CODE(DEVICE_TYPE.IOCTL_STORAGE_BASE, 0x0306, IOMethod.METHOD_BUFFERED, IOAccess.FILE_READ_WRITE_ACCESS);
public static uint IOCTL_STORAGE_SET_TEMPERATURE_THRESHOLD
=> CTL_CODE(DEVICE_TYPE.IOCTL_STORAGE_BASE, 0x0480, IOMethod.METHOD_BUFFERED, IOAccess.FILE_READ_WRITE_ACCESS);
public static uint IOCTL_STORAGE_START_DATA_INTEGRITY_CHECK
=> CTL_CODE(DEVICE_TYPE.IOCTL_STORAGE_BASE, 0x0621, IOMethod.METHOD_BUFFERED, IOAccess.FILE_READ_WRITE_ACCESS);

View File

@ -0,0 +1,34 @@
using System;
using System.Runtime.InteropServices;
namespace Vanara.PInvoke
{
public static partial class Kernel32
{
/// <summary>Determines whether the process is running in the specified job.</summary>
/// <param name="ProcessHandle">
/// <para>
/// A handle to the process to be tested. The handle must have the PROCESS_QUERY_INFORMATION or PROCESS_QUERY_LIMITED_INFORMATION access right. For more
/// information, see Process Security and Access Rights.
/// </para>
/// <para><c>Windows Server 2003 and Windows XP:</c> The handle must have the PROCESS_QUERY_INFORMATION access right.</para>
/// </param>
/// <param name="JobHandle">
/// <para>A handle to the job. If this parameter is NULL, the function tests if the process is running under any job.</para>
/// <para>
/// If this parameter is not NULL, the handle must have the JOB_OBJECT_QUERY access right. For more information, see Job Object Security and Access Rights.
/// </para>
/// </param>
/// <param name="Result">A pointer to a value that receives TRUE if the process is running in the job, and FALSE otherwise.</param>
/// <returns>
/// <para>If the function succeeds, the return value is nonzero.</para>
/// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// BOOL WINAPI IsProcessInJob( _In_ HANDLE ProcessHandle, _In_opt_ HANDLE JobHandle, _Out_ PBOOL Result);
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms684127(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms684127")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool IsProcessInJob([In] IntPtr ProcessHandle, [In] IntPtr JobHandle, [MarshalAs(UnmanagedType.Bool)] out bool Result);
}
}

1615
PInvoke/Kernel32/JobApi2.cs Normal file

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,353 @@
using System.Runtime.InteropServices;
using System.Text;
namespace Vanara.PInvoke
{
public static partial class Lz32
{
/// <summary>Retrieves the original name of a compressed file, if the file was compressed by the Lempel-Ziv algorithm.</summary>
/// <param name="lpszSource">The name of the compressed file.</param>
/// <param name="lpszBuffer">A pointer to a buffer that receives the original name of the compressed file.</param>
/// <returns>
/// <para>If the function succeeds, the return value is 1.</para>
/// <para>If the function fails, the return value is LZERROR_BADVALUE. There is no extended error information for this function; do not call <c>GetLastError</c>.</para>
/// </returns>
// INT WINAPI GetExpandedName( _In_ LPTSTR lpszSource, _Out_ LPTSTR lpszBuffer); https://msdn.microsoft.com/en-us/library/windows/desktop/aa364941(v=vs.85).aspx
[DllImport(Lib.Lz32, SetLastError = true, CharSet = CharSet.Auto)]
[PInvokeData("LzExpand.h", MSDNShortId = "aa364941")]
public static extern int GetExpandedName(string lpszSource, [Out] StringBuilder lpszBuffer);
/// <summary>Closes a file that was opened by using the <c>LZOpenFile</c> function.</summary>
/// <param name="hFile">A handle to the file to be closed.</param>
/// <returns>This function does not return a value.</returns>
// void APIENTRY LZClose( _In_ INT hFile); https://msdn.microsoft.com/en-us/library/windows/desktop/aa365221(v=vs.85).aspx
[DllImport(Lib.Lz32, SetLastError = false, ExactSpelling = true)]
[PInvokeData("LzExpand.h", MSDNShortId = "aa365221")]
public static extern void LZClose(int hFile);
/// <summary>
/// Copies a source file to a destination file. If the source file has been compressed by the Lempel-Ziv algorithm, this function creates a decompressed
/// destination file. If the source file is not compressed, this function duplicates the original file.
/// </summary>
/// <param name="hfSource">A handle to the source file.</param>
/// <param name="hfDest">A handle to the destination file.</param>
/// <returns>
/// <para>If the function succeeds, the return value specifies the size, in bytes, of the destination file.</para>
/// <para>
/// If the function fails, the return value is an LZERROR_* code. These codes have values less than zero. Note that <c>LZCopy</c> calls neither
/// <c>SetLastError</c> nor <c>SetLastErrorEx</c>; thus, its failure does not affect a thread's last-error code.
/// </para>
/// <para>The following is a list of error codes that <c>LZCopy</c> can return upon failure.</para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Return code</term>
/// <term>Description</term>
/// </listheader>
/// <item>
/// <term>LZERROR_BADINHANDLE</term>
/// <term>The handle identifying the source file is not valid. The file cannot be read.</term>
/// </item>
/// <item>
/// <term>LZERROR_BADOUTHANDLE</term>
/// <term>The handle identifying the destination file is not valid. The file cannot be written.</term>
/// </item>
/// <item>
/// <term>LZERROR_GLOBALLOC</term>
/// <term>The maximum number of open compressed files has been exceeded or local memory cannot be allocated.</term>
/// </item>
/// <item>
/// <term>LZERROR_GLOBLOCK</term>
/// <term>The LZ file handle cannot be locked down.</term>
/// </item>
/// <item>
/// <term>LZERROR_READ</term>
/// <term>The source file format is not valid.</term>
/// </item>
/// </list>
/// </para>
/// <para>There is no extended error information for this function; do not call <c>GetLastError</c>.</para>
/// </returns>
// LONG WINAPI LZCopy( _In_ INT hfSource, _In_ INT hfDest); https://msdn.microsoft.com/en-us/library/windows/desktop/aa365223(v=vs.85).aspx
[DllImport(Lib.Lz32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("LzExpand.h", MSDNShortId = "aa365223")]
public static extern int LZCopy(int hfSource, int hfDest);
/// <summary>Allocates memory for the internal data structures required to decompress files, and then creates and initializes them.</summary>
/// <param name="hfSource">A handle to the file.</param>
/// <returns>
/// <para>If the function succeeds, the return value is a new LZ file handle.</para>
/// <para>
/// If the function fails, the return value is an LZERROR_* code. These codes have values less than zero. Note that <c>LZInit</c> calls neither
/// <c>SetLastError</c> nor <c>SetLastErrorEx</c>; thus, its failure does not affect a thread's last-error code.
/// </para>
/// <para>The following is the list of the error codes that <c>LZInit</c> can return upon failure.</para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Return code</term>
/// <term>Description</term>
/// </listheader>
/// <item>
/// <term>LZERROR_BADINHANDLE</term>
/// <term>The handle identifying the source file is not valid. The file cannot be read.</term>
/// </item>
/// <item>
/// <term>LZERROR_GLOBALLOC</term>
/// <term>The maximum number of open compressed files has been exceeded or local memory cannot be allocated.</term>
/// </item>
/// <item>
/// <term>LZERROR_GLOBLOCK</term>
/// <term>The LZ file handle cannot be locked down.</term>
/// </item>
/// <item>
/// <term>LZERROR_UNKNOWNALG</term>
/// <term>The file is compressed with an unrecognized compression algorithm.</term>
/// </item>
/// </list>
/// </para>
/// <para>There is no extended error information for this function; do not call <c>GetLastError</c>.</para>
/// </returns>
// INT WINAPI LZInit( _In_ INT hfSource); https://msdn.microsoft.com/en-us/library/windows/desktop/aa365224(v=vs.85).aspx
[DllImport(Lib.Lz32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("LzExpand.h", MSDNShortId = "aa365224")]
public static extern int LZInit(int hfSource);
/// <summary>Creates, opens, reopens, or deletes the specified file.</summary>
/// <param name="lpFileName">The name of the file.</param>
/// <param name="lpReOpenBuf">
/// <para>
/// A pointer to the <c>OFSTRUCT</c> structure that is to receive information about the file when the file is first opened. The structure can be used in
/// subsequent calls to the <c>LZOpenFile</c> function to see the open file.
/// </para>
/// <para>The <c>szPathName</c> member of this structure contains characters from the original equipment manufacturer (OEM) character set.</para>
/// </param>
/// <param name="wStyle">
/// <para>The action to be taken. This parameter can be one or more of the following values.</para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Value</term>
/// <term>Meaning</term>
/// </listheader>
/// <item>
/// <term>OF_CANCEL0x0800</term>
/// <term>Ignored. Provided only for compatibility with 16-bit Windows. Use the OF_PROMPT style to display a dialog box containing a Cancel button.</term>
/// </item>
/// <item>
/// <term>OF_CREATE0x1000</term>
/// <term>Directs LZOpenFile to create a new file. If the file already exists, it is truncated to zero length.</term>
/// </item>
/// <item>
/// <term>OF_DELETE0x0200</term>
/// <term>Deletes the file.</term>
/// </item>
/// <item>
/// <term>OF_EXIST0x4000</term>
/// <term>Opens the file and then closes it to test for a file&amp;#39;s existence.</term>
/// </item>
/// <item>
/// <term>OF_PARSE0x0100</term>
/// <term>Fills the OFSTRUCT structure but carries out no other action.</term>
/// </item>
/// <item>
/// <term>OF_PROMPT0x2000</term>
/// <term>
/// Displays a dialog box if the requested file does not exist. The dialog box informs the user that the system cannot find the file, and it contains
/// Retry and Cancel buttons. Clicking the Cancel button directs LZOpenFile to return a file not found error message.
/// </term>
/// </item>
/// <item>
/// <term>OF_READ0x0000</term>
/// <term>Opens the file for reading only.</term>
/// </item>
/// <item>
/// <term>OF_READWRITE0x0002</term>
/// <term>Opens the file for reading and writing.</term>
/// </item>
/// <item>
/// <term>OF_REOPEN0x8000</term>
/// <term>Opens the file using information in the reopen buffer.</term>
/// </item>
/// <item>
/// <term>OF_SHARE_DENY_NONE0x0040</term>
/// <term>
/// Opens the file without denying other processes read or write access to the file. LZOpenFile fails if the file has been opened in compatibility mode
/// by any other process.
/// </term>
/// </item>
/// <item>
/// <term>OF_SHARE_DENY_READ0x0030</term>
/// <term>
/// Opens the file and denies other processes read access to the file. LZOpenFile fails if the file has been opened in compatibility mode or has been
/// opened for read access by any other process.
/// </term>
/// </item>
/// <item>
/// <term>OF_SHARE_DENY_WRITE0x0020</term>
/// <term>
/// Opens the file and denies other processes write access to the file. LZOpenFile fails if the file has been opened in compatibility mode or has been
/// opened for write access by any other process.
/// </term>
/// </item>
/// <item>
/// <term>OF_SHARE_EXCLUSIVE0x0010</term>
/// <term>
/// Opens the file in exclusive mode, denying other processes both read and write access to the file. LZOpenFile fails if the file has been opened in any
/// other mode for read or write access, even by the current process.
/// </term>
/// </item>
/// <item>
/// <term>OF_WRITE0x0001</term>
/// <term>Opens the file for writing only.</term>
/// </item>
/// </list>
/// </para>
/// </param>
/// <returns>
/// <para>
/// If the function succeeds and the value specified by the wStyle parameter is not <c>OF_READ</c>, the return value is a handle identifying the file. If
/// the file is compressed and opened with wStyle set to <c>OF_READ</c>, the return value is a special file handle.
/// </para>
/// <para>
/// If the function fails, the return value is an <c>LZERROR_*</c> code. These codes have values less than zero. There is no extended error information
/// for this function; do not call <c>GetLastError</c>.
/// </para>
/// <para>The following is the list of the error codes that <c>LZOpenFile</c> can return upon failure.</para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Return code/value</term>
/// <term>Description</term>
/// </listheader>
/// <item>
/// <term>LZERROR_BADINHANDLE-1</term>
/// <term>The handle identifying the source file is not valid. The file cannot be read.</term>
/// </item>
/// <item>
/// <term>LZERROR_GLOBALLOC-5</term>
/// <term>The maximum number of open compressed files has been exceeded or local memory cannot be allocated.</term>
/// </item>
/// </list>
/// </para>
/// </returns>
// INT WINAPI LZOpenFile( _In_ LPTSTR lpFileName, _Out_ LPOFSTRUCT lpReOpenBuf, _In_ WORD wStyle); https://msdn.microsoft.com/en-us/library/windows/desktop/aa365225(v=vs.85).aspx
[DllImport(Lib.Lz32, SetLastError = true, CharSet = CharSet.Auto)]
[PInvokeData("LzExpand.h", MSDNShortId = "aa365225")]
public static extern int LZOpenFile(string lpFileName, out OFSTRUCT lpReOpenBuf, ushort wStyle);
/// <summary>Reads (at most) the specified number of bytes from a file and copies them into a buffer.</summary>
/// <param name="hFile">A handle to the file.</param>
/// <param name="lpBuffer">A pointer to a buffer that receives the bytes read from the file. Ensure that this buffer is larger than cbRead.</param>
/// <param name="cbRead">The count of bytes to be read.</param>
/// <returns>
/// <para>If the function succeeds, the return value specifies the number of bytes read.</para>
/// <para>
/// If the function fails, the return value is an LZERROR_* code. These codes have values less than zero. Note that <c>LZRead</c> calls neither
/// <c>SetLastError</c> nor <c>SetLastErrorEx</c>; thus, its failure does not affect a thread's last-error code.
/// </para>
/// <para>The following is the list of error codes that <c>LZRead</c> can return upon failure.</para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Return code</term>
/// <term>Description</term>
/// </listheader>
/// <item>
/// <term>LZERROR_BADINHANDLE</term>
/// <term>The handle identifying the source file is not valid. The file cannot be read.</term>
/// </item>
/// <item>
/// <term>LZERROR_BADOUTHANDLE</term>
/// <term>The handle identifying the destination file is not valid. The file cannot be written.</term>
/// </item>
/// <item>
/// <term>LZERROR_BADVALUE</term>
/// <term>One of the input parameters is not valid.</term>
/// </item>
/// <item>
/// <term>LZERROR_GLOBALLOC</term>
/// <term>The maximum number of open compressed files has been exceeded or local memory cannot be allocated.</term>
/// </item>
/// <item>
/// <term>LZERROR_GLOBLOCK</term>
/// <term>The LZ file handle cannot be locked down.</term>
/// </item>
/// <item>
/// <term>LZERROR_READ</term>
/// <term>The source file format is not valid.</term>
/// </item>
/// <item>
/// <term>LZERROR_WRITE</term>
/// <term>There is insufficient space for the output file.</term>
/// </item>
/// </list>
/// </para>
/// <para>There is no extended error information for this function; do not call <c>GetLastError</c>.</para>
/// </returns>
// INT WINAPI LZRead( _In_ INT hFile, _Out_ LPSTR lpBuffer, _In_ INT cbRead); https://msdn.microsoft.com/en-us/library/windows/desktop/aa365226(v=vs.85).aspx
[DllImport(Lib.Lz32, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Ansi)]
[PInvokeData("LzExpand.h", MSDNShortId = "aa365226")]
public static extern int LZRead(int hFile, [Out] StringBuilder lpBuffer, int cbRead);
/// <summary>Moves a file pointer the specified number of bytes from a starting position.</summary>
/// <param name="hFile">A handle to the file.</param>
/// <param name="lOffset">The number of bytes by which to move the file pointer.</param>
/// <param name="iOrigin">
/// <para>The starting position of the pointer. This parameter must be one of the following values.</para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Value</term>
/// <term>Meaning</term>
/// </listheader>
/// <item>
/// <term>0</term>
/// <term>Moves the file pointer lOffset bytes from the beginning of the file.</term>
/// </item>
/// <item>
/// <term>1</term>
/// <term>Moves the file pointer lOffset bytes from the current position.</term>
/// </item>
/// <item>
/// <term>2</term>
/// <term>Moves the file pointer lOffset bytes from the end of the file.</term>
/// </item>
/// </list>
/// </para>
/// </param>
/// <returns>
/// <para>If the function succeeds, the return value specifies the offset from the beginning of the file to the new pointer position.</para>
/// <para>
/// If the function fails, the return value is an LZERROR_* code. These codes have values less than zero. Note that <c>LZSeek</c> calls neither
/// <c>SetLastError</c> nor <c>SetLastErrorEx</c>; thus, its failure does not affect a thread's last-error code.
/// </para>
/// <para>The following is the list of error codes that <c>LZSeek</c> can return upon failure.</para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Return code</term>
/// <term>Description</term>
/// </listheader>
/// <item>
/// <term>LZERROR_BADINHANDLE</term>
/// <term>The handle identifying the source file is not valid. The file cannot be read.</term>
/// </item>
/// <item>
/// <term>LZERROR_BADVALUE</term>
/// <term>One of the parameters is outside the range of acceptable values.</term>
/// </item>
/// <item>
/// <term>LZERROR_GLOBLOCK</term>
/// <term>The LZ file handle cannot be locked down.</term>
/// </item>
/// </list>
/// </para>
/// <para>There is no extended error information for this function; do not call <c>GetLastError</c>.</para>
/// </returns>
// LONG WINAPI LZSeek( _In_ INT hFile, _In_ LONG lOffset, _In_ INT iOrigin); https://msdn.microsoft.com/en-us/library/windows/desktop/aa365227(v=vs.85).aspx
[DllImport(Lib.Lz32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("LzExpand.h", MSDNShortId = "aa365227")]
public static extern int LZSeek(int hFile, int lOffset, int iOrigin);
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,90 @@
using System;
using System.Runtime.InteropServices;
namespace Vanara.PInvoke
{
public static partial class Kernel32
{
/// <summary>Indicates that the namespace is destroyed on closing.</summary>
public const uint PRIVATE_NAMESPACE_FLAG_DESTROY = 0x00000001;
/// <summary>Adds a security identifier (SID) to the specified boundary descriptor.</summary>
/// <param name="BoundaryDescriptor">A handle to the boundary descriptor. The <c>CreateBoundaryDescriptor</c> function returns this handle.</param>
/// <param name="RequiredSid">A pointer to a <c>SID</c> structure.</param>
/// <returns>
/// <para>If the function succeeds, the return value is nonzero.</para>
/// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// BOOL WINAPI AddSIDToBoundaryDescriptor( _Inout_ HANDLE *BoundaryDescriptor, _In_ PSID RequiredSid); https://msdn.microsoft.com/en-us/library/windows/desktop/ms681937(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms681937")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool AddSIDToBoundaryDescriptor(ref IntPtr BoundaryDescriptor, IntPtr RequiredSid);
/// <summary>Closes an open namespace handle.</summary>
/// <param name="Handle">The namespace handle. This handle is created by <c>CreatePrivateNamespace</c> or <c>OpenPrivateNamespace</c>.</param>
/// <param name="Flags">If this parameter is <c>PRIVATE_NAMESPACE_FLAG_DESTROY</c> (0x00000001), the namespace is destroyed.</param>
/// <returns>
/// <para>If the function succeeds, the return value is nonzero.</para>
/// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// BOOLEAN WINAPI ClosePrivateNamespace( _In_ HANDLE Handle, _In_ ULONG Flags); https://msdn.microsoft.com/en-us/library/windows/desktop/ms682026(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms682026")]
[return: MarshalAs(UnmanagedType.U1)]
public static extern bool ClosePrivateNamespace(IntPtr Handle, uint Flags);
/// <summary>Creates a boundary descriptor.</summary>
/// <param name="Name">The name of the boundary descriptor.</param>
/// <param name="Flags">This parameter is reserved for future use.</param>
/// <returns>
/// <para>If the function succeeds, the return value is a handle to the boundary descriptor.</para>
/// <para>If the function fails, the return value is <c>NULL</c>. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// HANDLE WINAPI CreateBoundaryDescriptor( _In_ LPCTSTR Name, _In_ ULONG Flags); https://msdn.microsoft.com/en-us/library/windows/desktop/ms682121(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)]
[PInvokeData("WinBase.h", MSDNShortId = "ms682121")]
public static extern IntPtr CreateBoundaryDescriptor(string Name, [Optional] uint Flags);
/// <summary>Creates a private namespace.</summary>
/// <param name="lpPrivateNamespaceAttributes">
/// A pointer to a <c>SECURITY_ATTRIBUTES</c> structure that specifies the security attributes of the namespace object.
/// </param>
/// <param name="lpBoundaryDescriptor">
/// A descriptor that defines how the namespace is to be isolated. The caller must be within this boundary. The <c>CreateBoundaryDescriptor</c> function
/// creates a boundary descriptor.
/// </param>
/// <param name="lpAliasPrefix">
/// <para>The prefix for the namespace. To create an object in this namespace, specify the object name as prefix\objectname.</para>
/// <para>The system supports multiple private namespaces with the same name, as long as they define different boundaries.</para>
/// </param>
/// <returns>
/// <para>If the function succeeds, it returns a handle to the new namespace.</para>
/// <para>If the function fails, the return value is <c>NULL</c>. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// HANDLE WINAPI CreatePrivateNamespace( _In_opt_ LPSECURITY_ATTRIBUTES lpPrivateNamespaceAttributes, _In_ LPVOID lpBoundaryDescriptor, _In_ LPCTSTR
// lpAliasPrefix); https://msdn.microsoft.com/en-us/library/windows/desktop/ms682419(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)]
[PInvokeData("WinBase.h", MSDNShortId = "ms682419")]
public static extern IntPtr CreatePrivateNamespace(ref SECURITY_ATTRIBUTES lpPrivateNamespaceAttributes, IntPtr lpBoundaryDescriptor, string lpAliasPrefix);
/// <summary>Deletes the specified boundary descriptor.</summary>
/// <param name="BoundaryDescriptor">A handle to the boundary descriptor. The <c>CreateBoundaryDescriptor</c> function returns this handle.</param>
/// <returns>This function does not return a value.</returns>
// VOID WINAPI DeleteBoundaryDescriptor( _In_ HANDLE BoundaryDescriptor); https://msdn.microsoft.com/en-us/library/windows/desktop/ms682549(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms682549")]
public static extern void DeleteBoundaryDescriptor(IntPtr BoundaryDescriptor);
/// <summary>Opens a private namespace.</summary>
/// <param name="lpBoundaryDescriptor">
/// A descriptor that defines how the namespace is to be isolated. The <c>CreateBoundaryDescriptor</c> function creates a boundary descriptor.
/// </param>
/// <param name="lpAliasPrefix">The prefix for the namespace. To create an object in this namespace, specify the object name as prefix\objectname.</param>
/// <returns>The function returns the handle to the existing namespace.</returns>
// HANDLE WINAPI OpenPrivateNamespace( _In_ LPVOID lpBoundaryDescriptor, _In_ LPCTSTR lpAliasPrefix); https://msdn.microsoft.com/en-us/library/windows/desktop/ms684318(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, CharSet = CharSet.Auto)]
[PInvokeData("WinBase.h", MSDNShortId = "ms684318")]
public static extern IntPtr OpenPrivateNamespace(IntPtr lpBoundaryDescriptor, string lpAliasPrefix);
}
}

View File

@ -0,0 +1,816 @@
using System;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
namespace Vanara.PInvoke
{
public static partial class Kernel32
{
/// <summary>Does not wait for the named pipe. If the named pipe is not available, the function returns an error.</summary>
public const uint NMPWAIT_NOWAIT = 0x00000001;
/// <summary>The time-out interval is the default value specified by the server process in the CreateNamedPipe function.</summary>
public const uint NMPWAIT_USE_DEFAULT_WAIT = 0x00000000;
/// <summary>The function does not return until an instance of the named pipe is available.</summary>
public const uint NMPWAIT_WAIT_FOREVER = 0xffffffff;
/// <summary>Values that can be used in the dwOpenMode parameter of <see cref="CreateNamedPipe"/>.</summary>
[Flags]
public enum PIPE_ACCESS : uint
{
/// <summary>
/// The flow of data in the pipe goes from client to server only. This mode gives the server the equivalent of GENERIC_READ access to the pipe. The
/// client must specify GENERIC_WRITE access when connecting to the pipe. If the client must read pipe settings by calling the GetNamedPipeInfo or
/// GetNamedPipeHandleState functions, the client must specify GENERIC_WRITE and FILE_READ_ATTRIBUTES access when connecting to the pipe.
/// </summary>
PIPE_ACCESS_INBOUND = 0x00000001,
/// <summary>
/// The flow of data in the pipe goes from server to client only. This mode gives the server the equivalent of GENERIC_WRITE access to the pipe. The
/// client must specify GENERIC_READ access when connecting to the pipe. If the client must change pipe settings by calling the
/// SetNamedPipeHandleState function, the client must specify GENERIC_READ and FILE_WRITE_ATTRIBUTES access when connecting to the pipe.
/// </summary>
PIPE_ACCESS_OUTBOUND = 0x00000002,
/// <summary>
/// The pipe is bi-directional; both server and client processes can read from and write to the pipe. This mode gives the server the equivalent of
/// GENERIC_READ and GENERIC_WRITE access to the pipe. The client can specify GENERIC_READ or GENERIC_WRITE, or both, when it connects to the pipe
/// using the CreateFile function.
/// </summary>
PIPE_ACCESS_DUPLEX = 0x00000003,
}
/// <summary>The pipe mode.</summary>
[Flags]
public enum PIPE_TYPE : uint
{
/// <summary>
/// Blocking mode is enabled. When the pipe handle is specified in the ReadFile, WriteFile, or ConnectNamedPipe function, the operations are not
/// completed until there is data to read, all data is written, or a client is connected. Use of this mode can mean waiting indefinitely in some
/// situations for a client process to perform an action.
/// </summary>
PIPE_WAIT = 0x00000000,
/// <summary>
/// Nonblocking mode is enabled. In this mode, ReadFile, WriteFile, and ConnectNamedPipe always return immediately. Note that nonblocking mode is
/// supported for compatibility with Microsoft LAN Manager version 2.0 and should not be used to achieve asynchronous I/O with named pipes. For more
/// information on asynchronous pipe I/O, see Synchronous and Overlapped Input and Output.
/// </summary>
PIPE_NOWAIT = 0x00000001,
/// <summary>Data is read from the pipe as a stream of bytes. This mode can be used with either PIPE_TYPE_MESSAGE or PIPE_TYPE_BYTE.</summary>
PIPE_READMODE_BYTE = 0x00000000,
/// <summary>Data is read from the pipe as a stream of messages. This mode can be only used if PIPE_TYPE_MESSAGE is also specified./summary>
PIPE_READMODE_MESSAGE = 0x00000002,
/// <summary>
/// Data is written to the pipe as a stream of bytes. This mode cannot be used with PIPE_READMODE_MESSAGE. The pipe does not distinguish bytes
/// written during different write operations.
/// </summary>
PIPE_TYPE_BYTE = 0x00000000,
/// <summary>
/// Data is written to the pipe as a stream of messages. The pipe treats the bytes written during each write operation as a message unit. The
/// GetLastError function returns ERROR_MORE_DATA when a message is not read completely. This mode can be used with either PIPE_READMODE_MESSAGE or PIPE_READMODE_BYTE.
/// </summary>
PIPE_TYPE_MESSAGE = 0x00000004,
/// <summary>Connections from remote clients can be accepted and checked against the security descriptor for the pipe.</summary>
PIPE_ACCEPT_REMOTE_CLIENTS = 0x00000000,
/// <summary>Connections from remote clients are automatically rejected.</summary>
PIPE_REJECT_REMOTE_CLIENTS = 0x00000008,
/// <summary>The handle refers to the client end of a named pipe instance. This is the default.</summary>
PIPE_CLIENT_END = 0x00000000,
/// <summary>
/// The handle refers to the server end of a named pipe instance. If this value is not specified, the handle refers to the client end of a named pipe instance.
/// </summary>
PIPE_SERVER_END = 0x00000001,
}
/// <summary>
/// Connects to a message-type pipe (and waits if an instance of the pipe is not available), writes to and reads from the pipe, and then closes the pipe.
/// </summary>
/// <param name="lpNamedPipeName">The pipe name.</param>
/// <param name="lpInBuffer">The data to be written to the pipe.</param>
/// <param name="nInBufferSize">The size of the write buffer, in bytes.</param>
/// <param name="lpOutBuffer">A pointer to the buffer that receives the data read from the pipe.</param>
/// <param name="nOutBufferSize">The size of the read buffer, in bytes.</param>
/// <param name="lpBytesRead">A pointer to a variable that receives the number of bytes read from the pipe.</param>
/// <param name="nTimeOut">
/// <para>
/// The number of milliseconds to wait for the named pipe to be available. In addition to numeric values, the following special values can be specified.
/// </para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Value</term>
/// <term>Meaning</term>
/// </listheader>
/// <item>
/// <term>NMPWAIT_NOWAIT0x00000001</term>
/// <term>Does not wait for the named pipe. If the named pipe is not available, the function returns an error.</term>
/// </item>
/// <item>
/// <term>NMPWAIT_WAIT_FOREVER0xffffffff</term>
/// <term>Waits indefinitely.</term>
/// </item>
/// <item>
/// <term>NMPWAIT_USE_DEFAULT_WAIT0x00000000</term>
/// <term>Uses the default time-out specified in a call to the CreateNamedPipe function.</term>
/// </item>
/// </list>
/// </para>
/// </param>
/// <returns>
/// <para>If the function succeeds, the return value is nonzero.</para>
/// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para>
/// <para>
/// If the message written to the pipe by the server process is longer than nOutBufferSize, <c>CallNamedPipe</c> returns <c>FALSE</c>, and
/// <c>GetLastError</c> returns ERROR_MORE_DATA. The remainder of the message is discarded, because <c>CallNamedPipe</c> closes the handle to the pipe
/// before returning.
/// </para>
/// </returns>
// BOOL WINAPI CallNamedPipe( _In_ LPCTSTR lpNamedPipeName, _In_ LPVOID lpInBuffer, _In_ DWORD nInBufferSize, _Out_ LPVOID lpOutBuffer, _In_ DWORD
// nOutBufferSize, _Out_ LPDWORD lpBytesRead, _In_ DWORD nTimeOut); https://msdn.microsoft.com/en-us/library/windows/desktop/aa365144(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)]
[PInvokeData("Winbase.h", MSDNShortId = "aa365144")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool CallNamedPipe([In] string lpNamedPipeName, [In] IntPtr lpInBuffer, uint nInBufferSize, IntPtr lpOutBuffer, uint nOutBufferSize,
[Out] out uint lpBytesRead, uint nTimeOut);
/// <summary>
/// Enables a named pipe server process to wait for a client process to connect to an instance of a named pipe. A client process connects by calling
/// either the <c>CreateFile</c> or <c>CallNamedPipe</c> function.
/// </summary>
/// <param name="hNamedPipe">A handle to the server end of a named pipe instance. This handle is returned by the <c>CreateNamedPipe</c> function.</param>
/// <param name="lpOverlapped">
/// <para>A pointer to an <c>OVERLAPPED</c> structure.</para>
/// <para>
/// If hNamedPipe was opened with FILE_FLAG_OVERLAPPED, the lpOverlapped parameter must not be <c>NULL</c>. It must point to a valid <c>OVERLAPPED</c>
/// structure. If hNamedPipe was opened with FILE_FLAG_OVERLAPPED and lpOverlapped is <c>NULL</c>, the function can incorrectly report that the connect
/// operation is complete.
/// </para>
/// <para>
/// If hNamedPipe was created with FILE_FLAG_OVERLAPPED and lpOverlapped is not <c>NULL</c>, the <c>OVERLAPPED</c> structure should contain a handle to a
/// manual-reset event object (which the server can create by using the <c>CreateEvent</c> function).
/// </para>
/// <para>
/// If hNamedPipe was not opened with FILE_FLAG_OVERLAPPED, the function does not return until a client is connected or an error occurs. Successful
/// synchronous operations result in the function returning a nonzero value if a client connects after the function is called.
/// </para>
/// </param>
/// <returns>
/// <para>
/// If the operation is synchronous, <c>ConnectNamedPipe</c> does not return until the operation has completed. If the function succeeds, the return
/// value is nonzero. If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.
/// </para>
/// <para>
/// If the operation is asynchronous, <c>ConnectNamedPipe</c> returns immediately. If the operation is still pending, the return value is zero and
/// <c>GetLastError</c> returns ERROR_IO_PENDING. (You can use the <c>HasOverlappedIoCompleted</c> macro to determine when the operation has finished.)
/// If the function fails, the return value is zero and <c>GetLastError</c> returns a value other than ERROR_IO_PENDING or ERROR_PIPE_CONNECTED.
/// </para>
/// <para>
/// If a client connects before the function is called, the function returns zero and <c>GetLastError</c> returns ERROR_PIPE_CONNECTED. This can happen
/// if a client connects in the interval between the call to <c>CreateNamedPipe</c> and the call to <c>ConnectNamedPipe</c>. In this situation, there is
/// a good connection between client and server, even though the function returns zero.
/// </para>
/// </returns>
// BOOL WINAPI ConnectNamedPipe( _In_ HANDLE hNamedPipe, _Inout_opt_ LPOVERLAPPED lpOverlapped); https://msdn.microsoft.com/en-us/library/windows/desktop/aa365146(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("Winbase.h", MSDNShortId = "aa365146")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern unsafe bool ConnectNamedPipe([In] IntPtr hNamedPipe, NativeOverlapped* lpOverlapped);
/// <summary>
/// Creates an instance of a named pipe and returns a handle for subsequent pipe operations. A named pipe server process uses this function either to
/// create the first instance of a specific named pipe and establish its basic attributes or to create a new instance of an existing named pipe.
/// </summary>
/// <param name="lpName">
/// <para>The unique pipe name. This string must have the following form:</para>
/// <para>\\.\pipe\pipename</para>
/// <para>
/// The pipename part of the name can include any character other than a backslash, including numbers and special characters. The entire pipe name string
/// can be up to 256 characters long. Pipe names are not case sensitive.
/// </para>
/// </param>
/// <param name="dwOpenMode">
/// <para>The open mode. The function fails if dwOpenMode specifies anything other than 0 or the flags listed in the following tables.</para>
/// <para>This parameter must specify one of the following pipe access modes. The same mode must be specified for each instance of the pipe.</para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Mode</term>
/// <term>Meaning</term>
/// </listheader>
/// <item>
/// <term>PIPE_ACCESS_DUPLEX0x00000003</term>
/// <term>
/// The pipe is bi-directional; both server and client processes can read from and write to the pipe. This mode gives the server the equivalent of
/// GENERIC_READ and GENERIC_WRITE access to the pipe. The client can specify GENERIC_READ or GENERIC_WRITE, or both, when it connects to the pipe using
/// the CreateFile function.
/// </term>
/// </item>
/// <item>
/// <term>PIPE_ACCESS_INBOUND0x00000001</term>
/// <term>
/// The flow of data in the pipe goes from client to server only. This mode gives the server the equivalent of GENERIC_READ access to the pipe. The
/// client must specify GENERIC_WRITE access when connecting to the pipe. If the client must read pipe settings by calling the GetNamedPipeInfo or
/// GetNamedPipeHandleState functions, the client must specify GENERIC_WRITE and FILE_READ_ATTRIBUTES access when connecting to the pipe.
/// </term>
/// </item>
/// <item>
/// <term>PIPE_ACCESS_OUTBOUND0x00000002</term>
/// <term>
/// The flow of data in the pipe goes from server to client only. This mode gives the server the equivalent of GENERIC_WRITE access to the pipe. The
/// client must specify GENERIC_READ access when connecting to the pipe. If the client must change pipe settings by calling the SetNamedPipeHandleState
/// function, the client must specify GENERIC_READ and FILE_WRITE_ATTRIBUTES access when connecting to the pipe.
/// </term>
/// </item>
/// </list>
/// </para>
/// <para>
/// This parameter can also include one or more of the following flags, which enable the write-through and overlapped modes. These modes can be different
/// for different instances of the same pipe.
/// </para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Mode</term>
/// <term>Meaning</term>
/// </listheader>
/// <item>
/// <term>FILE_FLAG_FIRST_PIPE_INSTANCE0x00080000</term>
/// <term>
/// If you attempt to create multiple instances of a pipe with this flag, creation of the first instance succeeds, but creation of the next instance
/// fails with ERROR_ACCESS_DENIED.
/// </term>
/// </item>
/// <item>
/// <term>FILE_FLAG_WRITE_THROUGH0x80000000</term>
/// <term>
/// Write-through mode is enabled. This mode affects only write operations on byte-type pipes and, then, only when the client and server processes are on
/// different computers. If this mode is enabled, functions writing to a named pipe do not return until the data written is transmitted across the
/// network and is in the pipe&amp;#39;s buffer on the remote computer. If this mode is not enabled, the system enhances the efficiency of network
/// operations by buffering data until a minimum number of bytes accumulate or until a maximum time elapses.
/// </term>
/// </item>
/// <item>
/// <term>FILE_FLAG_OVERLAPPED0x40000000</term>
/// <term>
/// Overlapped mode is enabled. If this mode is enabled, functions performing read, write, and connect operations that may take a significant time to be
/// completed can return immediately. This mode enables the thread that started the operation to perform other operations while the time-consuming
/// operation executes in the background. For example, in overlapped mode, a thread can handle simultaneous input and output (I/O) operations on multiple
/// instances of a pipe or perform simultaneous read and write operations on the same pipe handle. If overlapped mode is not enabled, functions
/// performing read, write, and connect operations on the pipe handle do not return until the operation is finished. The ReadFileEx and WriteFileEx
/// functions can only be used with a pipe handle in overlapped mode. The ReadFile, WriteFile, ConnectNamedPipe, and TransactNamedPipe functions can
/// execute either synchronously or as overlapped operations.
/// </term>
/// </item>
/// </list>
/// </para>
/// <para>
/// This parameter can include any combination of the following security access modes. These modes can be different for different instances of the same pipe.
/// </para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Mode</term>
/// <term>Meaning</term>
/// </listheader>
/// <item>
/// <term>WRITE_DAC0x00040000L</term>
/// <term>The caller will have write access to the named pipe&amp;#39;s discretionary access control list (ACL).</term>
/// </item>
/// <item>
/// <term>WRITE_OWNER0x00080000L</term>
/// <term>The caller will have write access to the named pipe&amp;#39;s owner.</term>
/// </item>
/// <item>
/// <term>ACCESS_SYSTEM_SECURITY0x01000000L</term>
/// <term>
/// The caller will have write access to the named pipe&amp;#39;s SACL. For more information, see Access-Control Lists (ACLs) and SACL Access Right.
/// </term>
/// </item>
/// </list>
/// </para>
/// </param>
/// <param name="dwPipeMode">
/// <para>The pipe mode. The function fails if dwPipeMode specifies anything other than 0 or the flags listed in the following tables.</para>
/// <para>One of the following type modes can be specified. The same type mode must be specified for each instance of the pipe.</para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Mode</term>
/// <term>Meaning</term>
/// </listheader>
/// <item>
/// <term>PIPE_TYPE_BYTE0x00000000</term>
/// <term>
/// Data is written to the pipe as a stream of bytes. This mode cannot be used with PIPE_READMODE_MESSAGE. The pipe does not distinguish bytes written
/// during different write operations.
/// </term>
/// </item>
/// <item>
/// <term>PIPE_TYPE_MESSAGE0x00000004</term>
/// <term>
/// Data is written to the pipe as a stream of messages. The pipe treats the bytes written during each write operation as a message unit. The
/// GetLastError function returns ERROR_MORE_DATA when a message is not read completely. This mode can be used with either PIPE_READMODE_MESSAGE or PIPE_READMODE_BYTE.
/// </term>
/// </item>
/// </list>
/// </para>
/// <para>One of the following read modes can be specified. Different instances of the same pipe can specify different read modes.</para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Mode</term>
/// <term>Meaning</term>
/// </listheader>
/// <item>
/// <term>PIPE_READMODE_BYTE0x00000000</term>
/// <term>Data is read from the pipe as a stream of bytes. This mode can be used with either PIPE_TYPE_MESSAGE or PIPE_TYPE_BYTE.</term>
/// </item>
/// <item>
/// <term>PIPE_READMODE_MESSAGE0x00000002</term>
/// <term>Data is read from the pipe as a stream of messages. This mode can be only used if PIPE_TYPE_MESSAGE is also specified.</term>
/// </item>
/// </list>
/// </para>
/// <para>One of the following wait modes can be specified. Different instances of the same pipe can specify different wait modes.</para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Mode</term>
/// <term>Meaning</term>
/// </listheader>
/// <item>
/// <term>PIPE_WAIT0x00000000</term>
/// <term>
/// Blocking mode is enabled. When the pipe handle is specified in the ReadFile, WriteFile, or ConnectNamedPipe function, the operations are not
/// completed until there is data to read, all data is written, or a client is connected. Use of this mode can mean waiting indefinitely in some
/// situations for a client process to perform an action.
/// </term>
/// </item>
/// <item>
/// <term>PIPE_NOWAIT0x00000001</term>
/// <term>
/// Nonblocking mode is enabled. In this mode, ReadFile, WriteFile, and ConnectNamedPipe always return immediately.Note that nonblocking mode is
/// supported for compatibility with Microsoft LAN Manager version 2.0 and should not be used to achieve asynchronous I/O with named pipes. For more
/// information on asynchronous pipe I/O, see Synchronous and Overlapped Input and Output.
/// </term>
/// </item>
/// </list>
/// </para>
/// <para>One of the following remote-client modes can be specified. Different instances of the same pipe can specify different remote-client modes.</para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Mode</term>
/// <term>Meaning</term>
/// </listheader>
/// <item>
/// <term>PIPE_ACCEPT_REMOTE_CLIENTS0x00000000</term>
/// <term>Connections from remote clients can be accepted and checked against the security descriptor for the pipe.</term>
/// </item>
/// <item>
/// <term>PIPE_REJECT_REMOTE_CLIENTS0x00000008</term>
/// <term>Connections from remote clients are automatically rejected.</term>
/// </item>
/// </list>
/// </para>
/// </param>
/// <param name="nMaxInstances">
/// <para>
/// The maximum number of instances that can be created for this pipe. The first instance of the pipe can specify this value; the same number must be
/// specified for other instances of the pipe. Acceptable values are in the range 1 through <c>PIPE_UNLIMITED_INSTANCES</c> (255).
/// </para>
/// <para>
/// If this parameter is <c>PIPE_UNLIMITED_INSTANCES</c>, the number of pipe instances that can be created is limited only by the availability of system
/// resources. If nMaxInstances is greater than <c>PIPE_UNLIMITED_INSTANCES</c>, the return value is <c>INVALID_HANDLE_VALUE</c> and <c>GetLastError</c>
/// returns <c>ERROR_INVALID_PARAMETER</c>.
/// </para>
/// </param>
/// <param name="nOutBufferSize">
/// The number of bytes to reserve for the output buffer. For a discussion on sizing named pipe buffers, see the following Remarks section.
/// </param>
/// <param name="nInBufferSize">
/// The number of bytes to reserve for the input buffer. For a discussion on sizing named pipe buffers, see the following Remarks section.
/// </param>
/// <param name="nDefaultTimeOut">
/// <para>
/// The default time-out value, in milliseconds, if the <c>WaitNamedPipe</c> function specifies <c>NMPWAIT_USE_DEFAULT_WAIT</c>. Each instance of a named
/// pipe must specify the same value.
/// </para>
/// <para>A value of zero will result in a default time-out of 50 milliseconds.</para>
/// </param>
/// <param name="lpSecurityAttributes">
/// A pointer to a <c>SECURITY_ATTRIBUTES</c> structure that specifies a security descriptor for the new named pipe and determines whether child
/// processes can inherit the returned handle. If lpSecurityAttributes is <c>NULL</c>, the named pipe gets a default security descriptor and the handle
/// cannot be inherited. The ACLs in the default security descriptor for a named pipe grant full control to the LocalSystem account, administrators, and
/// the creator owner. They also grant read access to members of the Everyone group and the anonymous account.
/// </param>
/// <returns>
/// <para>If the function succeeds, the return value is a handle to the server end of a named pipe instance.</para>
/// <para>If the function fails, the return value is <c>INVALID_HANDLE_VALUE</c>. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// HANDLE WINAPI CreateNamedPipe( _In_ LPCTSTR lpName, _In_ DWORD dwOpenMode, _In_ DWORD dwPipeMode, _In_ DWORD nMaxInstances, _In_ DWORD nOutBufferSize,
// _In_ DWORD nInBufferSize, _In_ DWORD nDefaultTimeOut, _In_opt_ LPSECURITY_ATTRIBUTES lpSecurityAttributes); https://msdn.microsoft.com/en-us/library/windows/desktop/aa365150(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)]
[PInvokeData("Winbase.h", MSDNShortId = "aa365150")]
public static extern IntPtr CreateNamedPipe([In] string lpName, uint dwOpenMode, PIPE_TYPE dwPipeMode, uint nMaxInstances, uint nOutBufferSize, uint nInBufferSize,
uint nDefaultTimeOut, [In] ref SECURITY_ATTRIBUTES lpSecurityAttributes);
/// <summary>Creates an anonymous pipe, and returns handles to the read and write ends of the pipe.</summary>
/// <param name="hReadPipe">A pointer to a variable that receives the read handle for the pipe.</param>
/// <param name="hWritePipe">A pointer to a variable that receives the write handle for the pipe.</param>
/// <param name="lpPipeAttributes">
/// <para>
/// A pointer to a <c>SECURITY_ATTRIBUTES</c> structure that determines whether the returned handle can be inherited by child processes. If
/// lpPipeAttributes is <c>NULL</c>, the handle cannot be inherited.
/// </para>
/// <para>
/// The <c>lpSecurityDescriptor</c> member of the structure specifies a security descriptor for the new pipe. If lpPipeAttributes is <c>NULL</c>, the
/// pipe gets a default security descriptor. The ACLs in the default security descriptor for a pipe come from the primary or impersonation token of the creator.
/// </para>
/// </param>
/// <param name="nSize">
/// The size of the buffer for the pipe, in bytes. The size is only a suggestion; the system uses the value to calculate an appropriate buffering
/// mechanism. If this parameter is zero, the system uses the default buffer size.
/// </param>
/// <returns>
/// <para>If the function succeeds, the return value is nonzero.</para>
/// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// BOOL WINAPI CreatePipe( _Out_ PHANDLE hReadPipe, _Out_ PHANDLE hWritePipe, _In_opt_ LPSECURITY_ATTRIBUTES lpPipeAttributes, _In_ DWORD nSize); https://msdn.microsoft.com/en-us/library/windows/desktop/aa365152(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("Winbase.h", MSDNShortId = "aa365152")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool CreatePipe(out IntPtr hReadPipe, out IntPtr hWritePipe, [In] ref SECURITY_ATTRIBUTES lpPipeAttributes, uint nSize);
/// <summary>Disconnects the server end of a named pipe instance from a client process.</summary>
/// <param name="hNamedPipe">A handle to an instance of a named pipe. This handle must be created by the <c>CreateNamedPipe</c> function.</param>
/// <returns>
/// <para>If the function succeeds, the return value is nonzero.</para>
/// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// BOOL WINAPI DisconnectNamedPipe( _In_ HANDLE hNamedPipe); https://msdn.microsoft.com/en-us/library/windows/desktop/aa365166(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("Winbase.h", MSDNShortId = "aa365166")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool DisconnectNamedPipe([In] IntPtr hNamedPipe);
/// <summary>Retrieves the client computer name for the specified named pipe.</summary>
/// <param name="Pipe">A handle to an instance of a named pipe. This handle must be created by the <c>CreateNamedPipe</c> function.</param>
/// <param name="ClientComputerName">The computer name.</param>
/// <param name="ClientComputerNameLength">The size of the ClientComputerName buffer, in bytes.</param>
/// <returns>
/// <para>If the function succeeds, the return value is nonzero.</para>
/// <para>If the function fails, the return value is zero. To get extended error information, call the <c>GetLastError</c> function.</para>
/// </returns>
// BOOL WINAPI GetNamedPipeClientComputerName( _In_ HANDLE Pipe, _Out_ LPTSTR ClientComputerName, _In_ ULONG ClientComputerNameLength); https://msdn.microsoft.com/en-us/library/windows/desktop/aa365437(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)]
[PInvokeData("Winbase.h", MSDNShortId = "aa365437")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetNamedPipeClientComputerName(IntPtr Pipe, StringBuilder ClientComputerName, uint ClientComputerNameLength);
/// <summary>
/// Retrieves information about a specified named pipe. The information returned can vary during the lifetime of an instance of the named pipe.
/// </summary>
/// <param name="hNamedPipe">
/// <para>
/// A handle to the named pipe for which information is wanted. The handle must have GENERIC_READ access for a read-only or read/write pipe, or it must
/// have GENERIC_WRITE and FILE_READ_ATTRIBUTES access for a write-only pipe.
/// </para>
/// <para>This parameter can also be a handle to an anonymous pipe, as returned by the <c>CreatePipe</c> function.</para>
/// </param>
/// <param name="lpState">
/// <para>
/// A pointer to a variable that indicates the current state of the handle. This parameter can be <c>NULL</c> if this information is not needed. Either
/// or both of the following values can be specified.
/// </para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Value</term>
/// <term>Meaning</term>
/// </listheader>
/// <item>
/// <term>PIPE_NOWAIT0x00000001</term>
/// <term>The pipe handle is in nonblocking mode. If this flag is not specified, the pipe handle is in blocking mode.</term>
/// </item>
/// <item>
/// <term>PIPE_READMODE_MESSAGE0x00000002</term>
/// <term>The pipe handle is in message-read mode. If this flag is not specified, the pipe handle is in byte-read mode.</term>
/// </item>
/// </list>
/// </para>
/// </param>
/// <param name="lpCurInstances">
/// A pointer to a variable that receives the number of current pipe instances. This parameter can be <c>NULL</c> if this information is not required.
/// </param>
/// <param name="lpMaxCollectionCount">
/// A pointer to a variable that receives the maximum number of bytes to be collected on the client's computer before transmission to the server. This
/// parameter must be <c>NULL</c> if the specified pipe handle is to the server end of a named pipe or if client and server processes are on the same
/// computer. This parameter can be <c>NULL</c> if this information is not required.
/// </param>
/// <param name="lpCollectDataTimeout">
/// A pointer to a variable that receives the maximum time, in milliseconds, that can pass before a remote named pipe transfers information over the
/// network. This parameter must be <c>NULL</c> if the specified pipe handle is to the server end of a named pipe or if client and server processes are
/// on the same computer. This parameter can be <c>NULL</c> if this information is not required.
/// </param>
/// <param name="lpUserName">
/// <para>
/// A pointer to a buffer that receives the user name string associated with the client application. The server can only retrieve this information if the
/// client opened the pipe with SECURITY_IMPERSONATION access.
/// </para>
/// <para>
/// This parameter must be <c>NULL</c> if the specified pipe handle is to the client end of a named pipe. This parameter can be <c>NULL</c> if this
/// information is not required.
/// </para>
/// </param>
/// <param name="nMaxUserNameSize">
/// The size of the buffer specified by the lpUserName parameter, in <c>TCHARs</c>. This parameter is ignored if lpUserName is <c>NULL</c>.
/// </param>
/// <returns>
/// <para>If the function succeeds, the return value is nonzero.</para>
/// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// BOOL WINAPI GetNamedPipeHandleState( _In_ HANDLE hNamedPipe, _Out_opt_ LPDWORD lpState, _Out_opt_ LPDWORD lpCurInstances, _Out_opt_ LPDWORD
// lpMaxCollectionCount, _Out_opt_ LPDWORD lpCollectDataTimeout, _Out_opt_ LPTSTR lpUserName, _In_ DWORD nMaxUserNameSize); https://msdn.microsoft.com/en-us/library/windows/desktop/aa365443(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)]
[PInvokeData("Winbase.h", MSDNShortId = "aa365443")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetNamedPipeHandleState([In] IntPtr hNamedPipe, out PIPE_TYPE lpState, out uint lpCurInstances, out uint lpMaxCollectionCount, out uint lpCollectDataTimeout,
[Out] StringBuilder lpUserName, uint nMaxUserNameSize);
/// <summary>Retrieves information about the specified named pipe.</summary>
/// <param name="hNamedPipe">
/// <para>
/// A handle to the named pipe instance. The handle must have GENERIC_READ access to the named pipe for a read-only or read/write pipe, or it must have
/// GENERIC_WRITE and FILE_READ_ATTRIBUTES access for a write-only pipe.
/// </para>
/// <para>This parameter can also be a handle to an anonymous pipe, as returned by the <c>CreatePipe</c> function.</para>
/// </param>
/// <param name="lpFlags">
/// <para>
/// A pointer to a variable that receives the type of the named pipe. This parameter can be <c>NULL</c> if this information is not required. Otherwise,
/// this parameter can be one or more of the following values.
/// </para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Value</term>
/// <term>Meaning</term>
/// </listheader>
/// <item>
/// <term>PIPE_CLIENT_END0x00000000</term>
/// <term>The handle refers to the client end of a named pipe instance. This is the default.</term>
/// </item>
/// <item>
/// <term>PIPE_SERVER_END0x00000001</term>
/// <term>
/// The handle refers to the server end of a named pipe instance. If this value is not specified, the handle refers to the client end of a named pipe instance.
/// </term>
/// </item>
/// <item>
/// <term>PIPE_TYPE_BYTE0x00000000</term>
/// <term>The named pipe is a byte pipe. This is the default.</term>
/// </item>
/// <item>
/// <term>PIPE_TYPE_MESSAGE0x00000004</term>
/// <term>The named pipe is a message pipe. If this value is not specified, the pipe is a byte pipe.</term>
/// </item>
/// </list>
/// </para>
/// </param>
/// <param name="lpOutBufferSize">
/// A pointer to a variable that receives the size of the buffer for outgoing data, in bytes. If the buffer size is zero, the buffer is allocated as
/// needed. This parameter can be <c>NULL</c> if this information is not required.
/// </param>
/// <param name="lpInBufferSize">
/// A pointer to a variable that receives the size of the buffer for incoming data, in bytes. If the buffer size is zero, the buffer is allocated as
/// needed. This parameter can be <c>NULL</c> if this information is not required.
/// </param>
/// <param name="lpMaxInstances">
/// A pointer to a variable that receives the maximum number of pipe instances that can be created. If the variable is set to PIPE_UNLIMITED_INSTANCES
/// (255), the number of pipe instances that can be created is limited only by the availability of system resources. This parameter can be <c>NULL</c> if
/// this information is not required.
/// </param>
/// <returns>
/// <para>If the function succeeds, the return value is nonzero.</para>
/// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// BOOL WINAPI GetNamedPipeInfo( _In_ HANDLE hNamedPipe, _Out_opt_ LPDWORD lpFlags, _Out_opt_ LPDWORD lpOutBufferSize, _Out_opt_ LPDWORD lpInBufferSize,
// _Out_opt_ LPDWORD lpMaxInstances); https://msdn.microsoft.com/en-us/library/windows/desktop/aa365445(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("Winbase.h", MSDNShortId = "aa365445")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetNamedPipeInfo([In] IntPtr hNamedPipe, out PIPE_TYPE lpFlags, out uint lpOutBufferSize, out uint lpInBufferSize, out uint lpMaxInstances);
/// <summary>
/// Copies data from a named or anonymous pipe into a buffer without removing it from the pipe. It also returns information about data in the pipe.
/// </summary>
/// <param name="hNamedPipe">
/// A handle to the pipe. This parameter can be a handle to a named pipe instance, as returned by the <c>CreateNamedPipe</c> or <c>CreateFile</c>
/// function, or it can be a handle to the read end of an anonymous pipe, as returned by the <c>CreatePipe</c> function. The handle must have
/// GENERIC_READ access to the pipe.
/// </param>
/// <param name="lpBuffer">A pointer to a buffer that receives data read from the pipe. This parameter can be <c>NULL</c> if no data is to be read.</param>
/// <param name="nBufferSize">The size of the buffer specified by the lpBuffer parameter, in bytes. This parameter is ignored if lpBuffer is <c>NULL</c>.</param>
/// <param name="lpBytesRead">
/// A pointer to a variable that receives the number of bytes read from the pipe. This parameter can be <c>NULL</c> if no data is to be read.
/// </param>
/// <param name="lpTotalBytesAvail">
/// A pointer to a variable that receives the total number of bytes available to be read from the pipe. This parameter can be <c>NULL</c> if no data is
/// to be read.
/// </param>
/// <param name="lpBytesLeftThisMessage">
/// A pointer to a variable that receives the number of bytes remaining in this message. This parameter will be zero for byte-type named pipes or for
/// anonymous pipes. This parameter can be <c>NULL</c> if no data is to be read.
/// </param>
/// <returns>
/// <para>If the function succeeds, the return value is nonzero.</para>
/// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// BOOL WINAPI PeekNamedPipe( _In_ HANDLE hNamedPipe, _Out_opt_ LPVOID lpBuffer, _In_ DWORD nBufferSize, _Out_opt_ LPDWORD lpBytesRead, _Out_opt_ LPDWORD
// lpTotalBytesAvail, _Out_opt_ LPDWORD lpBytesLeftThisMessage); https://msdn.microsoft.com/en-us/library/windows/desktop/aa365779(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("Winbase.h", MSDNShortId = "aa365779")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool PeekNamedPipe([In] IntPtr hNamedPipe, IntPtr lpBuffer, uint nBufferSize, out uint lpBytesRead, out uint lpTotalBytesAvail, out uint lpBytesLeftThisMessage);
/// <summary>
/// Sets the read mode and the blocking mode of the specified named pipe. If the specified handle is to the client end of a named pipe and if the named
/// pipe server process is on a remote computer, the function can also be used to control local buffering.
/// </summary>
/// <param name="hNamedPipe">
/// <para>
/// A handle to the named pipe instance. This parameter can be a handle to the server end of the pipe, as returned by the <c>CreateNamedPipe</c>
/// function, or to the client end of the pipe, as returned by the <c>CreateFile</c> function. The handle must have GENERIC_WRITE access to the named
/// pipe for a write-only or read/write pipe, or it must have GENERIC_READ and FILE_WRITE_ATTRIBUTES access for a read-only pipe.
/// </para>
/// <para>This parameter can also be a handle to an anonymous pipe, as returned by the <c>CreatePipe</c> function.</para>
/// </param>
/// <param name="lpMode">
/// <para>
/// The new pipe mode. The mode is a combination of a read-mode flag and a wait-mode flag. This parameter can be <c>NULL</c> if the mode is not being
/// set. Specify one of the following modes.
/// </para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Mode</term>
/// <term>Meaning</term>
/// </listheader>
/// <item>
/// <term>PIPE_READMODE_BYTE0x00000000</term>
/// <term>Data is read from the pipe as a stream of bytes. This mode is the default if no read-mode flag is specified.</term>
/// </item>
/// <item>
/// <term>PIPE_READMODE_MESSAGE0x00000002</term>
/// <term>Data is read from the pipe as a stream of messages. The function fails if this flag is specified for a byte-type pipe.</term>
/// </item>
/// </list>
/// </para>
/// <para>One of the following wait modes can be specified.</para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Mode</term>
/// <term>Meaning</term>
/// </listheader>
/// <item>
/// <term>PIPE_WAIT0x00000000</term>
/// <term>
/// Blocking mode is enabled. This mode is the default if no wait-mode flag is specified. When a blocking mode pipe handle is specified in the ReadFile,
/// WriteFile, or ConnectNamedPipe function, operations are not finished until there is data to read, all data is written, or a client is connected. Use
/// of this mode can mean waiting indefinitely in some situations for a client process to perform an action.
/// </term>
/// </item>
/// <item>
/// <term>PIPE_NOWAIT0x00000001</term>
/// <term>
/// Nonblocking mode is enabled. In this mode, ReadFile, WriteFile, and ConnectNamedPipe always return immediately. Note that nonblocking mode is
/// supported for compatibility with Microsoft LAN Manager version 2.0 and should not be used to achieve asynchronous input and output (I/O) with named pipes.
/// </term>
/// </item>
/// </list>
/// </para>
/// </param>
/// <param name="lpMaxCollectionCount">
/// The maximum number of bytes collected on the client computer before transmission to the server. This parameter must be <c>NULL</c> if the specified
/// pipe handle is to the server end of a named pipe or if client and server processes are on the same machine. This parameter is ignored if the client
/// process specifies the FILE_FLAG_WRITE_THROUGH flag in the <c>CreateFile</c> function when the handle was created. This parameter can be <c>NULL</c>
/// if the collection count is not being set.
/// </param>
/// <param name="lpCollectDataTimeout">
/// The maximum time, in milliseconds, that can pass before a remote named pipe transfers information over the network. This parameter must be
/// <c>NULL</c> if the specified pipe handle is to the server end of a named pipe or if client and server processes are on the same computer. This
/// parameter is ignored if the client process specified the FILE_FLAG_WRITE_THROUGH flag in the <c>CreateFile</c> function when the handle was created.
/// This parameter can be <c>NULL</c> if the collection count is not being set.
/// </param>
/// <returns>
/// <para>If the function succeeds, the return value is nonzero.</para>
/// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// BOOL WINAPI SetNamedPipeHandleState( _In_ HANDLE hNamedPipe, _In_opt_ LPDWORD lpMode, _In_opt_ LPDWORD lpMaxCollectionCount, _In_opt_ LPDWORD
// lpCollectDataTimeout); https://msdn.microsoft.com/en-us/library/windows/desktop/aa365787(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("Winbase.h", MSDNShortId = "aa365787")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetNamedPipeHandleState([In] IntPtr hNamedPipe, [In] IntPtr lpMode, [In] IntPtr lpMaxCollectionCount, [In] IntPtr lpCollectDataTimeout);
/// <summary>Combines the functions that write a message to and read a message from the specified named pipe into a single network operation.</summary>
/// <param name="hNamedPipe">
/// <para>A handle to the named pipe returned by the <c>CreateNamedPipe</c> or <c>CreateFile</c> function.</para>
/// <para>This parameter can also be a handle to an anonymous pipe, as returned by the <c>CreatePipe</c> function.</para>
/// </param>
/// <param name="lpInBuffer">A pointer to the buffer containing the data to be written to the pipe.</param>
/// <param name="nInBufferSize">The size of the input buffer, in bytes.</param>
/// <param name="lpOutBuffer">A pointer to the buffer that receives the data read from the pipe.</param>
/// <param name="nOutBufferSize">The size of the output buffer, in bytes.</param>
/// <param name="lpBytesRead">
/// <para>A pointer to the variable that receives the number of bytes read from the pipe.</para>
/// <para>If lpOverlapped is <c>NULL</c>, lpBytesRead cannot be <c>NULL</c>.</para>
/// <para>
/// If lpOverlapped is not <c>NULL</c>, lpBytesRead can be <c>NULL</c>. If this is an overlapped read operation, you can get the number of bytes read by
/// calling <c>GetOverlappedResult</c>. If hNamedPipe is associated with an I/O completion port, you can get the number of bytes read by calling <c>GetQueuedCompletionStatus</c>.
/// </para>
/// </param>
/// <param name="lpOverlapped">
/// <para>A pointer to an <c>OVERLAPPED</c> structure. This structure is required if hNamedPipe was opened with FILE_FLAG_OVERLAPPED.</para>
/// <para>
/// If hNamedPipe was opened with FILE_FLAG_OVERLAPPED, the lpOverlapped parameter must not be <c>NULL</c>. It must point to a valid <c>OVERLAPPED</c>
/// structure. If hNamedPipe was created with FILE_FLAG_OVERLAPPED and lpOverlapped is <c>NULL</c>, the function can incorrectly report that the
/// operation is complete.
/// </para>
/// <para>
/// If hNamedPipe was opened with FILE_FLAG_OVERLAPPED and lpOverlapped is not <c>NULL</c>, <c>TransactNamedPipe</c> is executed as an overlapped
/// operation. The <c>OVERLAPPED</c> structure should contain a manual-reset event object (which can be created by using the <c>CreateEvent</c>
/// function). If the operation cannot be completed immediately, <c>TransactNamedPipe</c> returns <c>FALSE</c> and <c>GetLastError</c> returns
/// ERROR_IO_PENDING. In this situation, the event object is set to the nonsignaled state before <c>TransactNamedPipe</c> returns, and it is set to the
/// signaled state when the transaction has finished. Also, you can be notified when an overlapped operation completes by using the
/// <c>GetQueuedCompletionStatus</c> or <c>GetQueuedCompletionStatusEx</c> functions. In this case, you do not need to assign the manual-reset event in
/// the <c>OVERLAPPED</c> structure, and the completion happens against hNamedPipe in the same way as an asynchronous read or write operation. For more
/// information about overlapped operations, see Pipes.
/// </para>
/// <para>If hNamedPipe was not opened with FILE_FLAG_OVERLAPPED, <c>TransactNamedPipe</c> does not return until the operation is complete.</para>
/// </param>
/// <returns>
/// <para>If the function succeeds, the return value is nonzero.</para>
/// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para>
/// <para>
/// If the message to be read is longer than the buffer specified by the nOutBufferSize parameter, <c>TransactNamedPipe</c> returns <c>FALSE</c> and the
/// <c>GetLastError</c> function returns ERROR_MORE_DATA. The remainder of the message can be read by a subsequent call to <c>ReadFile</c>,
/// <c>ReadFileEx</c>, or <c>PeekNamedPipe</c>.
/// </para>
/// </returns>
// BOOL WINAPI TransactNamedPipe( _In_ HANDLE hNamedPipe, _In_ LPVOID lpInBuffer, _In_ DWORD nInBufferSize, _Out_ LPVOID lpOutBuffer, _In_ DWORD
// nOutBufferSize, _Out_ LPDWORD lpBytesRead, _Inout_opt_ LPOVERLAPPED lpOverlapped); https://msdn.microsoft.com/en-us/library/windows/desktop/aa365790(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("Winbase.h", MSDNShortId = "aa365790")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern unsafe bool TransactNamedPipe([In] IntPtr hNamedPipe, [In] IntPtr lpInBuffer, uint nInBufferSize, IntPtr lpOutBuffer, uint nOutBufferSize, [Out] out uint lpBytesRead,
NativeOverlapped* lpOverlapped);
/// <summary>
/// Waits until either a time-out interval elapses or an instance of the specified named pipe is available for connection (that is, the pipe's server
/// process has a pending <c>ConnectNamedPipe</c> operation on the pipe).
/// </summary>
/// <param name="lpNamedPipeName">
/// <para>
/// The name of the named pipe. The string must include the name of the computer on which the server process is executing. A period may be used for the
/// servername if the pipe is local. The following pipe name format is used:
/// </para>
/// <para>\\servername\pipe\pipename</para>
/// </param>
/// <param name="nTimeOut">
/// <para>
/// The number of milliseconds that the function will wait for an instance of the named pipe to be available. You can used one of the following values
/// instead of specifying a number of milliseconds.
/// </para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Value</term>
/// <term>Meaning</term>
/// </listheader>
/// <item>
/// <term>NMPWAIT_USE_DEFAULT_WAIT0x00000000</term>
/// <term>The time-out interval is the default value specified by the server process in the CreateNamedPipe function.</term>
/// </item>
/// <item>
/// <term>NMPWAIT_WAIT_FOREVER0xffffffff</term>
/// <term>The function does not return until an instance of the named pipe is available.</term>
/// </item>
/// </list>
/// </para>
/// </param>
/// <returns>
/// <para>If an instance of the pipe is available before the time-out interval elapses, the return value is nonzero.</para>
/// <para>
/// If an instance of the pipe is not available before the time-out interval elapses, the return value is zero. To get extended error information, call <c>GetLastError</c>.
/// </para>
/// </returns>
// BOOL WINAPI WaitNamedPipe( _In_ LPCTSTR lpNamedPipeName, _In_ DWORD nTimeOut); https://msdn.microsoft.com/en-us/library/windows/desktop/aa365800(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)]
[PInvokeData("Winbase.h", MSDNShortId = "aa365800")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool WaitNamedPipe([In] string lpNamedPipeName, uint nTimeOut);
}
}

View File

@ -0,0 +1,371 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
using Vanara.Extensions;
using Vanara.InteropServices;
namespace Vanara.PInvoke
{
public static partial class Kernel32
{
/// <summary>Standard device handle types used by <see cref="GetStdHandle"/>.</summary>
[PInvokeData("Winbase.h")]
public enum StdHandleType : int
{
/// <summary>The standard input device. Initially, this is the console input buffer, CONIN$.</summary>
STD_INPUT_HANDLE = -10,
/// <summary>The standard output device. Initially, this is the active console screen buffer, CONOUT$.</summary>
STD_OUTPUT_HANDLE = -11,
/// <summary>The standard error device. Initially, this is the active console screen buffer, CONOUT$.</summary>
STD_ERROR_HANDLE = -12,
}
/// <summary>Retrieves a handle to the specified standard device (standard input, standard output, or standard error).</summary>
/// <param name="nStdHandle">
/// <para>The standard device. This parameter can be one of the following values.</para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Value</term>
/// <term>Meaning</term>
/// </listheader>
/// <item>
/// <term>STD_INPUT_HANDLE (DWORD)-10</term>
/// <term>The standard input device. Initially, this is the console input buffer, CONIN$.</term>
/// </item>
/// <item>
/// <term>STD_OUTPUT_HANDLE (DWORD)-11</term>
/// <term>The standard output device. Initially, this is the active console screen buffer, CONOUT$.</term>
/// </item>
/// <item>
/// <term>STD_ERROR_HANDLE (DWORD)-12</term>
/// <term>The standard error device. Initially, this is the active console screen buffer, CONOUT$.</term>
/// </item>
/// </list>
/// </para>
/// </param>
/// <returns>
/// <para>
/// If the function succeeds, the return value is a handle to the specified device, or a redirected handle set by a previous call to <c>SetStdHandle</c>.
/// The handle has <c>GENERIC_READ</c> and <c>GENERIC_WRITE</c> access rights, unless the application has used <c>SetStdHandle</c> to set a standard
/// handle with lesser access.
/// </para>
/// <para>If the function fails, the return value is <c>INVALID_HANDLE_VALUE</c>. To get extended error information, call <c>GetLastError</c>.</para>
/// <para>
/// If an application does not have associated standard handles, such as a service running on an interactive desktop, and has not redirected them, the
/// return value is <c>NULL</c>.
/// </para>
/// </returns>
// HANDLE WINAPI GetStdHandle( _In_ DWORD nStdHandle );
// https://docs.microsoft.com/en-us/windows/console/getstdhandle
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("Winbase.h")]
public static extern IntPtr GetStdHandle(StdHandleType nStdHandle);
/// <summary>Sets the environment strings.</summary>
/// <param name="NewEnvironment">The new environment strings. List of unicode null terminated strings with a double null termination at the end.</param>
/// <returns>
/// <para>If the function succeeds, the return value is nonzero.</para>
/// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
[PInvokeData("ProcessEnv.h", MSDNShortId = "")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetEnvironmentStringsW(string NewEnvironment);
/// <summary>Sets the handle for the specified standard device (standard input, standard output, or standard error).</summary>
/// <param name="nStdHandle">
/// <para>The standard device for which the handle is to be set. This parameter can be one of the following values.</para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Value</term>
/// <term>Meaning</term>
/// </listheader>
/// <item>
/// <term>STD_INPUT_HANDLE (DWORD)-10</term>
/// <term>The standard input device.</term>
/// </item>
/// <item>
/// <term>STD_OUTPUT_HANDLE (DWORD)-11</term>
/// <term>The standard output device.</term>
/// </item>
/// <item>
/// <term>STD_ERROR_HANDLE (DWORD)-12</term>
/// <term>The standard error device.</term>
/// </item>
/// </list>
/// </para>
/// </param>
/// <param name="hHandle">The handle for the standard device.</param>
/// <returns>
/// <para>If the function succeeds, the return value is nonzero.</para>
/// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// BOOL WINAPI SetStdHandle( _In_ DWORD nStdHandle, _In_ HANDLE hHandle );
// https://docs.microsoft.com/en-us/windows/console/setstdhandle
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("Winbase.h", MSDNShortId = "")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetStdHandle(StdHandleType nStdHandle, IntPtr hHandle);
/// <summary>Sets the handle for the specified standard device and returns the previous one</summary>
/// <param name="nStdHandle">The standard handle to replace. Can be STD_INPUT_HANDLE, STD_OUTPUT_HANDLE or STD_ERROR_HANDLE</param>
/// <param name="hHandle">The new handle</param>
/// <param name="phPrevValue">A pointer to a handle that receives the previous value. Can be NULL in which case the function behaves exactly as SetStdHandle</param>
/// <returns>Non-zero if the function succeeds, zero otherwise. More information is available via GetLastError</returns>
// BOOL WINAPI SetStdHandleEx (DWORD nStdHandle, HANDLE hHandle, HANDLE* phPrevValue)
// http://undoc.airesoft.co.uk/kernel32.dll/SetStdHandleEx.php
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("Winbase.h", MSDNShortId = "")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetStdHandleEx(StdHandleType nStdHandle, IntPtr hHandle, out IntPtr phPrevValue);
/// <summary>Retrieves the command-line string for the current process.</summary>
/// <returns>The return value is a pointer to the command-line string for the current process.</returns>
// LPTSTR WINAPI GetCommandLine(void);
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms683156(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, CharSet = CharSet.Auto)]
[PInvokeData("WinBase.h", MSDNShortId = "ms683156")]
public static extern string GetCommandLine();
/// <summary>Retrieves the environment variables for the current process.</summary>
/// <returns>
/// <para>If the function succeeds, the return value is a pointer to the environment block of the current process.</para>
/// <para>If the function fails, the return value is NULL.</para>
/// </returns>
// LPTCH WINAPI GetEnvironmentStrings(void);
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms683187(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, CharSet = CharSet.Auto)]
[PInvokeData("WinBase.h", MSDNShortId = "ms683187")]
public static extern EnvironmentStrings GetEnvironmentStrings();
/// <summary>Frees a block of environment strings.</summary>
/// <param name="lpszEnvironmentBlock">
/// A pointer to a block of environment strings. The pointer to the block must be obtained by calling the <c>GetEnvironmentStrings</c> function.
/// </param>
/// <returns>
/// <para>If the function succeeds, the return value is nonzero.</para>
/// <para>If the function fails, the return value is zero To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// BOOL WINAPI FreeEnvironmentStrings( _In_ LPTCH lpszEnvironmentBlock);
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms683151(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)]
[PInvokeData("WinBase.h", MSDNShortId = "ms683151")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool FreeEnvironmentStrings(IntPtr lpszEnvironmentBlock);
/// <summary>Represents a block of environment strings obtained by <see cref="GetEnvironmentStrings"/> and freed by <see cref="FreeEnvironmentStrings"/>.</summary>
/// <seealso cref="Vanara.InteropServices.GenericSafeHandle"/>
/// <seealso cref="System.Collections.Generic.IEnumerable{System.String}"/>
public sealed class EnvironmentStrings : GenericSafeHandle, IEnumerable<string>
{
/// <summary>Initializes a new instance of the <see cref="EnvironmentStrings"/> class.</summary>
public EnvironmentStrings() : this(IntPtr.Zero) { }
/// <summary>Initializes a new instance of the <see cref="EnvironmentStrings"/> class.</summary>
/// <param name="handle">The handle.</param>
public EnvironmentStrings(IntPtr handle) : base(handle, FreeEnvironmentStrings) { }
/// <summary>Gets the value.</summary>
/// <value>The value.</value>
public IEnumerable<string> Value => handle.ToStringEnum();
/// <summary>Returns an enumerator that iterates through the collection.</summary>
/// <returns>
/// A <see cref="T:System.Collections.Generic.IEnumerator`1" /> that can be used to iterate through the collection.
/// </returns>
public IEnumerator<string> GetEnumerator() => Value.GetEnumerator();
/// <summary>Returns an enumerator that iterates through a collection.</summary>
/// <returns>
/// An <see cref="T:System.Collections.IEnumerator" /> object that can be used to iterate through the collection.
/// </returns>
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
/// <summary>Retrieves the contents of the specified variable from the environment block of the calling process.</summary>
/// <param name="lpName">The name of the environment variable.</param>
/// <param name="lpBuffer">
/// A pointer to a buffer that receives the contents of the specified environment variable as a null-terminated string. An environment variable has a
/// maximum size limit of 32,767 characters, including the null-terminating character.
/// </param>
/// <param name="nSize">The size of the buffer pointed to by the lpBuffer parameter, including the null-terminating character, in characters.</param>
/// <returns>
/// <para>
/// If the function succeeds, the return value is the number of characters stored in the buffer pointed to by lpBuffer, not including the terminating
/// null character.
/// </para>
/// <para>
/// If lpBuffer is not large enough to hold the data, the return value is the buffer size, in characters, required to hold the string and its terminating
/// null character and the contents of lpBuffer are undefined.
/// </para>
/// <para>
/// If the function fails, the return value is zero. If the specified environment variable was not found in the environment block, <c>GetLastError</c>
/// returns ERROR_ENVVAR_NOT_FOUND.
/// </para>
/// </returns>
// DWORD WINAPI GetEnvironmentVariable( _In_opt_ LPCTSTR lpName, _Out_opt_ LPTSTR lpBuffer, _In_ DWORD nSize);
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms683188(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)]
[PInvokeData("WinBase.h", MSDNShortId = "ms683188")]
public static extern uint GetEnvironmentVariable(string lpName, StringBuilder lpBuffer, uint nSize);
/// <summary>Sets the contents of the specified environment variable for the current process.</summary>
/// <param name="lpName">
/// The name of the environment variable. The operating system creates the environment variable if it does not exist and lpValue is not NULL.
/// </param>
/// <param name="lpValue">
/// <para>
/// The contents of the environment variable. The maximum size of a user-defined environment variable is 32,767 characters. For more information, see
/// Environment Variables.
/// </para>
/// <para><c>Windows Server 2003 and Windows XP:</c> The total size of the environment block for a process may not exceed 32,767 characters.</para>
/// <para>If this parameter is NULL, the variable is deleted from the current process's environment.</para>
/// </param>
/// <returns>
/// <para>If the function succeeds, the return value is nonzero.</para>
/// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// BOOL WINAPI SetEnvironmentVariable( _In_ LPCTSTR lpName, _In_opt_ LPCTSTR lpValue);
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms686206(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)]
[PInvokeData("WinBase.h", MSDNShortId = "ms686206")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetEnvironmentVariable(string lpName, [Optional] string lpValue);
/// <summary>
/// <para>Expands environment-variable strings and replaces them with the values defined for the current user.</para>
/// <para>To specify the environment block for a particular user or the system, use the <c>ExpandEnvironmentStringsForUser</c> function.</para>
/// </summary>
/// <param name="lpSrc">
/// <para>
/// A buffer that contains one or more environment-variable strings in the form: %variableName%. For each such reference, the %variableName% portion is
/// replaced with the current value of that environment variable.
/// </para>
/// <para>Case is ignored when looking up the environment-variable name. If the name is not found, the %variableName% portion is left unexpanded.</para>
/// <para>
/// Note that this function does not support all the features that Cmd.exe supports. For example, it does not support %variableName:str1=str2% or %variableName:~offset,length%.
/// </para>
/// </param>
/// <param name="lpDst">
/// A pointer to a buffer that receives the result of expanding the environment variable strings in the lpSrc buffer. Note that this buffer cannot be the
/// same as the lpSrc buffer.
/// </param>
/// <param name="nSize">
/// The maximum number of characters that can be stored in the buffer pointed to by the lpDst parameter. When using ANSI strings, the buffer size should
/// be the string length, plus terminating null character, plus one. When using Unicode strings, the buffer size should be the string length plus the
/// terminating null character.
/// </param>
/// <returns>
/// <para>
/// If the function succeeds, the return value is the number of <c>TCHARs</c> stored in the destination buffer, including the terminating null character.
/// If the destination buffer is too small to hold the expanded string, the return value is the required buffer size, in characters.
/// </para>
/// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// DWORD WINAPI ExpandEnvironmentStrings( _In_ LPCTSTR lpSrc, _Out_opt_ LPTSTR lpDst, _In_ DWORD nSize);
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms724265(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)]
[PInvokeData("Winbase.h", MSDNShortId = "ms724265")]
public static extern uint ExpandEnvironmentStrings([In] string lpSrc, StringBuilder lpDst, uint nSize);
/// <summary>Changes the current directory for the current process.</summary>
/// <param name="lpPathName">
/// <para>
/// The path to the new current directory. This parameter may specify a relative path or a full path. In either case, the full path of the specified
/// directory is calculated and stored as the current directory. For more information, see File Names, Paths, and Namespaces.
/// </para>
/// <para>
/// In the ANSI version of this function, the name is limited to <c>MAX_PATH</c> characters. To extend this limit to 32,767 wide characters, call the
/// Unicode version of the function and prepend "\\?\" to the path. For more information, see Naming a File.
/// </para>
/// <para>
/// The final character before the null character must be a backslash ('\'). If you do not specify the backslash, it will be added for you; therefore,
/// specify <c>MAX_PATH</c>-2 characters for the path unless you include the trailing backslash, in which case, specify <c>MAX_PATH</c>-1 characters for
/// the path.
/// </para>
/// </param>
/// <returns>
/// <para>If the function succeeds, the return value is nonzero.</para>
/// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// BOOL WINAPI SetCurrentDirectory( _In_ LPCTSTR lpPathName);
// https://msdn.microsoft.com/en-us/library/windows/desktop/aa365530(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)]
[PInvokeData("WinBase.h", MSDNShortId = "aa365530")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetCurrentDirectory([In] string lpPathName);
/// <summary>Retrieves the current directory for the current process.</summary>
/// <param name="nBufferLength">
/// The length of the buffer for the current directory string, in <c>TCHARs</c>. The buffer length must include room for a terminating null character.
/// </param>
/// <param name="lpBuffer">
/// <para>
/// A pointer to the buffer that receives the current directory string. This null-terminated string specifies the absolute path to the current directory.
/// </para>
/// <para>To determine the required buffer size, set this parameter to <c>NULL</c> and the nBufferLength parameter to 0.</para>
/// </param>
/// <returns>
/// <para>
/// If the function succeeds, the return value specifies the number of characters that are written to the buffer, not including the terminating null character.
/// </para>
/// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para>
/// <para>
/// If the buffer that is pointed to by lpBuffer is not large enough, the return value specifies the required size of the buffer, in characters,
/// including the null-terminating character.
/// </para>
/// </returns>
// DWORD WINAPI GetCurrentDirectory( _In_ DWORD nBufferLength, _Out_ LPTSTR lpBuffer);
// https://msdn.microsoft.com/en-us/library/windows/desktop/aa364934(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)]
[PInvokeData("WinBase.h", MSDNShortId = "aa364934")]
public static extern uint GetCurrentDirectory(uint nBufferLength, StringBuilder lpBuffer);
/// <summary>Searches for a specified file in a specified path.</summary>
/// <param name="lpPath">
/// <para>The path to be searched for the file.</para>
/// <para>
/// If this parameter is <c>NULL</c>, the function searches for a matching file using a registry-dependent system search path. For more information, see
/// the Remarks section.
/// </para>
/// </param>
/// <param name="lpFileName">The name of the file for which to search.</param>
/// <param name="lpExtension">
/// <para>
/// The extension to be added to the file name when searching for the file. The first character of the file name extension must be a period (.). The
/// extension is added only if the specified file name does not end with an extension.
/// </para>
/// <para>If a file name extension is not required or if the file name contains an extension, this parameter can be <c>NULL</c>.</para>
/// </param>
/// <param name="nBufferLength">The size of the buffer that receives the valid path and file name (including the terminating null character), in <c>TCHARs</c>.</param>
/// <param name="lpBuffer">A pointer to the buffer to receive the path and file name of the file found. The string is a null-terminated string.</param>
/// <param name="lpFilePart">
/// A pointer to the variable to receive the address (within lpBuffer) of the last component of the valid path and file name, which is the address of the
/// character immediately following the final backslash (\) in the path.
/// </param>
/// <returns>
/// <para>
/// If the function succeeds, the value returned is the length, in <c>TCHARs</c>, of the string that is copied to the buffer, not including the
/// terminating null character. If the return value is greater than nBufferLength, the value returned is the size of the buffer that is required to hold
/// the path, including the terminating null character.
/// </para>
/// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// DWORD WINAPI SearchPath( _In_opt_ LPCTSTR lpPath, _In_ LPCTSTR lpFileName, _In_opt_ LPCTSTR lpExtension, _In_ DWORD nBufferLength, _Out_ LPTSTR lpBuffer, _Out_opt_ LPTSTR *lpFilePart);
// https://msdn.microsoft.com/en-us/library/windows/desktop/aa365527(v=vs.85).aspx
[PInvokeData("WinBase.h", MSDNShortId = "aa365527")]
[DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)]
public static extern uint SearchPath([In, Optional] string lpPath, [In] string lpFileName, [In, Optional] string lpExtension, uint nBufferLength, StringBuilder lpBuffer, out IntPtr lpFilePart);
/// <summary>Determines whether the current directory should be included in the search path for the specified executable.</summary>
/// <param name="ExeName">The name of the executable file.</param>
/// <returns>If the current directory should be part of the search path, the return value is TRUE. Otherwise, the return value is FALSE.</returns>
// BOOL WINAPI NeedCurrentDirectoryForExePath( _In_ LPCTSTR ExeName);
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms684269(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, CharSet = CharSet.Auto)]
[PInvokeData("WinBase.h", MSDNShortId = "ms684269")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool NeedCurrentDirectoryForExePath(string ExeName);
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,72 @@
using System;
using System.Runtime.InteropServices;
namespace Vanara.PInvoke
{
public static partial class Kernel32
{
/// <summary>Retrieves the processor group affinity of the specified process.</summary>
/// <param name="hProcess">
/// <para>A handle to the process.</para>
/// <para>
/// This handle must have the PROCESS_QUERY_INFORMATION or PROCESS_QUERY_LIMITED_INFORMATION access right. For more information, see Process Security and
/// Access Rights.
/// </para>
/// </param>
/// <param name="GroupCount">
/// On input, specifies the number of elements in GroupArray array. On output, specifies the number of processor groups written to the array. If the
/// array is too small, the function fails with ERROR_INSUFFICIENT_BUFFER and sets the GroupCount parameter to the number of elements required.
/// </param>
/// <param name="GroupArray">
/// An array of processor group numbers. A group number is included in the array if a thread in the process is assigned to a processor in the group.
/// </param>
/// <returns>
/// <para>If the function succeeds, the return value is nonzero.</para>
/// <para>If the function fails, the return value is zero. To get extended error information, use <c>GetLastError</c>.</para>
/// <para>If the error value is ERROR_INSUFFICIENT_BUFFER, the GroupCount parameter contains the required buffer size in number of elements.</para>
/// </returns>
// BOOL GetProcessGroupAffinity( _In_ HANDLE hProcess, _Inout_ PUSHORT GroupCount, _Out_ PUSHORT GroupArray); https://msdn.microsoft.com/en-us/library/windows/desktop/dd405496(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "dd405496")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetProcessGroupAffinity(IntPtr hProcess, ref ushort GroupCount, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] ref ushort[] GroupArray);
/// <summary>Retrieves the processor group affinity of the specified thread.</summary>
/// <param name="hThread">
/// <para>A handle to the thread for which the processor group affinity is desired.</para>
/// <para>
/// The handle must have the THREAD_QUERY_INFORMATION or THREAD_QUERY_LIMITED_INFORMATION access right. For more information, see Thread Security and
/// Access Rights.
/// </para>
/// </param>
/// <param name="GroupAffinity">A pointer to a GROUP_AFFINITY structure to receive the group affinity of the thread.</param>
/// <returns>
/// <para>If the function succeeds, the return value is nonzero.</para>
/// <para>If the function fails, the return value is zero. To get extended error information, use <c>GetLastError</c>.</para>
/// </returns>
// BOOL GetThreadGroupAffinity( _In_ HANDLE hThread, _Out_ PGROUP_AFFINITY GroupAffinity); https://msdn.microsoft.com/en-us/library/windows/desktop/dd405498(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "dd405498")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetThreadGroupAffinity(IntPtr hThread, out GROUP_AFFINITY GroupAffinity);
/// <summary>Sets the processor group affinity for the specified thread.</summary>
/// <param name="hThread">
/// <para>A handle to the thread.</para>
/// <para>The handle must have the THREAD_SET_INFORMATION access right. For more information, see Thread Security and Access Rights.</para>
/// </param>
/// <param name="GroupAffinity">A <c>GROUP_AFFINITY</c> structure that specifies the processor group affinity to be used for the specified thread.</param>
/// <param name="PreviousGroupAffinity">
/// A pointer to a <c>GROUP_AFFINITY</c> structure to receive the thread's previous group affinity. This parameter can be NULL.
/// </param>
/// <returns>
/// <para>If the function succeeds, the return value is nonzero.</para>
/// <para>If the function fails, the return value is zero. To get extended error information, use <c>GetLastError</c>.</para>
/// </returns>
// BOOL SetThreadGroupAffinity( _In_ HANDLE hThread, _In_ const GROUP_AFFINITY *GroupAffinity, _Out_opt_ PGROUP_AFFINITY PreviousGroupAffinity); https://msdn.microsoft.com/en-us/library/windows/desktop/dd405516(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "dd405516")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetThreadGroupAffinity(IntPtr hThread, ref GROUP_AFFINITY GroupAffinity, out GROUP_AFFINITY PreviousGroupAffinity);
}
}

View File

@ -0,0 +1,47 @@
using System.Runtime.InteropServices;
namespace Vanara.PInvoke
{
public static partial class Kernel32
{
/// <summary>
/// Retrieves the current value of the performance counter, which is a high resolution (&lt;1us) time stamp that can be used for time-interval measurements.
/// </summary>
/// <param name="lpPerformanceCount">A pointer to a variable that receives the current performance-counter value, in counts.</param>
/// <returns>
/// <para>If the function succeeds, the return value is nonzero.</para>
/// <para>
/// If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>. On systems that run Windows XP or
/// later, the function will always succeed and will thus never return zero.
/// </para>
/// </returns>
// BOOL WINAPI QueryPerformanceCounter( _Out_ LARGE_INTEGER *lpPerformanceCount);
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms644904(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("Winbase.h", MSDNShortId = "ms644904")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool QueryPerformanceCounter(out long lpPerformanceCount);
/// <summary>
/// Retrieves the frequency of the performance counter. The frequency of the performance counter is fixed at system boot and is consistent across all
/// processors. Therefore, the frequency need only be queried upon application initialization, and the result can be cached.
/// </summary>
/// <param name="lpFrequency">
/// A pointer to a variable that receives the current performance-counter frequency, in counts per second. If the installed hardware doesn't support a
/// high-resolution performance counter, this parameter can be zero (this will not occur on systems that run Windows XP or later).
/// </param>
/// <returns>
/// <para>If the installed hardware supports a high-resolution performance counter, the return value is nonzero.</para>
/// <para>
/// If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>. On systems that run Windows XP or
/// later, the function will always succeed and will thus never return zero.
/// </para>
/// </returns>
// BOOL WINAPI QueryPerformanceFrequency( _Out_ LARGE_INTEGER *lpFrequency);
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms644905(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("Winbase.h", MSDNShortId = "ms644905")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool QueryPerformanceFrequency(out long lpFrequency);
}
}

View File

@ -0,0 +1,236 @@
using System;
using System.Runtime.InteropServices;
namespace Vanara.PInvoke
{
public static partial class Kernel32
{
/// <summary>
/// Converts the specified auxiliary counter value to the corresponding performance counter value; optionally provides the estimated conversion error in
/// nanoseconds due to latencies and maximum possible drift.
/// </summary>
/// <param name="ullAuxiliaryCounterValue">The auxiliary counter value to convert.</param>
/// <param name="lpPerformanceCounterValue">On success, contains the converted performance counter value. Will be undefined if the function fails.</param>
/// <param name="lpConversionError">On success, contains the estimated conversion error, in nanoseconds. Will be undefined if the function fails.</param>
/// <returns>
/// <para>Returns <c>S_OK</c> if the conversion succeeds; otherwise, returns another <c>HRESULT</c> specifying the error.</para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Return value</term>
/// <term>Description</term>
/// </listheader>
/// <item>
/// <term>S_OK</term>
/// <term>The function succeeded.</term>
/// </item>
/// <item>
/// <term>E_NOTIMPL</term>
/// <term>The auxiliary counter is not supported.</term>
/// </item>
/// <item>
/// <term>E_BOUNDS</term>
/// <term>The value to convert is outside the permitted range (+/- 10 seconds from when the called occurred).</term>
/// </item>
/// </list>
/// </para>
/// </returns>
// HRESULT WINAPI ConvertAuxiliaryCounterToPerformanceCounter( _In_ ULONGLONG ullAuxiliaryCounterValue, _Out_ PULONGLONG lpPerformanceCounterValue,
// _Out_opt_ PULONGLONG lpConversionError); https://msdn.microsoft.com/en-us/library/windows/desktop/mt781214(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)]
[PInvokeData("Realtimeapiset.h", MSDNShortId = "mt781214")]
public static extern HRESULT ConvertAuxiliaryCounterToPerformanceCounter(ulong ullAuxiliaryCounterValue, out ulong lpPerformanceCounterValue, out ulong lpConversionError);
/// <summary>
/// Converts the specified performance counter value to the corresponding auxiliary counter value; optionally provides the estimated conversion error in
/// nanoseconds due to latencies and maximum possible drift.
/// </summary>
/// <param name="ullPerformanceCounterValue">The performance counter value to convert.</param>
/// <param name="lpAuxiliaryCounterValue">On success, contains the converted auxiliary counter value. Will be undefined if the function fails.</param>
/// <param name="lpConversionError">On success, contains the estimated conversion error, in nanoseconds. Will be undefined if the function fails.</param>
/// <returns>
/// <para>Returns <c>S_OK</c> if the conversion succeeds; otherwise, returns another <c>HRESULT</c> specifying the error.</para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Return value</term>
/// <term>Description</term>
/// </listheader>
/// <item>
/// <term>S_OK</term>
/// <term>The function succeeded.</term>
/// </item>
/// <item>
/// <term>E_NOTIMPL</term>
/// <term>The auxiliary counter is not supported.</term>
/// </item>
/// <item>
/// <term>E_BOUNDS</term>
/// <term>The value to convert is outside the permitted range (+/- 10 seconds from when the called occurred).</term>
/// </item>
/// <item>
/// <term>E_BOUNDS</term>
/// <term>The value to convert is prior to the last system boot or S3/S4 transition.</term>
/// </item>
/// </list>
/// </para>
/// </returns>
// HRESULT WINAPI ConvertPerformanceCounterToAuxiliaryCounter( _In_ ULONGLONG ullPerformanceCounterValue, _Out_ PULONGLONG lpAuxiliaryCounterValue,
// _Out_opt_ PULONGLONG lpConversionError); https://msdn.microsoft.com/en-us/library/windows/desktop/mt781215(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)]
[PInvokeData("Realtimeapiset.h", MSDNShortId = "mt781215")]
public static extern HRESULT ConvertPerformanceCounterToAuxiliaryCounter(ulong ullPerformanceCounterValue, out ulong lpAuxiliaryCounterValue, out ulong lpConversionError);
/// <summary>Queries the auxiliary counter frequency.</summary>
/// <param name="lpAuxiliaryCounterFrequency">
/// Long pointer to an output buffer that contains the specified auxiliary counter frequency. If the auxiliary counter is not supported, the value in the
/// output buffer will be undefined.
/// </param>
/// <returns>Returns <c>S_OK</c> if the auxiliary counter is supported and <c>E_NOTIMPL</c> if the auxiliary counter is not supported.</returns>
// HRESULT WINAPI QueryAuxiliaryCounterFrequency( _Out_ PULONGLONG lpAuxiliaryCounterFrequency); https://msdn.microsoft.com/en-us/library/windows/desktop/mt781218(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)]
[PInvokeData("Realtimeapiset.h", MSDNShortId = "mt781218")]
public static extern HRESULT QueryAuxiliaryCounterFrequency(out ulong lpAuxiliaryCounterFrequency);
/// <summary>
/// <para>Retrieves the cycle time for the idle thread of each processor in the system.</para>
/// <para>
/// On a system with more than 64 processors, this function retrieves the cycle time for the idle thread of each processor in the processor group to
/// which the calling thread is assigned. Use the <c>QueryIdleProcessorCycleTimeEx</c> function to retrieve the cycle time for the idle thread on each
/// logical processor for a specific processor group.
/// </para>
/// </summary>
/// <param name="BufferLength">
/// <para>
/// On input, specifies the size of the ProcessorIdleCycleTime buffer, in bytes. This buffer is expected to be 8 times the number of processors in the group.
/// </para>
/// <para>
/// On output, specifies the number of elements written to the buffer. If the buffer size is not sufficient, the function fails and this parameter
/// receives the required length of the buffer.
/// </para>
/// </param>
/// <param name="ProcessorIdleCycleTime">
/// The number of CPU clock cycles used by each idle thread. This buffer must be 8 times the number of processors in the system in size.
/// </param>
/// <returns>
/// <para>If the function succeeds, the return value is nonzero.</para>
/// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// BOOL WINAPI QueryIdleProcessorCycleTime( _Inout_ PULONG BufferLength, _Out_ PULONG64 ProcessorIdleCycleTime); https://msdn.microsoft.com/en-us/library/windows/desktop/ms684922(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms684922")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool QueryIdleProcessorCycleTime(ref uint BufferLength, IntPtr ProcessorIdleCycleTime);
/// <summary>Retrieves the accumulated cycle time for the idle thread on each logical processor in the specified processor group.</summary>
/// <param name="Group">The number of the processor group for which to retrieve the cycle time.</param>
/// <param name="BufferLength">
/// <para>
/// On input, specifies the size of the ProcessorIdleCycleTime buffer, in bytes. This buffer is expected to be 8 times the number of processors in the group.
/// </para>
/// <para>
/// On output, specifies the number of elements written to the buffer. If the buffer size is not sufficient, the function fails and this parameter
/// receives the required length of the buffer.
/// </para>
/// </param>
/// <param name="ProcessorIdleCycleTime">
/// The number of CPU clock cycles used by each idle thread. If this parameter is NULL, the function updates the BufferLength parameter with the required length.
/// </param>
/// <returns>
/// <para>If the function succeeds, the return value is nonzero.</para>
/// <para>If the function fails, the return value is zero. To get extended error information, use <c>GetLastError</c>.</para>
/// </returns>
// BOOL QueryIdleProcessorCycleTimeEx( _In_ USHORT Group, _Inout_ PULONG BufferLength, _Out_ PULONG64 ProcessorIdleCycleTime); https://msdn.microsoft.com/en-us/library/windows/desktop/dd405507(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "dd405507")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool QueryIdleProcessorCycleTimeEx(ushort Group, ref uint BufferLength, IntPtr ProcessorIdleCycleTime);
/// <summary>Gets the current interrupt-time count. For a more precise count, use <c>QueryInterruptTimePrecise</c>.</summary>
/// <param name="lpInterruptTime">
/// A pointer to a ULONGLONG in which to receive the interrupt-time count in system time units of 100 nanoseconds. Divide by ten million, or 1e7, to get
/// seconds (there are 1e9 nanoseconds in a second, so there are 1e7 100-nanoseconds in a second).
/// </param>
/// <returns>This function does not return a value.</returns>
// VOID QueryInterruptTime( _Out_ PULONGLONG lpInterruptTime); https://msdn.microsoft.com/en-us/library/windows/desktop/dn903659(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)]
[PInvokeData("Realtimeapiset.h", MSDNShortId = "dn903659")]
public static extern void QueryInterruptTime(out ulong lpInterruptTime);
/// <summary>Gets the current interrupt-time count, in a more precise form than <c>QueryInterruptTime</c> does.</summary>
/// <param name="lpInterruptTimePrecise">
/// A pointer to a ULONGLONG in which to receive the interrupt-time count in system time units of 100 nanoseconds. Divide by ten million, or 1e7, to get
/// seconds (there are 1e9 nanoseconds in a second, so there are 1e7 100-nanoseconds in a second).
/// </param>
/// <returns>This function does not return a value.</returns>
// VOID QueryInterruptTimePrecise( _Out_ PULONGLONG lpInterruptTimePrecise); https://msdn.microsoft.com/en-us/library/windows/desktop/dn903660(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)]
[PInvokeData("Realtimeapiset.h", MSDNShortId = "dn903660")]
public static extern void QueryInterruptTimePrecise(out ulong lpInterruptTimePrecise);
/// <summary>Retrieves the sum of the cycle time of all threads of the specified process.</summary>
/// <param name="ProcessHandle">
/// A handle to the process. The handle must have the PROCESS_QUERY_INFORMATION or PROCESS_QUERY_LIMITED_INFORMATION access right. For more information,
/// see Process Security and Access Rights.
/// </param>
/// <param name="CycleTime">
/// The number of CPU clock cycles used by the threads of the process. This value includes cycles spent in both user mode and kernel mode.
/// </param>
/// <returns>
/// <para>If the function succeeds, the return value is nonzero.</para>
/// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// BOOL WINAPI QueryProcessCycleTime( _In_ HANDLE ProcessHandle, _Out_ PULONG64 CycleTime); https://msdn.microsoft.com/en-us/library/windows/desktop/ms684929(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms684929")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool QueryProcessCycleTime(IntPtr ProcessHandle, out ulong CycleTime);
/// <summary>Retrieves the cycle time for the specified thread.</summary>
/// <param name="ThreadHandle">
/// A handle to the thread. The handle must have the PROCESS_QUERY_INFORMATION or PROCESS_QUERY_LIMITED_INFORMATION access right. For more information,
/// see Process Security and Access Rights.
/// </param>
/// <param name="CycleTime">The number of CPU clock cycles used by the thread. This value includes cycles spent in both user mode and kernel mode.</param>
/// <returns>
/// <para>If the function succeeds, the return value is nonzero.</para>
/// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// BOOL WINAPI QueryThreadCycleTime( _In_ HANDLE ThreadHandle, _Out_ PULONG64 CycleTime); https://msdn.microsoft.com/en-us/library/windows/desktop/ms684943(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms684943")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool QueryThreadCycleTime(IntPtr ThreadHandle, out ulong CycleTime);
/// <summary>
/// Gets the current unbiased interrupt-time count, in units of 100 nanoseconds. The unbiased interrupt-time count does not include time the system
/// spends in sleep or hibernation.
/// </summary>
/// <param name="lpUnbiasedInterruptTime">
/// A pointer to a ULONGLONG in which to receive the unbiased interrupt-time count in system time units of 100 nanoseconds. Divide by ten million, or
/// 1e7, to get seconds (there are 1e9 nanoseconds in a second, so there are 1e7 100-nanoseconds in a second).
/// </param>
/// <returns>
/// If the function succeeds, the return value is nonzero. If the function fails because it is called with a null parameter, the return value is zero.
/// </returns>
// BOOL QueryUnbiasedInterruptTime( _Out_ PULONGLONG lpUnbiasedInterruptTime); https://msdn.microsoft.com/en-us/library/windows/desktop/ee662307(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)]
[PInvokeData("Winbase.h", MSDNShortId = "ee662307")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool QueryUnbiasedInterruptTime(out ulong lpUnbiasedInterruptTime);
/// <summary>
/// Gets the current unbiased interrupt-time count, in a more precise form than <c>QueryUnbiasedInterruptTime</c> does. The unbiased interrupt-time count
/// does not include time the system spends in sleep or hibernation.
/// </summary>
/// <param name="lpUnbiasedInterruptTimePrecise">
/// A pointer to a ULONGLONG in which to receive the unbiased interrupt-time count in system time units of 100 nanoseconds. Divide by ten million, or
/// 1e7, to get seconds (there are 1e9 nanoseconds in a second, so there are 1e7 100-nanoseconds in a second).
/// </param>
/// <returns>This function does not return a value.</returns>
// VOID QueryUnbiasedInterruptTimePrecise( _Out_ PULONGLONG lpUnbiasedInterruptTimePrecise); https://msdn.microsoft.com/en-us/library/windows/desktop/dn891448(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)]
[PInvokeData("Realtimeapiset.h", MSDNShortId = "dn891448")]
public static extern void QueryUnbiasedInterruptTimePrecise(out ulong lpUnbiasedInterruptTimePrecise);
}
}

View File

@ -0,0 +1,31 @@
using System;
using System.Runtime.InteropServices;
using System.Text;
namespace Vanara.PInvoke
{
public static partial class Kernel32
{
/// <summary>
/// The <c>GetAppContainerNamedObjectPath</c> function retrieves the named object path for the app container. Each app container has its own named object path.
/// </summary>
/// <param name="Token">
/// A handle pertaining to the token. If <c>NULL</c> is passed in and no AppContainerSid parameter is passed in, the caller's current process token is
/// used, or the thread token if impersonating.
/// </param>
/// <param name="AppContainerSid">The SID of the app container.</param>
/// <param name="ObjectPathLength">The length of the buffer.</param>
/// <param name="ObjectPath">Buffer that is filled with the named object path.</param>
/// <param name="ReturnLength">Returns the length required to accommodate the length of the named object path.</param>
/// <returns>
/// <para>If the function succeeds, the function returns a value of <c>TRUE</c>.</para>
/// <para>If the function fails, it returns a value of <c>FALSE</c>. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// BOOL GetAppContainerNamedObjectPath( _In_opt_ HANDLE Token, _In_opt_ PSID AppContainerSid, _In_ ULONG ObjectPathLength, _Out_opt_ LPWSTR ObjectPath, _Out_ PULONG ReturnLength);
// https://msdn.microsoft.com/en-us/library/windows/desktop/hh448493(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("Securityappcontainer.h", MSDNShortId = "hh448493")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetAppContainerNamedObjectPath(IntPtr Token, IntPtr AppContainerSid, uint ObjectPathLength, [Out] StringBuilder ObjectPath, out uint ReturnLength);
}
}

View File

@ -0,0 +1,117 @@
using System;
using System.Runtime.InteropServices;
using System.Text;
using Vanara.InteropServices;
using FILETIME = System.Runtime.InteropServices.ComTypes.FILETIME;
namespace Vanara.PInvoke
{
public static partial class Kernel32
{
/* AccessCheck
AccessCheckAndAuditAlarmW
AccessCheckByType
AccessCheckByTypeAndAuditAlarmW
AccessCheckByTypeResultList
AccessCheckByTypeResultListAndAuditAlarmByHandleW
AccessCheckByTypeResultListAndAuditAlarmW
AddAccessAllowedAce
AddAccessAllowedAceEx
AddAccessAllowedObjectAce
AddAccessDeniedAce
AddAccessDeniedAceEx
AddAccessDeniedObjectAce
AddAce
AddAuditAccessAce
AddAuditAccessAceEx
AddAuditAccessObjectAce
AddMandatoryAce
AddResourceAttributeAce
AddScopedPolicyIDAce
AdjustTokenGroups
AdjustTokenPrivileges
AllocateAndInitializeSid
AllocateLocallyUniqueId
AreAllAccessesGranted
AreAnyAccessesGranted
CheckTokenCapability
CheckTokenMembership
CheckTokenMembershipEx
ConvertToAutoInheritPrivateObjectSecurity
CopySid
CreatePrivateObjectSecurity
CreatePrivateObjectSecurityEx
CreatePrivateObjectSecurityWithMultipleInheritance
CreateRestrictedToken
CreateWellKnownSid
CveEventWrite
DeleteAce
DeriveCapabilitySidsFromName
DestroyPrivateObjectSecurity
DuplicateToken
DuplicateTokenEx
EqualDomainSid
EqualPrefixSid
EqualSid
FindFirstFreeAce
FreeSid
GetAce
GetAclInformation
GetAppContainerAce
GetCachedSigningLevel
GetFileSecurityW
GetKernelObjectSecurity
GetLengthSid
GetPrivateObjectSecurity
GetSecurityDescriptorControl
GetSecurityDescriptorDacl
GetSecurityDescriptorGroup
GetSecurityDescriptorLength
GetSecurityDescriptorOwner
GetSecurityDescriptorOwner
GetSecurityDescriptorSacl
GetSidIdentifierAuthority
GetSidLengthRequired
GetSidSubAuthority
GetSidSubAuthorityCount
GetTokenInformation
GetWindowsAccountDomainSid
ImpersonateAnonymousToken
ImpersonateLoggedOnUser
ImpersonateSelf
InitializeAcl
InitializeSecurityDescriptor
InitializeSid
IsTokenRestricted
IsValidAcl
IsValidSecurityDescriptor
IsValidSid
IsWellKnownSid
MakeAbsoluteSD
MakeSelfRelativeSD
MapGenericMask
ObjectCloseAuditAlarmW
ObjectDeleteAuditAlarmW
ObjectOpenAuditAlarmW
ObjectPrivilegeAuditAlarmW
PrivilegeCheck
PrivilegedServiceAuditAlarmW
QuerySecurityAccessMask
RevertToSelf
SetAclInformation
SetCachedSigningLevel
SetFileSecurityW
SetKernelObjectSecurity
SetPrivateObjectSecurity
SetPrivateObjectSecurityEx
SetSecurityAccessMask
SetSecurityDescriptorControl
SetSecurityDescriptorDacl
SetSecurityDescriptorGroup
SetSecurityDescriptorOwner
SetSecurityDescriptorRMControl
SetSecurityDescriptorSacl
SetTokenInformation
*/
}
}

View File

@ -0,0 +1,770 @@
using System;
using System.Runtime.InteropServices;
using System.Text;
namespace Vanara.PInvoke
{
public static partial class Kernel32
{
/// <summary>The system default Windows ANSI code page.</summary>
public const uint CP_ACP = 0;
/// <summary>The current system Macintosh code page.</summary>
public const uint CP_MACCP = 2;
/// <summary>The current system OEM code page.</summary>
public const uint CP_OEMCP = 1;
/// <summary>Symbol code page (42).</summary>
public const uint CP_SYMBOL = 42;
/// <summary>The Windows ANSI code page for the current thread.</summary>
public const uint CP_THREAD_ACP = 3;
/// <summary>UTF-7. Use this value only when forced by a 7-bit transport mechanism. Use of UTF-8 is preferred.</summary>
public const uint CP_UTF7 = 65000;
/// <summary>UTF-8.</summary>
public const uint CP_UTF8 = 65001;
/// <summary>Flags specifying the character type information to retrieve.</summary>
[Flags]
public enum CHAR_TYPE_INFO
{
/// <summary>Retrieve character type information.</summary>
CT_CTYPE1 = 1,
/// <summary>Retrieve bidirectional layout information.</summary>
CT_CTYPE2 = 2,
/// <summary>Retrieve text processing information.</summary>
CT_CTYPE3 = 4,
}
/// <summary>Flags used by CompareString and CompareStringEx</summary>
public enum COMPARE_STRING
{
/// <summary>Ignore case. For many scripts (notably Latin scripts), NORM_IGNORECASE coincides with LINGUISTIC_IGNORECASE.</summary>
NORM_IGNORECASE = 1,
/// <summary>Ignore nonspacing characters. For many scripts (notably Latin scripts), NORM_IGNORENONSPACE coincides with LINGUISTIC_IGNOREDIACRITIC.</summary>
NORM_IGNORENONSPACE = 2,
/// <summary>Ignore symbols and punctuation.</summary>
NORM_IGNORESYMBOLS = 4,
/// <summary>Do not differentiate between hiragana and katakana characters. Corresponding hiragana and katakana characters compare as equal.</summary>
NORM_IGNOREKANATYPE = 65536,
/// <summary>
/// Ignore the difference between half-width and full-width characters, for example, C a t == cat. The full-width form is a formatting distinction used
/// in Chinese and Japanese scripts.
/// </summary>
NORM_IGNOREWIDTH = 131072,
/// <summary>Ignore case, as linguistically appropriate.</summary>
LINGUISTIC_IGNORECASE = 16,
/// <summary>Ignore nonspacing characters, as linguistically appropriate.</summary>
LINGUISTIC_IGNOREDIACRITIC = 32,
/// <summary>
/// Use the default linguistic rules for casing, instead of file system rules. Note that most scenarios for CompareStringEx use this flag. This flag does
/// not have to be used when your application calls CompareStringOrdinal.
/// </summary>
NORM_LINGUISTIC_CASING = 134217728,
/// <summary>Treat punctuation the same as symbols.</summary>
SORT_STRINGSORT = 0x00001000,
/// <summary>Windows 7: Treat digits as numbers during sorting, for example, sort &amp;quot;2&amp;quot; before &amp;quot;10&amp;quot;.</summary>
SORT_DIGITSASNUMBERS = 8
}
/// <summary>Flags indicating the conversion type.</summary>
[Flags]
public enum MBCONV
{
/// <summary>
/// Default; do not use with MB_COMPOSITE. Always use precomposed characters, that is, characters having a single character value for a base or
/// nonspacing character combination. For example, in the character &amp;#232;, the e is the base character and the accent grave mark is the
/// nonspacing character. If a single Unicode code point is defined for a character, the application should use it instead of a separate base
/// character and a nonspacing character. For example, &amp;#196; is represented by the single Unicode code point LATIN CAPITAL LETTER A WITH
/// DIAERESIS (U+00C4).
/// </summary>
MB_PRECOMPOSED = 0x00000001,
/// <summary>
/// Always use decomposed characters, that is, characters in which a base character and one or more nonspacing characters each have distinct code
/// point values. For example, &amp;#196; is represented by A + &amp;#168;: LATIN CAPITAL LETTER A (U+0041) + COMBINING DIAERESIS (U+0308). Note that
/// this flag cannot be used with MB_PRECOMPOSED.
/// </summary>
MB_COMPOSITE = 0x00000002,
/// <summary>Use glyph characters instead of control characters.</summary>
MB_USEGLYPHCHARS = 0x00000004,
/// <summary>
/// Fail if an invalid input character is encountered. Starting with Windows Vista, the function does not drop illegal code points if the application
/// does not set this flag, but instead replaces illegal sequences with U+FFFD (encoded as appropriate for the specified codepage).Windows 2000 with
/// SP4 and later, Windows XP: If this flag is not set, the function silently drops illegal code points. A call to GetLastError returns ERROR_NO_UNICODE_TRANSLATION.
/// </summary>
MB_ERR_INVALID_CHARS = 0x00000008,
}
/// <summary>Flags specifying the type of transformation to use during string mapping.</summary>
[PInvokeData("Winnls.h")]
[Flags]
public enum STRING_MAPPING
{
/// <summary>
/// Fold compatibility zone characters into standard Unicode equivalents. This flag is equivalent to normalization form KD in Windows Vista, if the
/// MAP_COMPOSITE flag is also set. If the composite flag is not set (default), this flag is equivalent to normalization form KC in Windows Vista.
/// </summary>
MAP_FOLDCZONE = 16,
/// <summary>
/// Map accented characters to precomposed characters, in which the accent and base character are combined into a single character value. This flag
/// is equivalent to normalization form C in Windows Vista. This value cannot be combined with MAP_COMPOSITE.
/// </summary>
MAP_PRECOMPOSED = 32,
/// <summary>
/// Map accented characters to decomposed characters, that is, characters in which a base character and one or more nonspacing characters each have
/// distinct code point values. For example, &amp;#196; is represented by A + &amp;#168;: LATIN CAPITAL LETTER A (U+0041) + COMBINING DIAERESIS
/// (U+0308). This flag is equivalent to normalization form D in Windows Vista. Note that this flag cannot be used with MB_PRECOMPOSED.
/// </summary>
MAP_COMPOSITE = 64,
/// <summary>Map all digits to Unicode characters 0 through 9.</summary>
MAP_FOLDDIGITS = 128,
/// <summary>
/// Expand all ligature characters so that they are represented by their two-character equivalent. For example, the ligature
/// &amp;quot;&amp;#230;&amp;quot; (U+00e6) expands to the two characters &amp;quot;a&amp;quot; (U+0061) + &amp;quot;e&amp;quot; (U+0065). This value
/// cannot be combined with MAP_PRECOMPOSED or MAP_COMPOSITE.
/// </summary>
MAP_EXPAND_LIGATURES = 8192,
}
/// <summary>Flags indicating the conversion type.</summary>
[Flags]
public enum WCCONV
{
/// <summary>
/// Convert composite characters, consisting of a base character and a nonspacing character, each with different character values. Translate these
/// characters to precomposed characters, which have a single character value for a base-nonspacing character combination. For example, in the
/// character &amp;#232;, the e is the base character and the accent grave mark is the nonspacing character.Your application can combine
/// WC_COMPOSITECHECK with any one of the following flags, with the default being WC_SEPCHARS. These flags determine the behavior of the function
/// when no precomposed mapping for a base-nonspacing character combination in a Unicode string is available. If none of these flags is supplied, the
/// function behaves as if the WC_SEPCHARS flag is set. For more information, see WC_COMPOSITECHECK and related flags in the Remarks section.
/// </summary>
WC_COMPOSITECHECK = 0x00000200,
/// <summary>Discard nonspacing characters during conversion.</summary>
WC_DISCARDNS = 0x00000010,
/// <summary>Default. Generate separate characters during conversion.</summary>
WC_SEPCHARS = 0x00000020,
/// <summary>Replace exceptions with the default character during conversion.</summary>
WC_DEFAULTCHAR = 0x00000040,
/// <summary>
/// Windows Vista and later: Fail (by returning 0 and setting the last-error code to ERROR_NO_UNICODE_TRANSLATION) if an invalid input character is
/// encountered. You can retrieve the last-error code with a call to GetLastError. If this flag is not set, the function replaces illegal sequences
/// with U+FFFD (encoded as appropriate for the specified codepage) and succeeds by returning the length of the converted string. Note that this flag
/// only applies when CodePage is specified as CP_UTF8 or 54936. It cannot be used with other code page values.
/// </summary>
WC_ERR_INVALID_CHARS = 0x00000080,
/// <summary>
/// Translate any Unicode characters that do not translate directly to multibyte equivalents to the default character specified by lpDefaultChar. In
/// other words, if translating from Unicode to multibyte and back to Unicode again does not yield the same Unicode character, the function uses the
/// default character. This flag can be used by itself or in combination with the other defined flags.For strings that require validation, such as
/// file, resource, and user names, the application should always use the WC_NO_BEST_FIT_CHARS flag. This flag prevents the function from mapping
/// characters to characters that appear similar but have very different semantics. In some cases, the semantic change can be extreme. For example,
/// the symbol for &amp;quot;∞&amp;quot; (infinity) maps to 8 (eight) in some code pages.
/// </summary>
WC_NO_BEST_FIT_CHARS = 0x00000400,
}
/// <summary>Compares two character strings, for a locale specified by identifier.</summary>
/// <param name="Locale">
/// Locale identifier of the locale used for the comparison. You can use the <c>MAKELCID</c> macro to create a locale identifier or use one of the
/// following predefined values.
/// </param>
/// <param name="dwCmpFlags">
/// Flags that indicate how the function compares the two strings. For detailed definitions, see the dwCmpFlags parameter of <c>CompareStringEx</c>.
/// </param>
/// <param name="lpString1">Pointer to the first string to compare.</param>
/// <param name="cchCount1">
/// Length of the string indicated by lpString1, excluding the terminating null character. This value represents bytes for the ANSI version of the
/// function and wide characters for the Unicode version. The application can supply a negative value if the string is null-terminated. In this case, the
/// function determines the length automatically.
/// </param>
/// <param name="lpString2">Pointer to the second string to compare.</param>
/// <param name="cchCount2">
/// Length of the string indicated by lpString2, excluding the terminating null character. This value represents bytes for the ANSI version of the
/// function and wide characters for the Unicode version. The application can supply a negative value if the string is null-terminated. In this case, the
/// function determines the length automatically.
/// </param>
/// <returns>Returns the values described for <c>CompareStringEx</c>.</returns>
// int CompareString( _In_ LCID Locale, _In_ DWORD dwCmpFlags, _In_ LPCTSTR lpString1, _In_ int cchCount1, _In_ LPCTSTR lpString2, _In_ int cchCount2); https://msdn.microsoft.com/en-us/library/windows/desktop/dd317759(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, CharSet = CharSet.Auto)]
[PInvokeData("Winnls.h", MSDNShortId = "dd317759")]
public static extern int CompareString(uint Locale, COMPARE_STRING dwCmpFlags, [In] string lpString1, int cchCount1, [In] string lpString2, int cchCount2);
/// <summary>Compares two Unicode (wide character) strings, for a locale specified by name.</summary>
/// <param name="lpLocaleName">Pointer to a locale name, or one of the following predefined values.</param>
/// <param name="dwCmpFlags">
/// <para>
/// Flags that indicate how the function compares the two strings. By default, these flags are not set. This parameter can specify a combination of any
/// of the following values, or it can be set to 0 to obtain the default behavior.
/// </para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Flag</term>
/// <term>Meaning</term>
/// </listheader>
/// <item>
/// <term>LINGUISTIC_IGNORECASE</term>
/// <term>Ignore case, as linguistically appropriate.</term>
/// </item>
/// <item>
/// <term>LINGUISTIC_IGNOREDIACRITIC</term>
/// <term>Ignore nonspacing characters, as linguistically appropriate.</term>
/// </item>
/// <item>
/// <term>NORM_IGNORECASE</term>
/// <term>Ignore case. For many scripts (notably Latin scripts), NORM_IGNORECASE coincides with LINGUISTIC_IGNORECASE.</term>
/// </item>
/// <item>
/// <term>NORM_IGNOREKANATYPE</term>
/// <term>Do not differentiate between hiragana and katakana characters. Corresponding hiragana and katakana characters compare as equal.</term>
/// </item>
/// <item>
/// <term>NORM_IGNORENONSPACE</term>
/// <term>Ignore nonspacing characters. For many scripts (notably Latin scripts), NORM_IGNORENONSPACE coincides with LINGUISTIC_IGNOREDIACRITIC.</term>
/// </item>
/// <item>
/// <term>NORM_IGNORESYMBOLS</term>
/// <term>Ignore symbols and punctuation.</term>
/// </item>
/// <item>
/// <term>NORM_IGNOREWIDTH</term>
/// <term>
/// Ignore the difference between half-width and full-width characters, for example, C a t == cat. The full-width form is a formatting distinction used
/// in Chinese and Japanese scripts.
/// </term>
/// </item>
/// <item>
/// <term>NORM_LINGUISTIC_CASING</term>
/// <term>
/// Use the default linguistic rules for casing, instead of file system rules. Note that most scenarios for CompareStringEx use this flag. This flag does
/// not have to be used when your application calls CompareStringOrdinal.
/// </term>
/// </item>
/// <item>
/// <term>SORT_DIGITSASNUMBERS</term>
/// <term>Windows 7: Treat digits as numbers during sorting, for example, sort &amp;quot;2&amp;quot; before &amp;quot;10&amp;quot;.</term>
/// </item>
/// <item>
/// <term>SORT_STRINGSORT</term>
/// <term>Treat punctuation the same as symbols.</term>
/// </item>
/// </list>
/// </para>
/// </param>
/// <param name="lpString1">Pointer to the first string to compare.</param>
/// <param name="cchCount1">
/// Length of the string indicated by lpString1, excluding the terminating null character. The application can supply a negative value if the string is
/// null-terminated. In this case, the function determines the length automatically.
/// </param>
/// <param name="lpString2">Pointer to the second string to compare.</param>
/// <param name="cchCount2">
/// Length of the string indicated by lpString2, excluding the terminating null character. The application can supply a negative value if the string is
/// null-terminated. In this case, the function determines the length automatically.
/// </param>
/// <param name="lpVersionInformation">
/// <para>
/// Pointer to an <c>NLSVERSIONINFOEX</c> structure that contains the version information about the relevant NLS capability; usually retrieved from <c>GetNLSVersionEx</c>.
/// </para>
/// <para><c>Windows Vista, Windows 7:</c> Reserved; must set to <c>NULL</c>.</para>
/// </param>
/// <param name="lpReserved">Reserved; must set to <c>NULL</c>.</param>
/// <param name="lParam">Reserved; must be set to 0.</param>
/// <returns>
/// <para>
/// Returns one of the following values if successful. To maintain the C runtime convention of comparing strings, the value 2 can be subtracted from a
/// nonzero return value. Then, the meaning of &lt;0, ==0, and &gt;0 is consistent with the C runtime.
/// </para>
/// <para>
/// The function returns 0 if it does not succeed. To get extended error information, the application can call <c>GetLastError</c>, which can return one
/// of the following error codes:
/// </para>
/// </returns>
// int CompareStringEx( _In_opt_ LPCWSTR lpLocaleName, _In_ DWORD dwCmpFlags, _In_ LPCWSTR lpString1, _In_ int cchCount1, _In_ LPCWSTR lpString2, _In_
// int cchCount2, _In_opt_ LPNLSVERSIONINFO lpVersionInformation, _In_opt_ LPVOID lpReserved, _In_opt_ LPARAM lParam); https://msdn.microsoft.com/en-us/library/windows/desktop/dd317761(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
[PInvokeData("Stringapiset.h", MSDNShortId = "dd317761")]
public static extern int CompareStringEx(string lpLocaleName, COMPARE_STRING dwCmpFlags, string lpString1, int cchCount1, string lpString2, int cchCount2, IntPtr lpVersionInformation, [Optional] IntPtr lpReserved, [Optional] IntPtr lParam);
/// <summary>Compares two Unicode strings to test binary equivalence.</summary>
/// <param name="lpString1">Pointer to the first string to compare.</param>
/// <param name="cchCount1">
/// Length of the string indicated by lpString1. The application supplies -1 if the string is null-terminated. In this case, the function determines the
/// length automatically.
/// </param>
/// <param name="lpString2">Pointer to the second string to compare.</param>
/// <param name="cchCount2">
/// Length of the string indicated by lpString2. The application supplies -1 if the string is null-terminated. In this case, the function determines the
/// length automatically.
/// </param>
/// <param name="bIgnoreCase">
/// <c>TRUE</c> if the function is to perform a case-insensitive comparison, using the operating system uppercase table information. The application sets
/// this parameter to <c>FALSE</c> if the function is to compare the strings exactly as they are passed in.
/// </param>
/// <returns>
/// <para>
/// Returns one of the following values if successful. To maintain the C runtime convention of comparing strings, the value 2 can be subtracted from a
/// nonzero return value. Then, the meaning of &lt;0, ==0, and &gt;0 is consistent with the C runtime.
/// </para>
/// <para>
/// The function returns 0 if it does not succeed. To get extended error information, the application can call <c>GetLastError</c>, which can return one
/// of the following error codes:
/// </para>
/// </returns>
// int CompareStringOrdinal( _In_ LPCWSTR lpString1, _In_ int cchCount1, _In_ LPCWSTR lpString2, _In_ int cchCount2, _In_ BOOL bIgnoreCase); https://msdn.microsoft.com/en-us/library/windows/desktop/dd317762(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
[PInvokeData("Stringapiset.h", MSDNShortId = "dd317762")]
public static extern int CompareStringOrdinal(string lpString1, int cchCount1, string lpString2, int cchCount2, [MarshalAs(UnmanagedType.Bool)] bool bIgnoreCase);
/// <summary>
/// Maps one Unicode string to another, performing the specified transformation. For an overview of the use of the string functions, see Strings.
/// </summary>
/// <param name="dwMapFlags">
/// <para>Flags specifying the type of transformation to use during string mapping. This parameter can be a combination of the following values.</para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Flag</term>
/// <term>Meaning</term>
/// </listheader>
/// <item>
/// <term>MAP_COMPOSITE</term>
/// <term>
/// Map accented characters to decomposed characters, that is, characters in which a base character and one or more nonspacing characters each have
/// distinct code point values. For example, &amp;#196; is represented by A + &amp;#168;: LATIN CAPITAL LETTER A (U+0041) + COMBINING DIAERESIS (U+0308).
/// This flag is equivalent to normalization form D in Windows Vista. Note that this flag cannot be used with MB_PRECOMPOSED.
/// </term>
/// </item>
/// <item>
/// <term>MAP_EXPAND_LIGATURES</term>
/// <term>
/// Expand all ligature characters so that they are represented by their two-character equivalent. For example, the ligature
/// &amp;quot;&amp;#230;&amp;quot; (U+00e6) expands to the two characters &amp;quot;a&amp;quot; (U+0061) + &amp;quot;e&amp;quot; (U+0065). This value
/// cannot be combined with MAP_PRECOMPOSED or MAP_COMPOSITE.
/// </term>
/// </item>
/// <item>
/// <term>MAP_FOLDCZONE</term>
/// <term>
/// Fold compatibility zone characters into standard Unicode equivalents. This flag is equivalent to normalization form KD in Windows Vista, if the
/// MAP_COMPOSITE flag is also set. If the composite flag is not set (default), this flag is equivalent to normalization form KC in Windows Vista.
/// </term>
/// </item>
/// <item>
/// <term>MAP_FOLDDIGITS</term>
/// <term>Map all digits to Unicode characters 0 through 9.</term>
/// </item>
/// <item>
/// <term>MAP_PRECOMPOSED</term>
/// <term>
/// Map accented characters to precomposed characters, in which the accent and base character are combined into a single character value. This flag is
/// equivalent to normalization form C in Windows Vista. This value cannot be combined with MAP_COMPOSITE.
/// </term>
/// </item>
/// </list>
/// </para>
/// </param>
/// <param name="lpSrcStr">Pointer to a source string that the function maps.</param>
/// <param name="cchSrc">
/// Size, in characters, of the source string indicated by lpSrcStr, excluding the terminating null character. The application can set the parameter to
/// any negative value to specify that the source string is null-terminated. In this case, the function calculates the string length automatically, and
/// null-terminates the mapped string indicated by lpDestStr.
/// </param>
/// <param name="lpDestStr">Pointer to a buffer in which this function retrieves the mapped string.</param>
/// <param name="cchDest">
/// <para>
/// Size, in characters, of the destination string indicated by lpDestStr. If space for a terminating null character is included in cchSrc, cchDest must
/// also include space for a terminating null character.
/// </para>
/// <para>
/// The application can set cchDest to 0. In this case, the function does not use the lpDestStr parameter and returns the required buffer size for the
/// mapped string. If the MAP_FOLDDIGITS flag is specified, the return value is the maximum size required, even if the actual number of characters needed
/// is smaller than the maximum size. If the maximum size is not passed, the function fails with ERROR_INSUFFICIENT_BUFFER.
/// </para>
/// </param>
/// <returns>
/// <para>
/// Returns the number of characters in the translated string, including a terminating null character, if successful. If the function succeeds and the
/// value of cchDest is 0, the return value is the size of the buffer required to hold the translated string, including a terminating null character.
/// </para>
/// <para>
/// This function returns 0 if it does not succeed. To get extended error information, the application can call <c>GetLastError</c>, which can return one
/// of the following error codes:
/// </para>
/// </returns>
// int FoldString( _In_ DWORD dwMapFlags, _In_ LPCTSTR lpSrcStr, _In_ int cchSrc, _Out_opt_ LPTSTR lpDestStr, _In_ int cchDest); https://msdn.microsoft.com/en-us/library/windows/desktop/dd318063(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)]
[PInvokeData("Winnls.h", MSDNShortId = "dd318063")]
public static extern int FoldString(STRING_MAPPING dwMapFlags, [In] string lpSrcStr, int cchSrc, [Out] StringBuilder lpDestStr, int cchDest);
/// <summary>
/// Retrieves character type information for the characters in the specified Unicode source string. For each character in the string, the function sets
/// one or more bits in the corresponding 16-bit element of the output array. Each bit identifies a given character type, for example, letter, digit, or neither.
/// </summary>
/// <param name="dwInfoType">
/// <para>
/// Flags specifying the character type information to retrieve. This parameter can have the following values. The character types are divided into
/// different levels as described in the Remarks section.
/// </para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Flag</term>
/// <term>Meaning</term>
/// </listheader>
/// <item>
/// <term>CT_CTYPE1</term>
/// <term>Retrieve character type information.</term>
/// </item>
/// <item>
/// <term>CT_CTYPE2</term>
/// <term>Retrieve bidirectional layout information.</term>
/// </item>
/// <item>
/// <term>CT_CTYPE3</term>
/// <term>Retrieve text processing information.</term>
/// </item>
/// </list>
/// </para>
/// </param>
/// <param name="lpSrcStr">
/// Pointer to the Unicode string for which to retrieve the character types. The string is assumed to be null-terminated if cchSrc is set to any negative value.
/// </param>
/// <param name="cchSrc">
/// Size, in characters, of the string indicated by lpSrcStr. If the size includes a terminating null character, the function retrieves character type
/// information for that character. If the application sets the size to any negative integer, the source string is assumed to be null-terminated and the
/// function calculates the size automatically with an additional character for the null termination.
/// </param>
/// <param name="lpCharType">
/// Pointer to an array of 16-bit values. The length of this array must be large enough to receive one 16-bit value for each character in the source
/// string. If cchSrc is not a negative number, lpCharType should be an array of words with cchSrc elements. If cchSrc is set to a negative number,
/// lpCharType is an array of words with lpSrcStr + 1 elements. When the function returns, this array contains one word corresponding to each character
/// in the source string.
/// </param>
/// <returns>
/// Returns a nonzero value if successful, or 0 otherwise. To get extended error information, the application can call <c>GetLastError</c>, which can
/// return one of the following error codes:
/// </returns>
// BOOL GetStringTypeW( _In_ DWORD dwInfoType, _In_ LPCWSTR lpSrcStr, _In_ int cchSrc, _Out_ LPWORD lpCharType); https://msdn.microsoft.com/en-us/library/windows/desktop/dd318119(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
[PInvokeData("Stringapiset.h", MSDNShortId = "dd318119")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetStringType(CHAR_TYPE_INFO dwInfoType, [In] string lpSrcStr, int cchSrc, out ushort lpCharType);
/// <summary>
/// Retrieves character type information for the characters in the specified source string. For each character in the string, the function sets one or
/// more bits in the corresponding 16-bit element of the output array. Each bit identifies a given character type, for example, letter, digit, or neither.
/// </summary>
/// <param name="Locale">
/// <para>
/// Locale identifier that specifies the locale. This value uniquely defines the ANSI code page. You can use the <c>MAKELCID</c> macro to create a locale
/// identifier or use one of the following predefined values.
/// </para>
/// <para><c>Windows Vista and later:</c> The following custom locale identifiers are also supported.</para>
/// </param>
/// <param name="dwInfoType">
/// Flags specifying the character type information to retrieve. For possible flag values, see the dwInfoType parameter of <c>GetStringTypeW</c>. For
/// detailed information about the character type bits, see Remarks for <c>GetStringTypeW</c>.
/// </param>
/// <param name="lpSrcStr">
/// Pointer to the string for which to retrieve the character types. The string is assumed to be null-terminated if cchSrc is set to any negative value.
/// </param>
/// <param name="cchSrc">
/// Size, in characters, of the string indicated by lpSrcStr. The size refers to bytes for the ANSI version of the function or wide characters for the
/// Unicode version. If the size includes a terminating null character, the function retrieves character type information for that character. If the
/// application sets the size to any negative integer, the source string is assumed to be null-terminated and the function calculates the size
/// automatically with an additional character for the null termination.
/// </param>
/// <param name="lpCharType">
/// Pointer to an array of 16-bit values. The length of this array must be large enough to receive one 16-bit value for each character in the source
/// string. If cchSrc is not a negative number, lpCharType should be an array of words with cchSrc elements. If cchSrc is set to a negative number,
/// lpCharType is an array of words with lpSrcStr + 1 elements. When the function returns, this array contains one word corresponding to each character
/// in the source string.
/// </param>
/// <returns>
/// Returns a nonzero value if successful, or 0 otherwise. To get extended error information, the application can call <c>GetLastError</c>, which can
/// return one of the following error codes:
/// </returns>
// BOOL GetStringTypeEx( _In_ LCID Locale, _In_ DWORD dwInfoType, _In_ LPCTSTR lpSrcStr, _In_ int cchSrc, _Out_ LPWORD lpCharType); https://msdn.microsoft.com/en-us/library/windows/desktop/dd318118(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)]
[PInvokeData("Winnls.h", MSDNShortId = "dd318118")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetStringTypeEx(uint Locale, CHAR_TYPE_INFO dwInfoType, [In] string lpSrcStr, int cchSrc, out ushort lpCharType);
/// <summary>Maps a character string to a UTF-16 (wide character) string. The character string is not necessarily from a multibyte character set.</summary>
/// <param name="CodePage">
/// <para>
/// Code page to use in performing the conversion. This parameter can be set to the value of any code page that is installed or available in the
/// operating system. For a list of code pages, see Code Page Identifiers. Your application can also specify one of the values shown in the following table.
/// </para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Value</term>
/// <term>Meaning</term>
/// </listheader>
/// <item>
/// <term>CP_ACP</term>
/// <term>The system default Windows ANSI code page.</term>
/// </item>
/// <item>
/// <term>CP_MACCP</term>
/// <term>The current system Macintosh code page.</term>
/// </item>
/// <item>
/// <term>CP_OEMCP</term>
/// <term>The current system OEM code page.</term>
/// </item>
/// <item>
/// <term>CP_SYMBOL</term>
/// <term>Symbol code page (42).</term>
/// </item>
/// <item>
/// <term>CP_THREAD_ACP</term>
/// <term>The Windows ANSI code page for the current thread.</term>
/// </item>
/// <item>
/// <term>CP_UTF7</term>
/// <term>UTF-7. Use this value only when forced by a 7-bit transport mechanism. Use of UTF-8 is preferred.</term>
/// </item>
/// <item>
/// <term>CP_UTF8</term>
/// <term>UTF-8.</term>
/// </item>
/// </list>
/// </para>
/// </param>
/// <param name="dwFlags">
/// <para>
/// Flags indicating the conversion type. The application can specify a combination of the following values, with MB_PRECOMPOSED being the default.
/// MB_PRECOMPOSED and MB_COMPOSITE are mutually exclusive. MB_USEGLYPHCHARS and MB_ERR_INVALID_CHARS can be set regardless of the state of the other flags.
/// </para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Value</term>
/// <term>Meaning</term>
/// </listheader>
/// <item>
/// <term>MB_COMPOSITE</term>
/// <term>
/// Always use decomposed characters, that is, characters in which a base character and one or more nonspacing characters each have distinct code point
/// values. For example, &amp;#196; is represented by A + &amp;#168;: LATIN CAPITAL LETTER A (U+0041) + COMBINING DIAERESIS (U+0308). Note that this flag
/// cannot be used with MB_PRECOMPOSED.
/// </term>
/// </item>
/// <item>
/// <term>MB_ERR_INVALID_CHARS</term>
/// <term>
/// Fail if an invalid input character is encountered. Starting with Windows Vista, the function does not drop illegal code points if the application
/// does not set this flag, but instead replaces illegal sequences with U+FFFD (encoded as appropriate for the specified codepage).Windows 2000 with SP4
/// and later, Windows XP: If this flag is not set, the function silently drops illegal code points. A call to GetLastError returns ERROR_NO_UNICODE_TRANSLATION.
/// </term>
/// </item>
/// <item>
/// <term>MB_PRECOMPOSED</term>
/// <term>
/// Default; do not use with MB_COMPOSITE. Always use precomposed characters, that is, characters having a single character value for a base or
/// nonspacing character combination. For example, in the character &amp;#232;, the e is the base character and the accent grave mark is the nonspacing
/// character. If a single Unicode code point is defined for a character, the application should use it instead of a separate base character and a
/// nonspacing character. For example, &amp;#196; is represented by the single Unicode code point LATIN CAPITAL LETTER A WITH DIAERESIS (U+00C4).
/// </term>
/// </item>
/// <item>
/// <term>MB_USEGLYPHCHARS</term>
/// <term>Use glyph characters instead of control characters.</term>
/// </item>
/// </list>
/// </para>
/// <para>For the code pages listed below, dwFlags must be set to 0. Otherwise, the function fails with ERROR_INVALID_FLAGS.</para>
/// </param>
/// <param name="lpMultiByteStr">Pointer to the character string to convert.</param>
/// <param name="cbMultiByte">
/// <para>
/// Size, in bytes, of the string indicated by the lpMultiByteStr parameter. Alternatively, this parameter can be set to -1 if the string is
/// null-terminated. Note that, if cbMultiByte is 0, the function fails.
/// </para>
/// <para>
/// If this parameter is -1, the function processes the entire input string, including the terminating null character. Therefore, the resulting Unicode
/// string has a terminating null character, and the length returned by the function includes this character.
/// </para>
/// <para>
/// If this parameter is set to a positive integer, the function processes exactly the specified number of bytes. If the provided size does not include a
/// terminating null character, the resulting Unicode string is not null-terminated, and the returned length does not include this character.
/// </para>
/// </param>
/// <param name="lpWideCharStr">Pointer to a buffer that receives the converted string.</param>
/// <param name="cchWideChar">
/// Size, in characters, of the buffer indicated by lpWideCharStr. If this value is 0, the function returns the required buffer size, in characters,
/// including any terminating null character, and makes no use of the lpWideCharStr buffer.
/// </param>
/// <returns>
/// <para>
/// Returns the number of characters written to the buffer indicated by lpWideCharStr if successful. If the function succeeds and cchWideChar is 0, the
/// return value is the required size, in characters, for the buffer indicated by lpWideCharStr. Also see dwFlags for info about how the
/// MB_ERR_INVALID_CHARS flag affects the return value when invalid sequences are input.
/// </para>
/// <para>
/// The function returns 0 if it does not succeed. To get extended error information, the application can call <c>GetLastError</c>, which can return one
/// of the following error codes:
/// </para>
/// </returns>
// int MultiByteToWideChar( _In_ UINT CodePage, _In_ DWORD dwFlags, _In_ LPCSTR lpMultiByteStr, _In_ int cbMultiByte, _Out_opt_ LPWSTR lpWideCharStr,
// _In_ int cchWideChar); https://msdn.microsoft.com/en-us/library/windows/desktop/dd319072(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("Stringapiset.h", MSDNShortId = "dd319072")]
public static extern int MultiByteToWideChar(uint CodePage, MBCONV dwFlags, [In] [MarshalAs(UnmanagedType.LPStr)] string lpMultiByteStr, int cbMultiByte,
[Out] [MarshalAs(UnmanagedType.LPWStr)] StringBuilder lpWideCharStr, int cchWideChar);
/// <summary>
/// Maps a UTF-16 (wide character) string to a new character string. The new character string is not necessarily from a multibyte character set.
/// </summary>
/// <param name="CodePage">
/// <para>
/// Code page to use in performing the conversion. This parameter can be set to the value of any code page that is installed or available in the
/// operating system. For a list of code pages, see Code Page Identifiers. Your application can also specify one of the values shown in the following table.
/// </para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Value</term>
/// <term>Meaning</term>
/// </listheader>
/// <item>
/// <term>CP_ACP</term>
/// <term>The system default Windows ANSI code page.</term>
/// </item>
/// <item>
/// <term>CP_MACCP</term>
/// <term>The current system Macintosh code page.</term>
/// </item>
/// <item>
/// <term>CP_OEMCP</term>
/// <term>The current system OEM code page.</term>
/// </item>
/// <item>
/// <term>CP_SYMBOL</term>
/// <term>Windows 2000: Symbol code page (42).</term>
/// </item>
/// <item>
/// <term>CP_THREAD_ACP</term>
/// <term>Windows 2000: The Windows ANSI code page for the current thread.</term>
/// </item>
/// <item>
/// <term>CP_UTF7</term>
/// <term>
/// UTF-7. Use this value only when forced by a 7-bit transport mechanism. Use of UTF-8 is preferred. With this value set, lpDefaultChar and
/// lpUsedDefaultChar must be set to NULL.
/// </term>
/// </item>
/// <item>
/// <term>CP_UTF8</term>
/// <term>UTF-8. With this value set, lpDefaultChar and lpUsedDefaultChar must be set to NULL.</term>
/// </item>
/// </list>
/// </para>
/// </param>
/// <param name="dwFlags">
/// <para>
/// Flags indicating the conversion type. The application can specify a combination of the following values. The function performs more quickly when none
/// of these flags is set. The application should specify WC_NO_BEST_FIT_CHARS and WC_COMPOSITECHECK with the specific value WC_DEFAULTCHAR to retrieve
/// all possible conversion results. If all three values are not provided, some results will be missing.
/// </para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Value</term>
/// <term>Meaning</term>
/// </listheader>
/// <item>
/// <term>WC_COMPOSITECHECK</term>
/// <term>
/// Convert composite characters, consisting of a base character and a nonspacing character, each with different character values. Translate these
/// characters to precomposed characters, which have a single character value for a base-nonspacing character combination. For example, in the character
/// &amp;#232;, the e is the base character and the accent grave mark is the nonspacing character.Your application can combine WC_COMPOSITECHECK with any
/// one of the following flags, with the default being WC_SEPCHARS. These flags determine the behavior of the function when no precomposed mapping for a
/// base-nonspacing character combination in a Unicode string is available. If none of these flags is supplied, the function behaves as if the
/// WC_SEPCHARS flag is set. For more information, see WC_COMPOSITECHECK and related flags in the Remarks section.
/// </term>
/// </item>
/// <item>
/// <term>WC_ERR_INVALID_CHARS</term>
/// <term>
/// Windows Vista and later: Fail (by returning 0 and setting the last-error code to ERROR_NO_UNICODE_TRANSLATION) if an invalid input character is
/// encountered. You can retrieve the last-error code with a call to GetLastError. If this flag is not set, the function replaces illegal sequences with
/// U+FFFD (encoded as appropriate for the specified codepage) and succeeds by returning the length of the converted string. Note that this flag only
/// applies when CodePage is specified as CP_UTF8 or 54936. It cannot be used with other code page values.
/// </term>
/// </item>
/// <item>
/// <term>WC_NO_BEST_FIT_CHARS</term>
/// <term>
/// Translate any Unicode characters that do not translate directly to multibyte equivalents to the default character specified by lpDefaultChar. In
/// other words, if translating from Unicode to multibyte and back to Unicode again does not yield the same Unicode character, the function uses the
/// default character. This flag can be used by itself or in combination with the other defined flags.For strings that require validation, such as file,
/// resource, and user names, the application should always use the WC_NO_BEST_FIT_CHARS flag. This flag prevents the function from mapping characters to
/// characters that appear similar but have very different semantics. In some cases, the semantic change can be extreme. For example, the symbol for
/// &amp;quot;∞&amp;quot; (infinity) maps to 8 (eight) in some code pages.
/// </term>
/// </item>
/// </list>
/// </para>
/// <para>For the code pages listed below, dwFlags must be 0. Otherwise, the function fails with ERROR_INVALID_FLAGS.</para>
/// </param>
/// <param name="lpWideCharStr">Pointer to the Unicode string to convert.</param>
/// <param name="cchWideChar">
/// <para>
/// Size, in characters, of the string indicated by lpWideCharStr. Alternatively, this parameter can be set to -1 if the string is null-terminated. If
/// cchWideChar is set to 0, the function fails.
/// </para>
/// <para>
/// If this parameter is -1, the function processes the entire input string, including the terminating null character. Therefore, the resulting character
/// string has a terminating null character, and the length returned by the function includes this character.
/// </para>
/// <para>
/// If this parameter is set to a positive integer, the function processes exactly the specified number of characters. If the provided size does not
/// include a terminating null character, the resulting character string is not null-terminated, and the returned length does not include this character.
/// </para>
/// </param>
/// <param name="lpMultiByteStr">Pointer to a buffer that receives the converted string.</param>
/// <param name="cbMultiByte">
/// Size, in bytes, of the buffer indicated by lpMultiByteStr. If this parameter is set to 0, the function returns the required buffer size for
/// lpMultiByteStr and makes no use of the output parameter itself.
/// </param>
/// <param name="lpDefaultChar">
/// <para>
/// Pointer to the character to use if a character cannot be represented in the specified code page. The application sets this parameter to <c>NULL</c>
/// if the function is to use a system default value. To obtain the system default character, the application can call the <c>GetCPInfo</c> or
/// <c>GetCPInfoEx</c> function.
/// </para>
/// <para>For the CP_UTF7 and CP_UTF8 settings for CodePage, this parameter must be set to <c>NULL</c>. Otherwise, the function fails with ERROR_INVALID_PARAMETER.</para>
/// </param>
/// <param name="lpUsedDefaultChar">
/// <para>
/// Pointer to a flag that indicates if the function has used a default character in the conversion. The flag is set to <c>TRUE</c> if one or more
/// characters in the source string cannot be represented in the specified code page. Otherwise, the flag is set to <c>FALSE</c>. This parameter can be
/// set to <c>NULL</c>.
/// </para>
/// <para>For the CP_UTF7 and CP_UTF8 settings for CodePage, this parameter must be set to <c>NULL</c>. Otherwise, the function fails with ERROR_INVALID_PARAMETER.</para>
/// </param>
/// <returns>
/// <para>
/// If successful, returns the number of bytes written to the buffer pointed to by lpMultiByteStr. If the function succeeds and cbMultiByte is 0, the
/// return value is the required size, in bytes, for the buffer indicated by lpMultiByteStr. Also see dwFlags for info about how the WC_ERR_INVALID_CHARS
/// flag affects the return value when invalid sequences are input.
/// </para>
/// <para>
/// The function returns 0 if it does not succeed. To get extended error information, the application can call <c>GetLastError</c>, which can return one
/// of the following error codes:
/// </para>
/// </returns>
// int WideCharToMultiByte( _In_ UINT CodePage, _In_ DWORD dwFlags, _In_ LPCWSTR lpWideCharStr, _In_ int cchWideChar, _Out_opt_ LPSTR lpMultiByteStr,
// _In_ int cbMultiByte, _In_opt_ LPCSTR lpDefaultChar, _Out_opt_ LPBOOL lpUsedDefaultChar); https://msdn.microsoft.com/en-us/library/windows/desktop/dd374130(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("Stringapiset.h", MSDNShortId = "dd374130")]
public static extern int WideCharToMultiByte(uint CodePage, WCCONV dwFlags, [In] [MarshalAs(UnmanagedType.LPWStr)] string lpWideCharStr, int cchWideChar,
[Out] [MarshalAs(UnmanagedType.LPStr)] StringBuilder lpMultiByteStr, int cbMultiByte, [In] [MarshalAs(UnmanagedType.LPStr)] string lpDefaultChar, [MarshalAs(UnmanagedType.Bool)] out bool lpUsedDefaultChar);
}
}

2034
PInvoke/Kernel32/SynchApi.cs Normal file

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,68 @@
using System;
using System.Runtime.InteropServices;
namespace Vanara.PInvoke
{
public static partial class Kernel32
{
/// <summary>Retrieves the node that currently has the highest number.</summary>
/// <param name="HighestNodeNumber">The number of the highest node.</param>
/// <returns>
/// <para>If the function succeeds, the return value is nonzero.</para>
/// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// BOOL WINAPI GetNumaHighestNodeNumber( _Out_ PULONG HighestNodeNumber); https://msdn.microsoft.com/en-us/library/windows/desktop/ms683203(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms683203")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetNumaHighestNodeNumber(out uint HighestNodeNumber);
/// <summary>Retrieves the processor mask for a node regardless of the processor group the node belongs to.</summary>
/// <param name="Node">The node number.</param>
/// <param name="ProcessorMask">
/// <para>
/// A pointer to a <c>GROUP_AFFINITY</c> structure that receives the processor mask for the specified node. A processor mask is a bit vector in which
/// each bit represents a processor and whether it is in the node.
/// </para>
/// <para>If the specified node has no processors configured, the <c>Mask</c> member is zero and the <c>Group</c> member is undefined.</para>
/// </param>
/// <returns>
/// <para>If the function succeeds, the return value is nonzero.</para>
/// <para>If the function fails, the return value is zero.</para>
/// </returns>
// BOOL GetNumaNodeProcessorMaskEx( _In_ USHORT Node, _Out_ PGROUP_AFFINITY ProcessorMask); https://msdn.microsoft.com/en-us/library/windows/desktop/dd405493(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "dd405493")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetNumaNodeProcessorMaskEx(ushort Node, out GROUP_AFFINITY ProcessorMask);
/// <summary>Retrieves the NUMA node number that corresponds to the specified proximity identifier as a <c>USHORT</c> value.</summary>
/// <param name="ProximityId">The proximity identifier of the node.</param>
/// <param name="NodeNumber">Points to a variable to receive the node number for the specified proximity identifier.</param>
/// <returns>
/// <para>If the function succeeds, the return value is nonzero.</para>
/// <para>If the function fails, the return value is zero.</para>
/// </returns>
// BOOL GetNumaProximityNodeEx( _In_ ULONG ProximityId, _Out_ PUSHORT NodeNumber); https://msdn.microsoft.com/en-us/library/windows/desktop/dd405495(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "dd405495")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetNumaProximityNodeEx(uint ProximityId, out ushort NodeNumber);
/// <summary>Represents a processor group-specific affinity, such as the affinity of a thread.</summary>
// typedef struct _GROUP_AFFINITY { KAFFINITY Mask; WORD Group; WORD Reserved[3];} GROUP_AFFINITY, *PGROUP_AFFINITY;
// https://msdn.microsoft.com/en-us/library/windows/desktop/dd405500(v=vs.85).aspx
[PInvokeData("WinNT.h", MSDNShortId = "dd405500")]
[StructLayout(LayoutKind.Sequential)]
public struct GROUP_AFFINITY
{
/// <summary>A bitmap that specifies the affinity for zero or more processors within the specified group.</summary>
public UIntPtr Mask;
/// <summary>The processor group number.</summary>
public ushort Group;
/// <summary>This member is reserved.</summary>
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)]
public ushort[] Reserved;
}
}
}

View File

@ -0,0 +1,742 @@
using Microsoft.Win32.SafeHandles;
using System;
using System.Runtime.InteropServices;
using FILETIME = System.Runtime.InteropServices.ComTypes.FILETIME;
namespace Vanara.PInvoke
{
using PTP_CALLBACK_INSTANCE = IntPtr;
using PTP_CLEANUP_GROUP = IntPtr;
using PTP_IO = IntPtr;
using PTP_POOL = IntPtr;
using PTP_TIMER = IntPtr;
using PTP_WAIT = IntPtr;
using PTP_WORK = IntPtr;
public static partial class Kernel32
{
/// <summary>
/// Applications implement this callback if they call the SetThreadpoolCallbackCleanupGroup function to specify the callback to use when CloseThreadpoolCleanupGroup is called.
/// </summary>
/// <param name="ObjectContext">Optional application-defined data specified during creation of the object.</param>
/// <param name="CleanupContext">Optional application-defined data specified using CloseThreadpoolCleanupGroupMembers.</param>
[UnmanagedFunctionPointer(CallingConvention.Winapi)]
public delegate void PTP_CLEANUP_GROUP_CANCEL_CALLBACK(IntPtr ObjectContext, IntPtr CleanupContext);
/// <summary>
/// Applications implement this callback if they call the TrySubmitThreadpoolCallback function to start a worker thread.
/// </summary>
/// <param name="Instance">A TP_CALLBACK_INSTANCE structure that defines the callback instance. Applications do not modify the members of this structure.</param>
/// <param name="Context">The application-defined data.</param>
[UnmanagedFunctionPointer(CallingConvention.Winapi)]
public delegate void PTP_SIMPLE_CALLBACK(PTP_CALLBACK_INSTANCE Instance, IntPtr Context);
/// <summary>Applications implement this callback if they call the SetThreadpoolTimer function to start a worker thread for the timer object.</summary>
/// <param name="Instance">A TP_CALLBACK_INSTANCE structure that defines the callback instance. Applications do not modify the members of this structure.</param>
/// <param name="Context">The application-defined data.</param>
/// <param name="Timer">A TP_TIMER structure that defines the timer object that generated the callback.</param>
[UnmanagedFunctionPointer(CallingConvention.Winapi)]
public delegate void PTP_TIMER_CALLBACK(PTP_CALLBACK_INSTANCE Instance, IntPtr Context, PTP_TIMER Timer);
/// <summary>
/// Applications implement this callback if they call the SetThreadpoolWait function to start a worker thread for the wait object.
/// </summary>
/// <param name="Instance">A TP_CALLBACK_INSTANCE structure that defines the callback instance. Applications do not modify the members of this structure.</param>
/// <param name="Context">The application-defined data.</param>
/// <param name="Wait">A TP_WAIT structure that defines the wait object that generated the callback.</param>
/// <param name="WaitResult">The result of the wait operation. This parameter can be one of the following values from WaitForMultipleObjects: WAIT_OBJECT_0, WAIT_TIMEOUT</param>
[UnmanagedFunctionPointer(CallingConvention.Winapi)]
public delegate void PTP_WAIT_CALLBACK(PTP_CALLBACK_INSTANCE Instance, IntPtr Context, PTP_WAIT Wait, uint WaitResult);
/// <summary>
/// Applications implement this callback if they call the StartThreadpoolIo function to start a worker thread for the I/O completion object.
/// </summary>
/// <param name="Instance">A TP_CALLBACK_INSTANCE structure that defines the callback instance. Applications do not modify the members of this structure.</param>
/// <param name="Context">The application-defined data.</param>
/// <param name="Overlapped">A pointer to a variable that receives the address of the OVERLAPPED structure that was specified when the completed I/O operation was started.</param>
/// <param name="IoResult">The result of the I/O operation. If the I/O is successful, this parameter is NO_ERROR. Otherwise, this parameter is one of the system error codes.</param>
/// <param name="NumberOfBytesTransferred">The number of bytes transferred during the I/O operation that has completed.</param>
/// <param name="Io">A TP_IO structure that defines the I/O completion object that generated the callback.</param>
[UnmanagedFunctionPointer(CallingConvention.Winapi)]
public delegate void PTP_WIN32_IO_CALLBACK(PTP_CALLBACK_INSTANCE Instance, IntPtr Context, IntPtr Overlapped, uint IoResult,
UIntPtr NumberOfBytesTransferred, PTP_IO Io);
/// <summary>
/// Applications implement this callback if they call the SubmitThreadpoolWork function to start a worker thread for the work object.
/// </summary>
/// <param name="Instance">A TP_CALLBACK_INSTANCE structure that defines the callback instance. Applications do not modify the members of this structure.</param>
/// <param name="Context">The application-defined data.</param>
/// <param name="Work">A TP_WORK structure that defines the work object that generated the callback.</param>
[UnmanagedFunctionPointer(CallingConvention.Winapi)]
public delegate void PTP_WORK_CALLBACK(PTP_CALLBACK_INSTANCE Instance, IntPtr Context, PTP_WORK Work);
[Flags]
public enum TP_CALLBACK_ENV_FLAGS
{
None = 0,
LongFunction = 1,
Persistent = 2,
}
/// <summary>The priority for the callback relative to other callbacks in the same thread pool.</summary>
public enum TP_CALLBACK_PRIORITY
{
/// <summary>The callback should run at high priority.</summary>
TP_CALLBACK_PRIORITY_HIGH,
/// <summary>The callback should run at normal priority.</summary>
TP_CALLBACK_PRIORITY_NORMAL,
/// <summary>The callback should run at low priority.</summary>
TP_CALLBACK_PRIORITY_LOW,
/// <summary>The callback is invalid.</summary>
TP_CALLBACK_PRIORITY_INVALID,
}
/// <summary>Indicates that the callback may not return quickly.</summary>
/// <param name="pci">A <c>TP_CALLBACK_INSTANCE</c> structure that defines the callback instance. The structure is passed to the callback function.</param>
/// <returns>
/// <para>
/// The function returns TRUE if another thread in the thread pool is available for processing callbacks or the thread pool was able to spin up a new
/// thread. In this case, the current callback function may use the current thread indefinitely.
/// </para>
/// <para>
/// The function returns FALSE if another thread in the thread pool is not available to process callbacks and the thread pool was not able to spin up a
/// new thread. The thread pool will attempt to spin up a new thread after a delay, but if the current callback function runs long, the thread pool may
/// lose efficiency.
/// </para>
/// </returns>
// BOOL WINAPI CallbackMayRunLong( _Inout_ PTP_CALLBACK_INSTANCE pci); https://msdn.microsoft.com/en-us/library/windows/desktop/ms681981(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms681981")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool CallbackMayRunLong(PTP_CALLBACK_INSTANCE pci);
/// <summary>Cancels the notification from the <c>StartThreadpoolIo</c> function.</summary>
/// <param name="pio">A <c>TP_IO</c> structure that defines the I/O completion object. The <c>CreateThreadpoolIo</c> function returns this structure.</param>
/// <returns>This function does not return a value.</returns>
// VOID WINAPI CancelThreadpoolIo( _Inout_ PTP_IO pio); https://msdn.microsoft.com/en-us/library/windows/desktop/ms681983(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms681983")]
public static extern void CancelThreadpoolIo(PTP_IO pio);
/// <summary>Closes the specified thread pool.</summary>
/// <param name="ptpp">A <c>TP_POOL</c> structure that defines the thread pool. The <c>CreateThreadpool</c> function returns this structure.</param>
/// <returns>This function does not return a value.</returns>
// VOID WINAPI CloseThreadpool( _Inout_ PTP_POOL ptpp); https://msdn.microsoft.com/en-us/library/windows/desktop/ms682030(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms682030")]
public static extern void CloseThreadpool(PTP_POOL ptpp);
/// <summary>Closes the specified cleanup group.</summary>
/// <param name="ptpcg">A <c>TP_CLEANUP_GROUP</c> structure that defines the cleanup group. The <c>CreateThreadpoolCleanupGroup</c> returns this structure.</param>
/// <returns>This function does not return a value.</returns>
// VOID WINAPI CloseThreadpoolCleanupGroup( _Inout_ PTP_CLEANUP_GROUP ptpcg); https://msdn.microsoft.com/en-us/library/windows/desktop/ms682033(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms682033")]
public static extern void CloseThreadpoolCleanupGroup(PTP_CLEANUP_GROUP ptpcg);
/// <summary>
/// Releases the members of the specified cleanup group, waits for all callback functions to complete, and optionally cancels any outstanding callback functions.
/// </summary>
/// <param name="ptpcg">
/// A <c>TP_CLEANUP_GROUP</c> structure that defines the cleanup group. The <c>CreateThreadpoolCleanupGroup</c> function returns this structure.
/// </param>
/// <param name="fCancelPendingCallbacks">
/// If this parameter is TRUE, the function cancels outstanding callbacks that have not yet started. If this parameter is FALSE, the function waits for
/// outstanding callback functions to complete.
/// </param>
/// <param name="pvCleanupContext">
/// The application-defined data to pass to the application's cleanup group callback function. You can specify the callback function when you call <c>SetThreadpoolCallbackCleanupGroup</c>.
/// </param>
/// <returns>This function does not return a value.</returns>
// VOID WINAPI CloseThreadpoolCleanupGroupMembers( _Inout_ PTP_CLEANUP_GROUP ptpcg, _In_ BOOL fCancelPendingCallbacks, _Inout_opt_ PVOID
// pvCleanupContext); https://msdn.microsoft.com/en-us/library/windows/desktop/ms682036(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms682036")]
public static extern void CloseThreadpoolCleanupGroupMembers(PTP_CLEANUP_GROUP ptpcg, [MarshalAs(UnmanagedType.Bool)] bool fCancelPendingCallbacks, IntPtr pvCleanupContext);
/// <summary>Releases the specified I/O completion object.</summary>
/// <param name="pio">A <c>TP_IO</c> structure that defines the I/O completion object. The <c>CreateThreadpoolIo</c> function returns this structure.</param>
/// <returns>This function does not return a value.</returns>
// VOID WINAPI CloseThreadpoolIo( _Inout_ PTP_IO pio); https://msdn.microsoft.com/en-us/library/windows/desktop/ms682038(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms682038")]
public static extern void CloseThreadpoolIo(PTP_IO pio);
/// <summary>Releases the specified timer object.</summary>
/// <param name="pti">A <c>TP_TIMER</c> structure that defines the timer object. The <c>CreateThreadpoolTimer</c> function returns this structure.</param>
/// <returns>This function does not return a value.</returns>
// VOID WINAPI CloseThreadpoolTimer( _Inout_ PTP_TIMER pti); https://msdn.microsoft.com/en-us/library/windows/desktop/ms682040(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms682040")]
public static extern void CloseThreadpoolTimer(PTP_TIMER pti);
/// <summary>Releases the specified wait object.</summary>
/// <param name="pwa">A <c>TP_WAIT</c> structure that defines the wait object. The <c>CreateThreadpoolWait</c> function returns this structure.</param>
/// <returns>This function does not return a value.</returns>
// VOID WINAPI CloseThreadpoolWait( _Inout_ PTP_WAIT pwa); https://msdn.microsoft.com/en-us/library/windows/desktop/ms682042(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms682042")]
public static extern void CloseThreadpoolWait(PTP_WAIT pwa);
/// <summary>Releases the specified work object.</summary>
/// <param name="pwk">A <c>TP_WORK</c> structure that defines the work object. The <c>CreateThreadpoolWork</c> function returns this structure.</param>
/// <returns>This function does not return a value.</returns>
// VOID WINAPI CloseThreadpoolWork( _Inout_ PTP_WORK pwk); https://msdn.microsoft.com/en-us/library/windows/desktop/ms682043(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms682043")]
public static extern void CloseThreadpoolWork(PTP_WORK pwk);
/// <summary>Allocates a new pool of threads to execute callbacks.</summary>
/// <param name="reserved">This parameter is reserved and must be NULL.</param>
/// <returns>
/// <para>
/// If the function succeeds, it returns a <c>TP_POOL</c> structure representing the newly allocated thread pool. Applications do not modify the members
/// of this structure.
/// </para>
/// <para>If function fails, it returns NULL. To retrieve extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// PTP_POOL WINAPI CreateThreadpool( _Reserved_ PVOID reserved); https://msdn.microsoft.com/en-us/library/windows/desktop/ms682456(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms682456")]
public static extern PTP_POOL CreateThreadpool(IntPtr reserved = default(IntPtr));
/// <summary>Creates a cleanup group that applications can use to track one or more thread pool callbacks.</summary>
/// <returns>
/// <para>
/// If the function succeeds, it returns a <c>TP_CLEANUP_GROUP</c> structure of the newly allocated cleanup group. Applications do not modify the members
/// of this structure.
/// </para>
/// <para>If function fails, it returns NULL. To retrieve extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// PTP_CLEANUP_GROUP WINAPI CreateThreadpoolCleanupGroup(void); https://msdn.microsoft.com/en-us/library/windows/desktop/ms682462(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms682462")]
public static extern PTP_CLEANUP_GROUP CreateThreadpoolCleanupGroup();
/// <summary>Creates a new I/O completion object.</summary>
/// <param name="fl">The file handle to bind to this I/O completion object.</param>
/// <param name="pfnio">The callback function to be called each time an overlapped I/O operation completes on the file. For details, see <c>IoCompletionCallback</c>.</param>
/// <param name="pv">Optional application-defined data to pass to the callback function.</param>
/// <param name="pcbe">
/// <para>
/// A <c>TP_CALLBACK_ENVIRON</c> structure that defines the environment in which to execute the callback. The <c>InitializeThreadpoolEnvironment</c>
/// function returns this structure.
/// </para>
/// <para>If this parameter is NULL, the callback executes in the default callback environment. For more information, see <c>InitializeThreadpoolEnvironment</c>.</para>
/// </param>
/// <returns>
/// <para>
/// If the function succeeds, it returns a <c>TP_IO</c> structure that defines the I/O object. Applications do not modify the members of this structure.
/// </para>
/// <para>If the function fails, it returns NULL. To retrieve extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// PTP_IO WINAPI CreateThreadpoolIo( _In_ HANDLE fl, _In_ PTP_WIN32_IO_CALLBACK pfnio, _Inout_opt_ PVOID pv, _In_opt_ PTP_CALLBACK_ENVIRON pcbe); https://msdn.microsoft.com/en-us/library/windows/desktop/ms682464(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms682464")]
public static extern PTP_IO CreateThreadpoolIo(SafeFileHandle fl, PTP_WIN32_IO_CALLBACK pfnio, IntPtr pv, PTP_CALLBACK_ENVIRON pcbe);
/// <summary>Creates a new timer object.</summary>
/// <param name="pfnti">The callback function to call each time the timer object expires. For details, see <c>TimerCallback</c>.</param>
/// <param name="pv">Optional application-defined data to pass to the callback function.</param>
/// <param name="pcbe">
/// <para>
/// A <c>TP_CALLBACK_ENVIRON</c> structure that defines the environment in which to execute the callback. The <c>InitializeThreadpoolEnvironment</c>
/// function returns this structure.
/// </para>
/// <para>If this parameter is NULL, the callback executes in the default callback environment. For more information, see <c>InitializeThreadpoolEnvironment</c>.</para>
/// </param>
/// <returns>
/// <para>
/// If the function succeeds, it returns a <c>TP_TIMER</c> structure that defines the timer object. Applications do not modify the members of this structure.
/// </para>
/// <para>If the function fails, it returns NULL. To retrieve extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// PTP_TIMER WINAPI CreateThreadpoolTimer( _In_ PTP_TIMER_CALLBACK pfnti, _Inout_opt_ PVOID pv, _In_opt_ PTP_CALLBACK_ENVIRON pcbe); https://msdn.microsoft.com/en-us/library/windows/desktop/ms682466(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms682466")]
public static extern PTP_TIMER CreateThreadpoolTimer(PTP_TIMER_CALLBACK pfnti, IntPtr pv, PTP_CALLBACK_ENVIRON pcbe);
/// <summary>Creates a new wait object.</summary>
/// <param name="pfnwa">The callback function to call when the wait completes or times out. For details, see <c>WaitCallback</c>.</param>
/// <param name="pv">Optional application-defined data to pass to the callback function.</param>
/// <param name="pcbe">
/// <para>
/// A <c>TP_CALLBACK_ENVIRON</c> structure that defines the environment in which to execute the callback. The <c>InitializeThreadpoolEnvironment</c>
/// function returns this structure.
/// </para>
/// <para>If this parameter is NULL, the callback executes in the default callback environment. For more information, see <c>InitializeThreadpoolEnvironment</c>.</para>
/// </param>
/// <returns>
/// <para>
/// If the function succeeds, it returns a <c>TP_WAIT</c> structure that defines the wait object. Applications do not modify the members of this structure.
/// </para>
/// <para>If the function fails, it returns NULL. To retrieve extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// PTP_WAIT WINAPI CreateThreadpoolWait( _In_ PTP_WAIT_CALLBACK pfnwa, _Inout_opt_ PVOID pv, _In_opt_ PTP_CALLBACK_ENVIRON pcbe); https://msdn.microsoft.com/en-us/library/windows/desktop/ms682474(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms682474")]
public static extern PTP_WAIT CreateThreadpoolWait(PTP_WAIT_CALLBACK pfnwa, IntPtr pv, PTP_CALLBACK_ENVIRON pcbe);
/// <summary>Creates a new work object.</summary>
/// <param name="pfnwk">
/// The callback function. A worker thread calls this callback each time you call <c>SubmitThreadpoolWork</c> to post the work object. For details, see <c>WorkCallback</c>.
/// </param>
/// <param name="pv">Optional application-defined data to pass to the callback function.</param>
/// <param name="pcbe">
/// <para>
/// A <c>TP_CALLBACK_ENVIRON</c> structure that defines the environment in which to execute the callback. The <c>InitializeThreadpoolEnvironment</c>
/// function returns this structure.
/// </para>
/// <para>If this parameter is NULL, the callback executes in the default callback environment. For more information, see <c>InitializeThreadpoolEnvironment</c>.</para>
/// </param>
/// <returns>
/// <para>
/// If the function succeeds, it returns a <c>TP_WORK</c> structure that defines the work object. Applications do not modify the members of this structure.
/// </para>
/// <para>If the function fails, it returns NULL. To retrieve extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// PTP_WORK WINAPI CreateThreadpoolWork( _In_ PTP_WORK_CALLBACK pfnwk, _Inout_opt_ PVOID pv, _In_opt_ PTP_CALLBACK_ENVIRON pcbe); https://msdn.microsoft.com/en-us/library/windows/desktop/ms682478(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms682478")]
public static extern PTP_WORK CreateThreadpoolWork(PTP_WORK_CALLBACK pfnwk, IntPtr pv, PTP_CALLBACK_ENVIRON pcbe);
/// <summary>
/// Removes the association between the currently executing callback function and the object that initiated the callback. The current thread will no
/// longer count as executing a callback on behalf of the object.
/// </summary>
/// <param name="pci">A <c>TP_CALLBACK_INSTANCE</c> structure that defines the callback instance. The structure is passed to the callback function.</param>
/// <returns>This function does not return a value.</returns>
// VOID WINAPI DisassociateCurrentThreadFromCallback( _Inout_ PTP_CALLBACK_INSTANCE pci); https://msdn.microsoft.com/en-us/library/windows/desktop/ms682581(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms682581")]
public static extern void DisassociateCurrentThreadFromCallback(PTP_CALLBACK_INSTANCE pci);
/// <summary>Specifies the DLL that the thread pool will unload when the current callback completes.</summary>
/// <param name="pci">A <c>TP_CALLBACK_INSTANCE</c> structure that defines the callback instance. The structure is passed to the callback function.</param>
/// <param name="mod">A handle to the DLL.</param>
/// <returns>This function does not return a value.</returns>
// VOID WINAPI FreeLibraryWhenCallbackReturns( _Inout_ PTP_CALLBACK_INSTANCE pci, _In_ HMODULE mod); https://msdn.microsoft.com/en-us/library/windows/desktop/ms683154(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms683154")]
public static extern void FreeLibraryWhenCallbackReturns(PTP_CALLBACK_INSTANCE pci, IntPtr mod);
/// <summary>Initializes a callback environment.</summary>
/// <param name="pcbe">A <c>TP_CALLBACK_ENVIRON</c> structure that defines a callback environment.</param>
/// <returns>This function does not return a value.</returns>
// VOID InitializeThreadpoolEnvironment( _Out_ PTP_CALLBACK_ENVIRON pcbe); https://msdn.microsoft.com/en-us/library/windows/desktop/ms683486(v=vs.85).aspx
[PInvokeData("WinBase.h", MSDNShortId = "ms683486")]
public static void InitializeThreadpoolEnvironment(out PTP_CALLBACK_ENVIRON pcbe) { pcbe = new PTP_CALLBACK_ENVIRON(); }
/// <summary>Determines whether the specified timer object is currently set.</summary>
/// <param name="pti">A <c>TP_TIMER</c> structure that defines the timer object. The <c>CreateThreadpoolTimer</c> function returns this structure.</param>
/// <returns>The return value is TRUE if the timer is set; otherwise, the return value is FALSE.</returns>
// BOOL WINAPI IsThreadpoolTimerSet( _Inout_ PTP_TIMER pti); https://msdn.microsoft.com/en-us/library/windows/desktop/ms684133(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms684133")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool IsThreadpoolTimerSet(PTP_TIMER pti);
/// <summary>Specifies the critical section that the thread pool will release when the current callback completes.</summary>
/// <param name="pci">A <c>TP_CALLBACK_INSTANCE</c> structure that defines the callback instance. The structure is passed to the callback function.</param>
/// <param name="pcs">The critical section.</param>
/// <returns>This function does not return a value.</returns>
// VOID WINAPI LeaveCriticalSectionWhenCallbackReturns( _Inout_ PTP_CALLBACK_INSTANCE pci, _Inout_ PCRITICAL_SECTION pcs); https://msdn.microsoft.com/en-us/library/windows/desktop/ms684171(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms684171")]
public static extern void LeaveCriticalSectionWhenCallbackReturns(PTP_CALLBACK_INSTANCE pci, IntPtr pcs);
/// <summary>Retrieves the stack reserve and commit sizes for threads in the specified thread pool.</summary>
/// <param name="ptpp">A <c>TP_POOL</c> structure that specifies the thread pool. The <c>CreateThreadpool</c> function returns this structure.</param>
/// <param name="ptpsi">A <c>TP_POOL_STACK_INFORMATION</c> structure that receives the stack reserve and commit size.</param>
/// <returns>
/// <para>If the function succeeds, the return value is nonzero.</para>
/// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// BOOL QueryThreadpoolStackInformation( _In_ PTP_POOL ptpp, _Out_ PTP_POOL_STACK_INFORMATION ptpsi); https://msdn.microsoft.com/en-us/library/windows/desktop/dd405508(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "dd405508")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool QueryThreadpoolStackInformation(PTP_POOL ptpp, out TP_POOL_STACK_INFORMATION ptpsi);
/// <summary>Specifies the mutex that the thread pool will release when the current callback completes.</summary>
/// <param name="pci">A <c>TP_CALLBACK_INSTANCE</c> structure that defines the callback instance. The structure is passed to the callback function.</param>
/// <param name="mut">A handle to the mutex.</param>
/// <returns>This function does not return a value.</returns>
// VOID WINAPI ReleaseMutexWhenCallbackReturns( _Inout_ PTP_CALLBACK_INSTANCE pci, _In_ HANDLE mut); https://msdn.microsoft.com/en-us/library/windows/desktop/ms685070(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms685070")]
public static extern void ReleaseMutexWhenCallbackReturns(PTP_CALLBACK_INSTANCE pci, IntPtr mut);
/// <summary>Specifies the semaphore that the thread pool will release when the current callback completes.</summary>
/// <param name="pci">A <c>TP_CALLBACK_INSTANCE</c> structure that defines the callback instance. The structure is passed to the callback function.</param>
/// <param name="sem">A handle to the semaphore.</param>
/// <param name="crel">The amount by which to increment the semaphore object's count.</param>
/// <returns>This function does not return a value.</returns>
// VOID WINAPI ReleaseSemaphoreWhenCallbackReturns( _Inout_ PTP_CALLBACK_INSTANCE pci, _In_ HANDLE sem, _In_ DWORD crel); https://msdn.microsoft.com/en-us/library/windows/desktop/ms685073(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms685073")]
public static extern void ReleaseSemaphoreWhenCallbackReturns(PTP_CALLBACK_INSTANCE pci, IntPtr sem, uint crel);
/// <summary>Specifies the event that the thread pool will set when the current callback completes.</summary>
/// <param name="pci">A <c>TP_CALLBACK_INSTANCE</c> structure that defines the callback instance. The structure is passed to the callback function.</param>
/// <param name="evt">A handle to the event to be set.</param>
/// <returns>This function does not return a value.</returns>
// VOID WINAPI SetEventWhenCallbackReturns( _Inout_ PTP_CALLBACK_INSTANCE pci, _In_ HANDLE evt); https://msdn.microsoft.com/en-us/library/windows/desktop/ms686214(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms686214")]
public static extern void SetEventWhenCallbackReturns(PTP_CALLBACK_INSTANCE pci, IntPtr evt);
/// <summary>Associates the specified cleanup group with the specified callback environment.</summary>
/// <param name="pcbe">
/// A <c>TP_CALLBACK_ENVIRON</c> structure that defines the callback environment. The <c>InitializeThreadpoolEnvironment</c> function returns this structure.
/// </param>
/// <param name="ptpcg">
/// A <c>TP_CLEANUP_GROUP</c> structure that defines the cleanup group. The <c>CreateThreadpoolCleanupGroup</c> function returns this structure.
/// </param>
/// <param name="pfng">
/// The cleanup callback to be called if the cleanup group is canceled before the associated object is released. The function is called when you call <c>CloseThreadpoolCleanupGroupMembers</c>.
/// </param>
/// <returns>This function does not return a value.</returns>
// VOID SetThreadpoolCallbackCleanupGroup( _Inout_ PTP_CALLBACK_ENVIRON pcbe, _In_ PTP_CLEANUP_GROUP ptpcg, _In_opt_ PTP_CLEANUP_GROUP_CANCEL_CALLBACK pfng);
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms686255(v=vs.85).aspx
[PInvokeData("WinBase.h", MSDNShortId = "ms686255")]
public static void SetThreadpoolCallbackCleanupGroup(this PTP_CALLBACK_ENVIRON pcbe, PTP_CLEANUP_GROUP ptpcg, PTP_CLEANUP_GROUP_CANCEL_CALLBACK pfng)
{
pcbe.CleanupGroup = ptpcg;
pcbe.CleanupGroupCancelCallback = pfng;
}
/// <summary>Ensures that the specified DLL remains loaded as long as there are outstanding callbacks.</summary>
/// <param name="pcbe">
/// A <c>TP_CALLBACK_ENVIRON</c> structure that defines the callback environment. The <c>InitializeThreadpoolEnvironment</c> function returns this structure.
/// </param>
/// <param name="mod">A handle to the DLL.</param>
/// <returns>This function does not return a value.</returns>
// VOID SetThreadpoolCallbackLibrary( _Inout_ PTP_CALLBACK_ENVIRON pcbe, _In_ PVOID mod);
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms686258(v=vs.85).aspx
[PInvokeData("WinBase.h", MSDNShortId = "ms686258")]
public static void SetThreadpoolCallbackLibrary(this PTP_CALLBACK_ENVIRON pcbe, IntPtr mod) { pcbe.RaceDll = mod; }
/// <summary>Specifies that the callback should run on a persistent thread.</summary>
/// <param name="pcbe">
/// A <c>TP_CALLBACK_ENVIRON</c> structure that defines the callback environment. The <c>InitializeThreadpoolEnvironment</c> function returns this structure.
/// </param>
/// <returns>This function does not return a value.</returns>
// VOID SetThreadpoolCallbackPersistent( _Inout_ PTP_CALLBACK_ENVIRON pcbe);
// https://msdn.microsoft.com/en-us/library/windows/desktop/dd405518(v=vs.85).aspx
[PInvokeData("WinBase.h", MSDNShortId = "dd405518")]
public static void SetThreadpoolCallbackPersistent(this PTP_CALLBACK_ENVIRON pcbe) { pcbe.Flags |= TP_CALLBACK_ENV_FLAGS.Persistent; }
/// <summary>Sets the thread pool to be used when generating callbacks.</summary>
/// <param name="pcbe">
/// A <c>TP_CALLBACK_ENVIRON</c> structure that defines the callback environment. The <c>InitializeThreadpoolEnvironment</c> function returns this structure.
/// </param>
/// <param name="ptpp">A <c>TP_POOL</c> structure that defines the thread pool. The <c>CreateThreadpool</c> function returns this structure.</param>
/// <returns>This function does not return a value.</returns>
// VOID SetThreadpoolCallbackPool( _Inout_ PTP_CALLBACK_ENVIRON pcbe, _In_ PTP_POOL ptpp);
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms686261(v=vs.85).aspx
[PInvokeData("WinBase.h", MSDNShortId = "ms686261")]
public static void SetThreadpoolCallbackPool(this PTP_CALLBACK_ENVIRON pcbe, PTP_POOL ptpp) { pcbe.Pool = ptpp; }
/// <summary>Specifies the priority of a callback function relative to other work items in the same thread pool.</summary><param name="pcbe">A <c>TP_CALLBACK_ENVIRON</c> structure that defines the callback environment. The <c>InitializeThreadpoolEnvironment</c> function returns this structure.</param><param name="Priority"><para>The priority for the callback relative to other callbacks in the same thread pool. This parameter can be one of the following <c>TP_CALLBACK_PRIORITY</c> enumeration values:</para><para><list type="table"><listheader><term>Value</term><term>Meaning</term></listheader><item><term>TP_CALLBACK_PRIORITY_HIGH</term><term>The callback should run at high priority. </term></item><item><term>TP_CALLBACK_PRIORITY_LOW</term><term>The callback should run at low priority.</term></item><item><term>TP_CALLBACK_PRIORITY_NORMAL</term><term>The callback should run at normal priority.</term></item></list></para></param><returns>This function does not return a value.</returns>
// VOID SetThreadpoolCallbackPriority( _Inout_ PTP_CALLBACK_ENVIRON pcbe, _In_ TP_CALLBACK_PRIORITY Priority);
// https://msdn.microsoft.com/en-us/library/windows/desktop/dd405519(v=vs.85).aspx
[PInvokeData("WinBase.h", MSDNShortId = "dd405519")]
public static void SetThreadpoolCallbackPriority(this PTP_CALLBACK_ENVIRON pcbe, TP_CALLBACK_PRIORITY Priority) { pcbe.CallbackPriority = Priority; }
/// <summary>Indicates that callbacks associated with this callback environment may not return quickly.</summary><param name="pcbe">A <c>TP_CALLBACK_ENVIRON</c> structure that defines the callback environment. The <c>InitializeThreadpoolEnvironment</c> function returns this structure.</param><returns>This function does not return a value.</returns>
// VOID SetThreadpoolCallbackRunsLong( _Inout_ PTP_CALLBACK_ENVIRON pcbe);
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms686263(v=vs.85).aspx
[PInvokeData("WinBase.h", MSDNShortId = "ms686263")]
public static void SetThreadpoolCallbackRunsLong(this PTP_CALLBACK_ENVIRON pcbe) { pcbe.Flags |= TP_CALLBACK_ENV_FLAGS.LongFunction; }
/// <summary>
/// Sets the stack reserve and commit sizes for new threads in the specified thread pool. Stack reserve and commit sizes for existing threads are not changed.
/// </summary>
/// <param name="ptpp">A <c>TP_POOL</c> structure that specifies the thread pool. The <c>CreateThreadpool</c> function returns this structure.</param>
/// <param name="ptpsi">A <c>TP_POOL_STACK_INFORMATION</c> structure that specifies the stack reserve and commit size for threads in the pool.</param>
/// <returns>
/// <para>If the function succeeds, the return value is nonzero.</para>
/// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// BOOL SetThreadpoolStackInformation( _Inout_ PTP_POOL ptpp, _In_ PTP_POOL_STACK_INFORMATION ptpsi); https://msdn.microsoft.com/en-us/library/windows/desktop/dd405520(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "dd405520")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetThreadpoolStackInformation(PTP_POOL ptpp, ref TP_POOL_STACK_INFORMATION ptpsi);
/// <summary>Sets the maximum number of threads that the specified thread pool can allocate to process callbacks.</summary>
/// <param name="ptpp">A <c>TP_POOL</c> structure that defines the thread pool. The <c>CreateThreadpool</c> function returns this structure.</param>
/// <param name="cthrdMost">The maximum number of threads.</param>
/// <returns>This function does not return a value.</returns>
// VOID WINAPI SetThreadpoolThreadMaximum( _Inout_ PTP_POOL ptpp, _In_ DWORD cthrdMost); https://msdn.microsoft.com/en-us/library/windows/desktop/ms686266(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms686266")]
public static extern void SetThreadpoolThreadMaximum(PTP_POOL ptpp, uint cthrdMost);
/// <summary>Sets the minimum number of threads that the specified thread pool must make available to process callbacks.</summary>
/// <param name="ptpp">A <c>TP_POOL</c> structure that defines the thread pool. The <c>CreateThreadpool</c> function returns this structure.</param>
/// <param name="cthrdMic">The minimum number of threads.</param>
/// <returns>
/// <para>If the function succeeds, it returns TRUE.</para>
/// <para>If the function fails, it returns FALSE. To retrieve extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// BOOL WINAPI SetThreadpoolThreadMinimum( _Inout_ PTP_POOL ptpp, _In_ DWORD cthrdMic); https://msdn.microsoft.com/en-us/library/windows/desktop/ms686268(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms686268")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetThreadpoolThreadMinimum(PTP_POOL ptpp, uint cthrdMic);
/// <summary>
/// Sets the timer object—, replacing the previous timer, if any. A worker thread calls the timer object's callback after the specified timeout expires.
/// </summary>
/// <param name="pti">
/// A pointer to a <c>TP_TIMER</c> structure that defines the timer object to set. The <c>CreateThreadpoolTimer</c> function returns this structure.
/// </param>
/// <param name="pftDueTime">
/// <para>
/// A pointer to a <c>FILETIME</c> structure that specifies the absolute or relative time at which the timer should expire. If positive or zero, it
/// indicates the absolute time since January 1, 1601 (UTC), measured in 100 nanosecond units. If negative, it indicates the amount of time to wait
/// relative to the current time. For more information about time values, see File Times.
/// </para>
/// <para>
/// If this parameter is NULL, the timer object will cease to queue new callbacks (but callbacks already queued will still occur). Note that if this
/// parameter is zero, the timer will expire immediately.
/// </para>
/// </param>
/// <param name="msPeriod">
/// The timer period, in milliseconds. If this parameter is zero, the timer is signaled once. If this parameter is greater than zero, the timer is
/// periodic. A periodic timer automatically reactivates each time the period elapses, until the timer is canceled.
/// </param>
/// <param name="msWindowLength">
/// The maximum amount of time the system can delay before calling the timer callback. If this parameter is set, the system can batch calls to conserve power.
/// </param>
/// <returns>This function does not return a value.</returns>
// VOID WINAPI SetThreadpoolTimer( _Inout_ PTP_TIMER pti, _In_opt_ PFILETIME pftDueTime, _In_ DWORD msPeriod, _In_opt_ DWORD msWindowLength); https://msdn.microsoft.com/en-us/library/windows/desktop/ms686271(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms686271")]
public static extern void SetThreadpoolTimer(PTP_TIMER pti, ref FILETIME pftDueTime, uint msPeriod, uint msWindowLength);
/// <summary>
/// Sets the timer object—, replacing the previous timer, if any. A worker thread calls the timer object's callback after the specified timeout expires.
/// </summary>
/// <param name="pti">
/// A pointer to a <c>TP_TIMER</c> structure that defines the timer object to set. The <c>CreateThreadpoolTimer</c> function returns this structure.
/// </param>
/// <param name="pftDueTime">
/// <para>
/// A pointer to a <c>FILETIME</c> structure that specifies the absolute or relative time at which the timer should expire. If positive or zero, it
/// indicates the absolute time since January 1, 1601 (UTC), measured in 100 nanosecond units. If negative, it indicates the amount of time to wait
/// relative to the current time. For more information about time values, see File Times.
/// </para>
/// <para>
/// If this parameter is NULL, the timer object will cease to queue new callbacks (but callbacks already queued will still occur). Note that if this
/// parameter is zero, the timer will expire immediately.
/// </para>
/// </param>
/// <param name="msPeriod">
/// The timer period, in milliseconds. If this parameter is zero, the timer is signaled once. If this parameter is greater than zero, the timer is
/// periodic. A periodic timer automatically reactivates each time the period elapses, until the timer is canceled.
/// </param>
/// <param name="msWindowLength">
/// The maximum amount of time the system can delay before calling the timer callback. If this parameter is set, the system can batch calls to conserve power.
/// </param>
/// <returns>
/// If the timer was previously active and was canceled, a value of TRUE is returned. Otherwise a value of FALSE is returned. If FALSE is returned, a
/// callback may be in progress or about to commence. If this is the case, a subsequent SetThreadpoolTimerEx operation will be properly synchronized with
/// completion of the timer callback.
/// </returns>
// https://msdn.microsoft.com/en-us/library/windows/desktop/dn894018(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)]
[PInvokeData("Threadpoolapiset.h", MSDNShortId = "dn894018")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetThreadpoolTimerEx(PTP_TIMER pti, ref FILETIME pftDueTime, uint msPeriod, uint msWindowLength);
/// <summary>
/// Sets the wait object—replacing the previous wait object, if any. A worker thread calls the wait object's callback function after the handle becomes
/// signaled or after the specified timeout expires.
/// </summary>
/// <param name="pwa">A pointer to a <c>TP_WAIT</c> structure that defines the wait object. The <c>CreateThreadpoolWait</c> function returns this structure.</param>
/// <param name="h">
/// <para>A handle.</para>
/// <para>If this parameter is NULL, the wait object will cease to queue new callbacks (but callbacks already queued will still occur).</para>
/// <para>If this parameter is not NULL, it must refer to a valid waitable object.</para>
/// <para>
/// If this handle is closed while the wait is still pending, the function's behavior is undefined. If the wait is still pending and the handle must be
/// closed, use <c>CloseThreadpoolWait</c> to cancel the wait and then close the handle.
/// </para>
/// </param>
/// <param name="pftTimeout">
/// <para>
/// A pointer to a <c>FILETIME</c> structure that specifies the absolute or relative time at which the wait operation should time out. If this parameter
/// points to a positive value, it indicates the absolute time since January 1, 1601 (UTC), in 100-nanosecond intervals. If this parameter points to a
/// negative value, it indicates the amount of time to wait relative to the current time. For more information about time values, see File Times.
/// </para>
/// <para>If this parameter points to 0, the wait times out immediately. If this parameter is NULL, the wait will not time out.</para>
/// </param>
/// <returns>This function does not return a value.</returns>
// VOID WINAPI SetThreadpoolWait( _Inout_ PTP_WAIT pwa, _In_opt_ HANDLE h, _In_opt_ PFILETIME pftTimeout); https://msdn.microsoft.com/en-us/library/windows/desktop/ms686273(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms686273")]
public static extern void SetThreadpoolWait(PTP_WAIT pwa, IntPtr h, ref FILETIME pftTimeout);
/// <summary>
/// Sets the wait object—replacing the previous wait object, if any. A worker thread calls the wait object's callback function after the handle becomes
/// signaled or after the specified timeout expires.
/// </summary>
/// <param name="pwa">A pointer to a <c>TP_WAIT</c> structure that defines the wait object. The <c>CreateThreadpoolWait</c> function returns this structure.</param>
/// <param name="h">
/// <para>A handle.</para>
/// <para>If this parameter is NULL, the wait object will cease to queue new callbacks (but callbacks already queued will still occur).</para>
/// <para>If this parameter is not NULL, it must refer to a valid waitable object.</para>
/// <para>
/// If this handle is closed while the wait is still pending, the function's behavior is undefined. If the wait is still pending and the handle must be
/// closed, use <c>CloseThreadpoolWait</c> to cancel the wait and then close the handle.
/// </para>
/// </param>
/// <param name="pftTimeout">
/// A pointer to a <c>FILETIME</c> structure that specifies the absolute or relative time at which the wait operation should time out. If this parameter
/// points to a positive value, it indicates the absolute time since January 1, 1601 (UTC), in 100-nanosecond intervals. If this parameter points to a
/// negative value, it indicates the amount of time to wait relative to the current time. For more information about time values, see File Times.
/// </param>
/// <param name="Reserved">Reserved.</param>
/// <returns>
/// TRUE, if the timer was previously active and was canceled; otherwise, FALSE. This return value can be used to maintain reference counts to
/// synchronize between completion and cancellation of a non-periodic timer operation. If FALSE is returned, a callback may be in progress or about to
/// commence. If FALSE is returned, a subsequent <c>WaitForThreadpool</c> or <c>WaitForThreadpoolEx</c> Callback operation will complete after that
/// callback is completed. A subsequent <c>SetThreadpool</c> or <c>SetThreadpoolEx</c> operation that is not later canceled will result in an additional callback.”
/// </returns>
// BOOL WINAPI SetThreadpoolWaitEx( _Inout_ PTP_WAIT pwa, _In_opt_ HANDLE h, _In_opt_ PFILETIME pftTimeout, _Reserved_ PVOID Reserved); https://msdn.microsoft.com/en-us/library/windows/desktop/mt186618(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)]
[PInvokeData("Threadpoolapiset.h", MSDNShortId = "mt186618")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetThreadpoolWaitEx(PTP_WAIT pwa, IntPtr h, ref FILETIME pftTimeout, IntPtr Reserved);
/// <summary>
/// Notifies the thread pool that I/O operations may possibly begin for the specified I/O completion object. A worker thread calls the I/O completion
/// object's callback function after the operation completes on the file handle bound to this object.
/// </summary>
/// <param name="pio">A <c>TP_IO</c> structure that defines the I/O completion object. The <c>CreateThreadpoolIo</c> function returns this structure.</param>
/// <returns>This function does not return a value.</returns>
// VOID WINAPI StartThreadpoolIo( _Inout_ PTP_IO pio); https://msdn.microsoft.com/en-us/library/windows/desktop/ms686326(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms686326")]
public static extern void StartThreadpoolIo(PTP_IO pio);
/// <summary>Posts a work object to the thread pool. A worker thread calls the work object's callback function.</summary>
/// <param name="pwk">A <c>TP_WORK</c> structure that defines the work object. The <c>CreateThreadpoolWork</c> function returns this structure.</param>
/// <returns>This function does not return a value.</returns>
// VOID WINAPI SubmitThreadpoolWork( _Inout_ PTP_WORK pwk); https://msdn.microsoft.com/en-us/library/windows/desktop/ms686338(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms686338")]
public static extern void SubmitThreadpoolWork(PTP_WORK pwk);
/// <summary>Requests that a thread pool worker thread call the specified callback function.</summary>
/// <param name="pfns">The callback function. For details, see <c>SimpleCallback</c>.</param>
/// <param name="pv">Optional application-defined data to pass to the callback function.</param>
/// <param name="pcbe">
/// <para>
/// A <c>TP_CALLBACK_ENVIRON</c> structure that defines the environment in which to execute the callback function. The
/// <c>InitializeThreadpoolEnvironment</c> function returns this structure.
/// </para>
/// <para>If this parameter is NULL, the callback executes in the default callback environment. For more information, see <c>InitializeThreadpoolEnvironment</c>.</para>
/// </param>
/// <returns>
/// <para>If the function succeeds, it returns TRUE.</para>
/// <para>If the function fails, it returns FALSE. To retrieve extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// BOOL WINAPI TrySubmitThreadpoolCallback( _In_ PTP_SIMPLE_CALLBACK pfns, _Inout_opt_ PVOID pv, _In_opt_ PTP_CALLBACK_ENVIRON pcbe); https://msdn.microsoft.com/en-us/library/windows/desktop/ms686862(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms686862")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool TrySubmitThreadpoolCallback(PTP_SIMPLE_CALLBACK pfns, IntPtr pv, PTP_CALLBACK_ENVIRON pcbe);
/// <summary>Waits for outstanding I/O completion callbacks to complete and optionally cancels pending callbacks that have not yet started to execute.</summary>
/// <param name="pio">A <c>TP_IO</c> structure that defines the I/O completion object. The <c>CreateThreadpoolIo</c> function returns this structure.</param>
/// <param name="fCancelPendingCallbacks">Indicates whether to cancel queued callbacks that have not yet started to execute.</param>
/// <returns>This function does not return a value.</returns>
// VOID WINAPI WaitForThreadpoolIoCallbacks( _Inout_ PTP_IO pio, _In_ BOOL fCancelPendingCallbacks); https://msdn.microsoft.com/en-us/library/windows/desktop/ms687038(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms687038")]
public static extern void WaitForThreadpoolIoCallbacks(PTP_IO pio, [MarshalAs(UnmanagedType.Bool)] bool fCancelPendingCallbacks);
/// <summary>Waits for outstanding timer callbacks to complete and optionally cancels pending callbacks that have not yet started to execute.</summary>
/// <param name="pti">
/// A <c>TP_TIMER</c> structure that defines the timer object. The <c>CreateThreadpoolTimer</c> function returns the <c>TP_TIMER</c> structure.
/// </param>
/// <param name="fCancelPendingCallbacks">Indicates whether to cancel queued callbacks that have not yet started to execute.</param>
/// <returns>This function does not return a value.</returns>
// VOID WINAPI WaitForThreadpoolTimerCallbacks( _Inout_ PTP_TIMER pti, _In_ BOOL fCancelPendingCallbacks); https://msdn.microsoft.com/en-us/library/windows/desktop/ms687042(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms687042")]
public static extern void WaitForThreadpoolTimerCallbacks(PTP_TIMER pti, [MarshalAs(UnmanagedType.Bool)] bool fCancelPendingCallbacks);
/// <summary>Waits for outstanding wait callbacks to complete and optionally cancels pending callbacks that have not yet started to execute.</summary>
/// <param name="pwa">
/// A <c>TP_WAIT</c> structure that defines the wait object. The <c>CreateThreadpoolWait</c> function returns the <c>TP_WAIT</c> structure.
/// </param>
/// <param name="fCancelPendingCallbacks">Indicates whether to cancel queued callbacks that have not yet started to execute.</param>
/// <returns>This function does not return a value.</returns>
// VOID WINAPI WaitForThreadpoolWaitCallbacks( _Inout_ PTP_WAIT pwa, _In_ BOOL fCancelPendingCallbacks); https://msdn.microsoft.com/en-us/library/windows/desktop/ms687047(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms687047")]
public static extern void WaitForThreadpoolWaitCallbacks(PTP_WAIT pwa, [MarshalAs(UnmanagedType.Bool)] bool fCancelPendingCallbacks);
/// <summary>Waits for outstanding work callbacks to complete and optionally cancels pending callbacks that have not yet started to execute.</summary>
/// <param name="pwk">A <c>TP_WORK</c> structure that defines the work object. The <c>CreateThreadpoolWork</c> function returns this structure.</param>
/// <param name="fCancelPendingCallbacks">Indicates whether to cancel queued callbacks that have not yet started to execute.</param>
/// <returns>This function does not return a value.</returns>
// VOID WINAPI WaitForThreadpoolWorkCallbacks( _Inout_ PTP_WORK pwk, _In_ BOOL fCancelPendingCallbacks); https://msdn.microsoft.com/en-us/library/windows/desktop/ms687053(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms687053")]
public static extern void WaitForThreadpoolWorkCallbacks(PTP_WORK pwk, [MarshalAs(UnmanagedType.Bool)] bool fCancelPendingCallbacks);
/// <summary>Used to set the stack reserve and commit sizes for new threads in a thread pool.</summary>
[PInvokeData("threadpoolapiset.h")]
[StructLayout(LayoutKind.Sequential)]
public struct TP_POOL_STACK_INFORMATION
{
/// <summary>The stack reserve size.</summary>
public SizeT StackReserve;
/// <summary>The stack commit size.</summary>
public SizeT StackCommit;
}
/// <summary>Defines a callback environment.</summary>
[PInvokeData("threadpoolapiset.h")]
[StructLayout(LayoutKind.Sequential)]
public class PTP_CALLBACK_ENVIRON
{
internal uint Version;
internal PTP_POOL Pool;
internal PTP_CLEANUP_GROUP CleanupGroup;
internal PTP_CLEANUP_GROUP_CANCEL_CALLBACK CleanupGroupCancelCallback;
internal IntPtr RaceDll;
internal IntPtr _ActivationContext;
internal PTP_SIMPLE_CALLBACK _FinalizationCallback;
internal TP_CALLBACK_ENV_FLAGS Flags;
internal TP_CALLBACK_PRIORITY CallbackPriority;
internal uint Size;
internal PTP_CALLBACK_ENVIRON()
{
var isMin7 = Environment.OSVersion.Version >= new Version(6, 1);
Version = isMin7 ? 3U : 1U;
if (isMin7)
{
CallbackPriority = TP_CALLBACK_PRIORITY.TP_CALLBACK_PRIORITY_NORMAL;
Size = (uint)Marshal.SizeOf(typeof(PTP_CALLBACK_ENVIRON));
}
}
/// <summary>Indicates a function to call when the callback environment is finalized.</summary>
/// <value>Pointer to a TP_SIMPLE_CALLBACK structure indicating a function to call when the callback environment is finalized.</value>
public PTP_SIMPLE_CALLBACK FinalizationCallback { set => _FinalizationCallback = value; }
/// <summary>Assigns an activation context to the callback environment.</summary>
/// <value>Pointer to an _ACTIVATION_CONTEXT structure.</value>
public ActCtxSafeHandle ActivationContext { set => _ActivationContext = value.DangerousGetHandle(); }
}
}
}

View File

@ -0,0 +1,422 @@
using Microsoft.Win32.SafeHandles;
using System;
using System.Runtime.InteropServices;
namespace Vanara.PInvoke
{
public static partial class Kernel32
{
/// <summary>
/// An application-defined function that serves as the starting address for a timer callback or a registered wait callback. Specify this address when
/// calling the CreateTimerQueueTimer, RegisterWaitForSingleObject function.
/// </summary>
/// <param name="lpParameter">
/// The thread data passed to the function using a parameter of the CreateTimerQueueTimer or RegisterWaitForSingleObject function.
/// </param>
/// <param name="TimerOrWaitFired">
/// If this parameter is TRUE, the wait timed out. If this parameter is FALSE, the wait event has been signaled. (This parameter is always TRUE for timer callbacks.)
/// </param>
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms687066(v=vs.85).aspx
[PInvokeData("WinBase.h", MSDNShortId = "ms687066")]
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
public delegate void WaitOrTimerCallback(IntPtr lpParameter, [MarshalAs(UnmanagedType.U1)] bool TimerOrWaitFired);
/// <summary>The flags that control execution.</summary>
public enum WT
{
/// <summary>
/// By default, the callback function is queued to a non-I/O worker thread.
/// <para>
/// The callback function is queued to a thread that uses I/O completion ports, which means they cannot perform an alertable wait. Therefore, if I/O
/// completes and generates an APC, the APC might wait indefinitely because there is no guarantee that the thread will enter an alertable wait state
/// after the callback completes.
/// </para>
/// </summary>
WT_EXECUTEDEFAULT = 0x00000000,
/// <summary>
/// This flag is not used.
/// <para>
/// Windows Server 2003 and Windows XP: The callback function is queued to an I/O worker thread. This flag should be used if the function should be
/// executed in a thread that waits in an alertable state. I/O worker threads were removed starting with Windows Vista and Windows Server 2008.
/// </para>
/// </summary>
WT_EXECUTEINIOTHREAD = 0x00000001,
/// <summary>Undocumented.</summary>
WT_EXECUTEINUITHREAD = 0x00000002,
/// <summary>
/// The callback function is invoked by the wait thread itself. This flag should be used only for short tasks or it could affect other wait operations.
/// <para>
/// Deadlocks can occur if some other thread acquires an exclusive lock and calls the UnregisterWait or UnregisterWaitEx function while the callback
/// function is trying to acquire the same lock.
/// </para>
/// </summary>
WT_EXECUTEINWAITTHREAD = 0x00000004,
/// <summary>The timer will be set to the signaled state only once. If this flag is set, the Period parameter must be zero.</summary>
WT_EXECUTEONLYONCE = 0x00000008,
/// <summary>
/// The callback function is invoked by the timer thread itself. This flag should be used only for short tasks or it could affect other timer operations.
/// <para>The callback function is queued as an APC. It should not perform alertable wait operations.</para>
/// </summary>
WT_EXECUTEINTIMERTHREAD = 0x00000020,
/// <summary>The callback function can perform a long wait. This flag helps the system to decide if it should create a new thread.</summary>
WT_EXECUTELONGFUNCTION = 0x00000010,
/// <summary>Undocumented.</summary>
WT_EXECUTEINPERSISTENTIOTHREAD = 0x00000040,
/// <summary>
/// The callback function is queued to a thread that never terminates. It does not guarantee that the same thread is used each time. This flag should
/// be used only for short tasks or it could affect other timer operations. This flag must be set if the thread calls functions that use APCs. For
/// more information, see Asynchronous Procedure Calls.
/// <para>Note that currently no worker thread is truly persistent, although worker threads do not terminate if there are any pending I/O requests.</para>
/// </summary>
WT_EXECUTEINPERSISTENTTHREAD = 0x00000080,
/// <summary>
/// Callback functions will use the current access token, whether it is a process or impersonation token. If this flag is not specified, callback
/// functions execute only with the process token.
/// <para>Windows XP: This flag is not supported until Windows XP SP2 and Windows Server 2003.</para>
/// </summary>
WT_TRANSFER_IMPERSONATION = 0x00000100,
}
/// <summary>
/// Associates the I/O completion port owned by the thread pool with the specified file handle. On completion of an I/O request involving this file, a
/// non-I/O worker thread will execute the specified callback function.
/// </summary>
/// <param name="FileHandle">
/// A handle to the file opened for overlapped I/O completion. This handle is returned by the <c>CreateFile</c> function, with the
/// <c>FILE_FLAG_OVERLAPPED</c> flag.
/// </param>
/// <param name="Function">
/// <para>
/// A pointer to the callback function to be executed in a non-I/O worker thread when the I/O operation is complete. This callback function must not call
/// the <c>TerminateThread</c> function.
/// </para>
/// <para>For more information about the completion routine, see <c>FileIOCompletionRoutine</c>.</para>
/// </param>
/// <param name="Flags">This parameter must be zero.</param>
/// <returns>
/// <para>If the function succeeds, the return value is nonzero.</para>
/// <para>
/// If the function fails, the return value is zero. To get extended error information, call the <c>GetLastError</c> function. The value returned is an
/// <c>NTSTATUS</c> error code. To retrieve the corresponding system error code, use the <c>RtlNtStatusToDosError</c> function.
/// </para>
/// </returns>
// BOOL WINAPI BindIoCompletionCallback( _In_ HANDLE FileHandle, _In_ LPOVERLAPPED_COMPLETION_ROUTINE Function, _In_ ULONG Flags); https://msdn.microsoft.com/en-us/library/windows/desktop/aa363484(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "aa363484")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool BindIoCompletionCallback([In] SafeFileHandle FileHandle, FileIOCompletionRoutine Function, [Optional] uint Flags);
/// <summary>Updates a timer-queue timer that was created by the <c>CreateTimerQueueTimer</c> function.</summary>
/// <param name="TimerQueue">
/// <para>A handle to the timer queue. This handle is returned by the <c>CreateTimerQueue</c> function.</para>
/// <para>If this parameter is <c>NULL</c>, the timer is associated with the default timer queue.</para>
/// </param>
/// <param name="Timer">A handle to the timer-queue timer. This handle is returned by the <c>CreateTimerQueueTimer</c> function.</param>
/// <param name="DueTime">The time after which the timer should expire, in milliseconds.</param>
/// <param name="Period">
/// The period of the timer, in milliseconds. If this parameter is zero, the timer is signaled once. If this parameter is greater than zero, the timer is
/// periodic. A periodic timer automatically reactivates each time the period elapses, until the timer is canceled using the <c>DeleteTimerQueueTimer</c>
/// function or reset using <c>ChangeTimerQueueTimer</c>.
/// </param>
/// <returns>
/// <para>If the function succeeds, the return value is nonzero.</para>
/// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// BOOL WINAPI ChangeTimerQueueTimer( _In_opt_ HANDLE TimerQueue, _Inout_ HANDLE Timer, _In_ ULONG DueTime, _In_ ULONG Period); https://msdn.microsoft.com/en-us/library/windows/desktop/ms682004(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms682004")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool ChangeTimerQueueTimer([In] IntPtr TimerQueue, IntPtr Timer, uint DueTime, uint Period);
/// <summary>
/// Creates a queue for timers. Timer-queue timers are lightweight objects that enable you to specify a callback function to be called at a specified time.
/// </summary>
/// <returns>
/// <para>
/// If the function succeeds, the return value is a handle to the timer queue. This handle can be used only in functions that require a handle to a timer queue.
/// </para>
/// <para>If the function fails, the return value is <c>NULL</c>. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// HANDLE WINAPI CreateTimerQueue(void); https://msdn.microsoft.com/en-us/library/windows/desktop/ms682483(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms682483")]
public static extern IntPtr CreateTimerQueue();
/// <summary>
/// Creates a timer-queue timer. This timer expires at the specified due time, then after every specified period. When the timer expires, the callback
/// function is called.
/// </summary>
/// <param name="phNewTimer">
/// A pointer to a buffer that receives a handle to the timer-queue timer on return. When this handle has expired and is no longer required, release it
/// by calling <c>DeleteTimerQueueTimer</c>.
/// </param>
/// <param name="TimerQueue">
/// <para>A handle to the timer queue. This handle is returned by the <c>CreateTimerQueue</c> function.</para>
/// <para>If this parameter is <c>NULL</c>, the timer is associated with the default timer queue.</para>
/// </param>
/// <param name="Callback">
/// A pointer to the application-defined function of type <c>WAITORTIMERCALLBACK</c> to be executed when the timer expires. For more information, see <c>WaitOrTimerCallback</c>.
/// </param>
/// <param name="Parameter">A single parameter value that will be passed to the callback function.</param>
/// <param name="DueTime">
/// The amount of time in milliseconds relative to the current time that must elapse before the timer is signaled for the first time.
/// </param>
/// <param name="Period">
/// The period of the timer, in milliseconds. If this parameter is zero, the timer is signaled once. If this parameter is greater than zero, the timer is
/// periodic. A periodic timer automatically reactivates each time the period elapses, until the timer is canceled.
/// </param>
/// <param name="Flags">
/// <para>This parameter can be one or more of the following values from WinNT.h.</para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Value</term>
/// <term>Meaning</term>
/// </listheader>
/// <item>
/// <term>WT_EXECUTEDEFAULT0x00000000</term>
/// <term>By default, the callback function is queued to a non-I/O worker thread.</term>
/// </item>
/// <item>
/// <term>WT_EXECUTEINTIMERTHREAD0x00000020</term>
/// <term>
/// The callback function is invoked by the timer thread itself. This flag should be used only for short tasks or it could affect other timer operations.
/// The callback function is queued as an APC. It should not perform alertable wait operations.
/// </term>
/// </item>
/// <item>
/// <term>WT_EXECUTEINIOTHREAD0x00000001</term>
/// <term>
/// This flag is not used.Windows Server 2003 and Windows XP: The callback function is queued to an I/O worker thread. This flag should be used if the
/// function should be executed in a thread that waits in an alertable state. I/O worker threads were removed starting with Windows Vista and Windows
/// Server 2008.
/// </term>
/// </item>
/// <item>
/// <term>WT_EXECUTEINPERSISTENTTHREAD0x00000080</term>
/// <term>
/// The callback function is queued to a thread that never terminates. It does not guarantee that the same thread is used each time. This flag should be
/// used only for short tasks or it could affect other timer operations. This flag must be set if the thread calls functions that use APCs. For more
/// information, see Asynchronous Procedure Calls.Note that currently no worker thread is truly persistent, although no worker thread will terminate if
/// there are any pending I/O requests.
/// </term>
/// </item>
/// <item>
/// <term>WT_EXECUTELONGFUNCTION0x00000010</term>
/// <term>The callback function can perform a long wait. This flag helps the system to decide if it should create a new thread.</term>
/// </item>
/// <item>
/// <term>WT_EXECUTEONLYONCE0x00000008</term>
/// <term>The timer will be set to the signaled state only once. If this flag is set, the Period parameter must be zero.</term>
/// </item>
/// <item>
/// <term>WT_TRANSFER_IMPERSONATION0x00000100</term>
/// <term>
/// Callback functions will use the current access token, whether it is a process or impersonation token. If this flag is not specified, callback
/// functions execute only with the process token.Windows XP: This flag is not supported until Windows XP with SP2 and Windows Server 2003.
/// </term>
/// </item>
/// </list>
/// </para>
/// </param>
/// <returns>
/// <para>If the function succeeds, the return value is nonzero.</para>
/// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// BOOL WINAPI CreateTimerQueueTimer( _Out_ PHANDLE phNewTimer, _In_opt_ HANDLE TimerQueue, _In_ WAITORTIMERCALLBACK Callback, _In_opt_ PVOID Parameter,
// _In_ DWORD DueTime, _In_ DWORD Period, _In_ ULONG Flags); https://msdn.microsoft.com/en-us/library/windows/desktop/ms682485(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms682485")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool CreateTimerQueueTimer(out IntPtr phNewTimer, [In] IntPtr TimerQueue, WaitOrTimerCallback Callback, [In] IntPtr Parameter, uint DueTime, uint Period, WT Flags);
/// <summary>Deletes a timer queue. Any pending timers in the queue are canceled and deleted.</summary>
/// <param name="TimerQueue">A handle to the timer queue. This handle is returned by the <c>CreateTimerQueue</c> function.</param>
/// <param name="CompletionEvent">
/// <para>
/// A handle to the event object to be signaled when the function is successful and all callback functions have completed. This parameter can be <c>NULL</c>.
/// </para>
/// <para>If this parameter is <c>INVALID_HANDLE_VALUE</c>, the function waits for all callback functions to complete before returning.</para>
/// <para>
/// If this parameter is <c>NULL</c>, the function marks the timer for deletion and returns immediately. However, most callers should wait for the
/// callback function to complete so they can perform any needed cleanup.
/// </para>
/// </param>
/// <returns>
/// <para>If the function succeeds, the return value is nonzero.</para>
/// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// BOOL WINAPI DeleteTimerQueueEx( _In_ HANDLE TimerQueue, _In_opt_ HANDLE CompletionEvent); https://msdn.microsoft.com/en-us/library/windows/desktop/ms682568(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms682568")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool DeleteTimerQueueEx([In] IntPtr TimerQueue, [In] IntPtr CompletionEvent);
/// <summary>
/// Removes a timer from the timer queue and optionally waits for currently running timer callback functions to complete before deleting the timer.
/// </summary>
/// <param name="TimerQueue">
/// <para>A handle to the timer queue. This handle is returned by the <c>CreateTimerQueue</c> function.</para>
/// <para>If the timer was created using the default timer queue, this parameter should be <c>NULL</c>.</para>
/// </param>
/// <param name="Timer">A handle to the timer-queue timer. This handle is returned by the <c>CreateTimerQueueTimer</c> function.</param>
/// <param name="CompletionEvent">
/// <para>
/// A handle to the event object to be signaled when the system has canceled the timer and all callback functions have completed. This parameter can be <c>NULL</c>.
/// </para>
/// <para>If this parameter is <c>INVALID_HANDLE_VALUE</c>, the function waits for any running timer callback functions to complete before returning.</para>
/// <para>
/// If this parameter is <c>NULL</c>, the function marks the timer for deletion and returns immediately. If the timer has already expired, the timer
/// callback function will run to completion. However, there is no notification sent when the timer callback function has completed. Most callers should
/// not use this option, and should wait for running timer callback functions to complete so they can perform any needed cleanup.
/// </para>
/// </param>
/// <returns>
/// <para>If the function succeeds, the return value is nonzero.</para>
/// <para>
/// If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>. If the error code is
/// <c>ERROR_IO_PENDING</c>, it is not necessary to call this function again. For any other error, you should retry the call.
/// </para>
/// </returns>
// BOOL WINAPI DeleteTimerQueueTimer( _In_opt_ HANDLE TimerQueue, _In_ HANDLE Timer, _In_opt_ HANDLE CompletionEvent); https://msdn.microsoft.com/en-us/library/windows/desktop/ms682569(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms682569")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool DeleteTimerQueueTimer([In] IntPtr TimerQueue, [In] IntPtr Timer, [In] IntPtr CompletionEvent);
/// <summary>Queues a work item to a worker thread in the thread pool.</summary>
/// <param name="Function">
/// A pointer to the application-defined callback function of type LPTHREAD_START_ROUTINE to be executed by the thread in the thread pool. This value
/// represents the starting address of the thread. This callback function must not call the TerminateThread function.
/// <para>For more information, see ThreadProc.</para>
/// </param>
/// <param name="Context">A single parameter value to be passed to the thread function.</param>
/// <param name="Flags">The flags that control execution. This parameter can be one or more of the following values.</param>
/// <returns>
/// <para>If the function succeeds, the return value is nonzero.</para>
/// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms684957(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms684957")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool QueueUserWorkItem(PTHREAD_START_ROUTINE Function, [In] IntPtr Context, WT Flags);
/// <summary>
/// Directs a wait thread in the thread pool to wait on the object. The wait thread queues the specified callback function to the thread pool when one of
/// the following occurs:
/// </summary>
/// <param name="phNewWaitObject">
/// A pointer to a variable that receives a wait handle on return. Note that a wait handle cannot be used in functions that require an object handle,
/// such as <c>CloseHandle</c>.
/// </param>
/// <param name="hObject">
/// <para>A handle to the object. For a list of the object types whose handles can be specified, see the following Remarks section.</para>
/// <para>If this handle is closed while the wait is still pending, the function's behavior is undefined.</para>
/// <para>The handles must have the <c>SYNCHRONIZE</c> access right. For more information, see Standard Access Rights.</para>
/// </param>
/// <param name="Callback">
/// A pointer to the application-defined function of type <c>WAITORTIMERCALLBACK</c> to be executed when hObject is in the signaled state, or
/// dwMilliseconds elapses. For more information, see <c>WaitOrTimerCallback</c>.
/// </param>
/// <param name="Context">A single value that is passed to the callback function.</param>
/// <param name="dwMilliseconds">
/// The time-out interval, in milliseconds. The function returns if the interval elapses, even if the object's state is nonsignaled. If dwMilliseconds is
/// zero, the function tests the object's state and returns immediately. If dwMilliseconds is <c>INFINITE</c>, the function's time-out interval never elapses.
/// </param>
/// <param name="dwFlags">
/// <para>
/// This parameter can be one or more of the following values. For information about using these values with objects that remain signaled, see the
/// Remarks section.
/// </para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Value</term>
/// <term>Meaning</term>
/// </listheader>
/// <item>
/// <term>WT_EXECUTEDEFAULT0x00000000</term>
/// <term>By default, the callback function is queued to a non-I/O worker thread.</term>
/// </item>
/// <item>
/// <term>WT_EXECUTEINIOTHREAD0x00000001</term>
/// <term>
/// This flag is not used.Windows Server 2003 and Windows XP: The callback function is queued to an I/O worker thread. This flag should be used if the
/// function should be executed in a thread that waits in an alertable state. I/O worker threads were removed starting with Windows Vista and Windows
/// Server 2008.
/// </term>
/// </item>
/// <item>
/// <term>WT_EXECUTEINPERSISTENTTHREAD0x00000080</term>
/// <term>
/// The callback function is queued to a thread that never terminates. It does not guarantee that the same thread is used each time. This flag should be
/// used only for short tasks or it could affect other wait operations. This flag must be set if the thread calls functions that use APCs. For more
/// information, see Asynchronous Procedure Calls.Note that currently no worker thread is truly persistent, although no worker thread will terminate if
/// there are any pending I/O requests.
/// </term>
/// </item>
/// <item>
/// <term>WT_EXECUTEINWAITTHREAD0x00000004</term>
/// <term>
/// The callback function is invoked by the wait thread itself. This flag should be used only for short tasks or it could affect other wait operations.
/// Deadlocks can occur if some other thread acquires an exclusive lock and calls the UnregisterWait or UnregisterWaitEx function while the callback
/// function is trying to acquire the same lock.
/// </term>
/// </item>
/// <item>
/// <term>WT_EXECUTELONGFUNCTION0x00000010</term>
/// <term>The callback function can perform a long wait. This flag helps the system to decide if it should create a new thread.</term>
/// </item>
/// <item>
/// <term>WT_EXECUTEONLYONCE0x00000008</term>
/// <term>
/// The thread will no longer wait on the handle after the callback function has been called once. Otherwise, the timer is reset every time the wait
/// operation completes until the wait operation is canceled.
/// </term>
/// </item>
/// <item>
/// <term>WT_TRANSFER_IMPERSONATION0x00000100</term>
/// <term>
/// Callback functions will use the current access token, whether it is a process or impersonation token. If this flag is not specified, callback
/// functions execute only with the process token.Windows XP: This flag is not supported until Windows XP with SP2 and Windows Server 2003.
/// </term>
/// </item>
/// </list>
/// </para>
/// </param>
/// <returns>
/// <para>If the function succeeds, the return value is nonzero.</para>
/// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// BOOL WINAPI RegisterWaitForSingleObject( _Out_ PHANDLE phNewWaitObject, _In_ HANDLE hObject, _In_ WAITORTIMERCALLBACK Callback, _In_opt_ PVOID
// Context, _In_ ULONG dwMilliseconds, _In_ ULONG dwFlags); https://msdn.microsoft.com/en-us/library/windows/desktop/ms685061(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms685061")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool RegisterWaitForSingleObject(out IntPtr phNewWaitObject, [In] IntPtr hObject, WaitOrTimerCallback Callback, [In] IntPtr Context, uint dwMilliseconds, WT dwFlags);
/// <summary>Cancels a registered wait operation issued by the <c>RegisterWaitForSingleObject</c> function.</summary>
/// <param name="WaitHandle">The wait handle. This handle is returned by the <c>RegisterWaitForSingleObject</c> function.</param>
/// <param name="CompletionEvent">
/// <para>A handle to the event object to be signaled when the wait operation has been unregistered. This parameter can be <c>NULL</c>.</para>
/// <para>If this parameter is <c>INVALID_HANDLE_VALUE</c>, the function waits for all callback functions to complete before returning.</para>
/// <para>
/// If this parameter is <c>NULL</c>, the function marks the timer for deletion and returns immediately. However, most callers should wait for the
/// callback function to complete so they can perform any needed cleanup.
/// </para>
/// <para>
/// If the caller provides this event and the function succeeds or the function fails with <c>ERROR_IO_PENDING</c>, do not close the event until it is signaled.
/// </para>
/// </param>
/// <returns>
/// <para>If the function succeeds, the return value is nonzero.</para>
/// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// BOOL WINAPI UnregisterWaitEx( _In_ HANDLE WaitHandle, _In_opt_ HANDLE CompletionEvent); https://msdn.microsoft.com/en-us/library/windows/desktop/ms686876(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("LibLoaderAPI.h", MSDNShortId = "ms686876")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool UnregisterWaitEx([In] IntPtr WaitHandle, [In] IntPtr CompletionEvent);
}
}

View File

@ -0,0 +1,497 @@
using System.Runtime.InteropServices;
using System.Security;
using FILETIME = System.Runtime.InteropServices.ComTypes.FILETIME;
namespace Vanara.PInvoke
{
public static partial class Kernel32
{
/// <summary>Time Zone information.</summary>
public enum TZID : uint
{
/// <summary>
/// Daylight saving time is not used in the current time zone, because there are no transition dates or automatic adjustment for daylight saving time
/// is disabled.
/// </summary>
TIME_ZONE_ID_UNKNOWN = 0,
/// <summary>The system is operating in the range covered by the StandardDate member of the TIME_ZONE_INFORMATION structure.</summary>
TIME_ZONE_ID_STANDARD = 1,
/// <summary>The system is operating in the range covered by the DaylightDate member of the TIME_ZONE_INFORMATION structure.</summary>
TIME_ZONE_ID_DAYLIGHT = 2,
/// <summary>The time zone identifier is invalid.</summary>
TIME_ZONE_ID_INVALID = 0xFFFFFFFF
}
/// <summary>
/// Enumerates <c>DYNAMIC_TIME_ZONE_INFORMATION</c> entries stored in the registry. This information is used to support time zones that experience annual
/// boundary changes due to daylight saving time adjustments. Use the information returned by this function when calling
/// <c>GetDynamicTimeZoneInformationEffectiveYears</c> to retrieve the specific range of years to pass to <c>GetTimeZoneInformationForYear</c>.
/// </summary>
/// <param name="dwIndex">Index value that represents the location of a <c>DYNAMIC_TIME_ZONE_INFORMATION</c> entry.</param>
/// <param name="lpTimeZoneInformation">Specifies settings for a time zone and dynamic daylight saving time.</param>
/// <returns></returns>
// DWORD WINAPI EnumDynamicTimeZoneInformation( _In_ const DWORD dwIndex, _Out_ PDYNAMIC_TIME_ZONE_INFORMATION lpTimeZoneInformation); https://msdn.microsoft.com/en-us/library/windows/desktop/hh706893(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)]
[PInvokeData("Winbase.h", MSDNShortId = "hh706893")]
public static extern uint EnumDynamicTimeZoneInformation(uint dwIndex, out DYNAMIC_TIME_ZONE_INFORMATION lpTimeZoneInformation);
/// <summary>Converts a file time to system time format. System time is based on Coordinated Universal Time (UTC).</summary>
/// <param name="lpFileTime">
/// A pointer to a FILETIME structure containing the file time to be converted to system (UTC) date and time format. This value must be less than
/// 0x8000000000000000. Otherwise, the function fails.
/// </param>
/// <param name="lpSystemTime">A pointer to a SYSTEMTIME structure to receive the converted file time.</param>
/// <returns>
/// 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.
/// </returns>
[PInvokeData("FileAPI.h", MSDNShortId = "ms724280")]
[DllImport(Lib.Kernel32, ExactSpelling = true, SetLastError = true), SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool FileTimeToSystemTime(ref FILETIME lpFileTime, ref SYSTEMTIME lpSystemTime);
/// <summary>
/// Retrieves the current time zone and dynamic daylight saving time settings. These settings control the translations between Coordinated Universal Time
/// (UTC) and local time.
/// </summary>
/// <param name="pTimeZoneInformation">A pointer to a <c>DYNAMIC_TIME_ZONE_INFORMATION</c> structure.</param>
/// <returns>
/// <para>If the function succeeds, it returns one of the following values.</para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Return code/value</term>
/// <term>Description</term>
/// </listheader>
/// <item>
/// <term>TIME_ZONE_ID_UNKNOWN0</term>
/// <term>Daylight saving time is not used in the current time zone, because there are no transition dates.</term>
/// </item>
/// <item>
/// <term>TIME_ZONE_ID_STANDARD1</term>
/// <term>The system is operating in the range covered by the StandardDate member of the DYNAMIC_TIME_ZONE_INFORMATION structure.</term>
/// </item>
/// <item>
/// <term>TIME_ZONE_ID_DAYLIGHT2</term>
/// <term>The system is operating in the range covered by the DaylightDate member of the DYNAMIC_TIME_ZONE_INFORMATION structure.</term>
/// </item>
/// </list>
/// </para>
/// <para>If the function fails, it returns TIME_ZONE_ID_INVALID. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// DWORD WINAPI GetDynamicTimeZoneInformation( _Out_ PDYNAMIC_TIME_ZONE_INFORMATION pTimeZoneInformation); https://msdn.microsoft.com/en-us/library/windows/desktop/ms724318(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("Winbase.h", MSDNShortId = "ms724318")]
public static extern int GetDynamicTimeZoneInformation(out DYNAMIC_TIME_ZONE_INFORMATION pTimeZoneInformation);
/// <summary>
/// <para>Retrieves the current time zone settings. These settings control the translations between Coordinated Universal Time (UTC) and local time.</para>
/// <para>
/// To support boundaries for daylight saving time that change from year to year, use the <c>GetDynamicTimeZoneInformation</c> or
/// <c>GetTimeZoneInformationForYear</c> function.
/// </para>
/// </summary>
/// <param name="lpTimeZoneInformation">A pointer to a <c>TIME_ZONE_INFORMATION</c> structure to receive the current settings.</param>
/// <returns>
/// <para>If the function succeeds, it returns one of the following values.</para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Return code/value</term>
/// <term>Description</term>
/// </listheader>
/// <item>
/// <term>TIME_ZONE_ID_UNKNOWN0</term>
/// <term>
/// Daylight saving time is not used in the current time zone, because there are no transition dates or automatic adjustment for daylight saving time is disabled.
/// </term>
/// </item>
/// <item>
/// <term>TIME_ZONE_ID_STANDARD1</term>
/// <term>The system is operating in the range covered by the StandardDate member of the TIME_ZONE_INFORMATION structure.</term>
/// </item>
/// <item>
/// <term>TIME_ZONE_ID_DAYLIGHT2</term>
/// <term>The system is operating in the range covered by the DaylightDate member of the TIME_ZONE_INFORMATION structure.</term>
/// </item>
/// </list>
/// </para>
/// <para>
/// If the function fails for other reasons, such as an out of memory error, it returns TIME_ZONE_ID_INVALID. To get extended error information, call <c>GetLastError</c>.
/// </para>
/// </returns>
// DWORD WINAPI GetTimeZoneInformation( _Out_ LPTIME_ZONE_INFORMATION lpTimeZoneInformation); https://msdn.microsoft.com/en-us/library/windows/desktop/ms724421(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("Winbase.h", MSDNShortId = "ms724421")]
public static extern TZID GetTimeZoneInformation(out TIME_ZONE_INFORMATION lpTimeZoneInformation);
/// <summary>
/// Retrieves the time zone settings for the specified year and time zone. These settings control the translations between Coordinated Universal Time
/// (UTC) and local time.
/// </summary>
/// <param name="wYear">The year for which the time zone settings are to be retrieved. The wYear parameter must be a local time value.</param>
/// <param name="pdtzi">
/// A pointer to a <c>DYNAMIC_TIME_ZONE_INFORMATION</c> structure that specifies the time zone. To populate this parameter, call
/// <c>EnumDynamicTimeZoneInformation</c> with the index of the time zone you want. If this parameter is <c>NULL</c>, the current time zone is used.
/// </param>
/// <param name="ptzi">A pointer to a <c>TIME_ZONE_INFORMATION</c> structure that receives the time zone settings.</param>
/// <returns>
/// <para>If the function succeeds, the return value is nonzero.</para>
/// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// BOOL WINAPI GetTimeZoneInformationForYear( _In_ USHORT wYear, _In_opt_ PDYNAMIC_TIME_ZONE_INFORMATION pdtzi, _Out_ LPTIME_ZONE_INFORMATION ptzi); https://msdn.microsoft.com/en-us/library/windows/desktop/bb540851(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("Winbase.h", MSDNShortId = "bb540851")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetTimeZoneInformationForYear(ushort wYear, [In] ref DYNAMIC_TIME_ZONE_INFORMATION pdtzi, out TIME_ZONE_INFORMATION ptzi);
/// <summary>
/// Sets the current time zone and dynamic daylight saving time settings. These settings control translations from Coordinated Universal Time (UTC) to
/// local time.
/// </summary>
/// <param name="lpTimeZoneInformation">A pointer to a <c>DYNAMIC_TIME_ZONE_INFORMATION</c> structure.</param>
/// <returns>
/// <para>If the function succeeds, the return value is nonzero.</para>
/// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// BOOL WINAPI SetDynamicTimeZoneInformation( _In_ const DYNAMIC_TIME_ZONE_INFORMATION *lpTimeZoneInformation); https://msdn.microsoft.com/en-us/library/windows/desktop/ms724932(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("Winbase.h", MSDNShortId = "ms724932")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetDynamicTimeZoneInformation(ref DYNAMIC_TIME_ZONE_INFORMATION lpTimeZoneInformation);
/// <summary>
/// <para>Sets the current time zone settings. These settings control translations from Coordinated Universal Time (UTC) to local time.</para>
/// <para>To support boundaries for daylight saving time that change from year to year, use the <c>SetDynamicTimeZoneInformation</c> function.</para>
/// </summary>
/// <param name="lpTimeZoneInformation">A pointer to a <c>TIME_ZONE_INFORMATION</c> structure that contains the new settings.</param>
/// <returns>
/// <para>If the function succeeds, the return value is nonzero.</para>
/// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// BOOL WINAPI SetTimeZoneInformation( _In_ const TIME_ZONE_INFORMATION *lpTimeZoneInformation); https://msdn.microsoft.com/en-us/library/windows/desktop/ms724944(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("Winbase.h", MSDNShortId = "ms724944")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetTimeZoneInformation([In] ref TIME_ZONE_INFORMATION lpTimeZoneInformation);
/// <summary>Converts a system time to file time format. System time is based on Coordinated Universal Time (UTC).</summary>
/// <param name="lpSystemTime">
/// A pointer to a SYSTEMTIME structure that contains the system time to be converted from UTC to file time format. The wDayOfWeek member of the
/// SYSTEMTIME structure is ignored.
/// </param>
/// <param name="lpFileTime">A pointer to a FILETIME structure to receive the converted system time.</param>
/// <returns>
/// 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.
/// </returns>
[DllImport(Lib.Kernel32, ExactSpelling = true, SetLastError = true), SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
[PInvokeData("Winbase.h", MSDNShortId = "ms724948")]
public static extern bool SystemTimeToFileTime(ref SYSTEMTIME lpSystemTime, ref FILETIME lpFileTime);
/// <summary>Converts a time in Coordinated Universal Time (UTC) to a specified time zone's corresponding local time.</summary>
/// <param name="lpTimeZone">
/// <para>A pointer to a <c>TIME_ZONE_INFORMATION</c> structure that specifies the time zone of interest.</para>
/// <para>If lpTimeZone is <c>NULL</c>, the function uses the currently active time zone.</para>
/// </param>
/// <param name="lpUniversalTime">
/// A pointer to a <c>SYSTEMTIME</c> structure that specifies the UTC time to be converted. The function converts this universal time to the specified
/// time zone's corresponding local time.
/// </param>
/// <param name="lpLocalTime">A pointer to a <c>SYSTEMTIME</c> structure that receives the local time.</param>
/// <returns>
/// <para>
/// If the function succeeds, the return value is nonzero, and the function sets the members of the <c>SYSTEMTIME</c> structure pointed to by lpLocalTime
/// to the appropriate local time values.
/// </para>
/// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// BOOL WINAPI SystemTimeToTzSpecificLocalTime( _In_opt_ LPTIME_ZONE_INFORMATION lpTimeZone, _In_ LPSYSTEMTIME lpUniversalTime, _Out_ LPSYSTEMTIME lpLocalTime);
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("Winbase.h", MSDNShortId = "ms724949")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SystemTimeToTzSpecificLocalTime([In, MarshalAs(UnmanagedType.LPStruct)] TIME_ZONE_INFORMATION lpTimeZone,
[In, MarshalAs(UnmanagedType.LPStruct)] SYSTEMTIME lpUniversalTime, [Out] out SYSTEMTIME lpLocalTime);
/// <summary>
/// Converts a time in Coordinated Universal Time (UTC) with dynamic daylight saving time settings to a specified time zone's corresponding local time.
/// </summary>
/// <param name="lpTimeZoneInformation">
/// A pointer to a <c>DYNAMIC_TIME_ZONE_INFORMATION</c> structure that specifies the time zone and dynamic daylight saving time.
/// </param>
/// <param name="lpUniversalTime">
/// A pointer to a <c>SYSTEMTIME</c> structure that specifies the UTC time to be converted. The function converts this universal time to the specified
/// time zone's corresponding local time.
/// </param>
/// <param name="lpUniversalTime">A pointer to a <c>SYSTEMTIME</c> structure that receives the local time.</param>
/// <returns>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</returns>
// BOOL WINAPI SystemTimeToTzSpecificLocalTimeEx( _In_opt_ const DYNAMIC_TIME_ZONE_INFORMATION* lpTimeZoneInformation, _In_ const SYSTEMTIME*
// lpUniversalTime, _Out_ LPSYSTEMTIME lpLocalTime ); https://msdn.microsoft.com/en-us/library/windows/desktop/jj206642(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("Winbase.h", MSDNShortId = "jj206642")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SystemTimeToTzSpecificLocalTimeEx([In] ref DYNAMIC_TIME_ZONE_INFORMATION lpTimeZoneInformation, [In] ref SYSTEMTIME lpUniversalTime, out SYSTEMTIME lpLocalTime);
/// <summary>
/// <para>Converts a local time to a time in Coordinated Universal Time (UTC).</para>
/// </summary>
/// <param name="lpTimeZoneInformation">
/// <para>A pointer to a <c>TIME_ZONE_INFORMATION</c> structure that specifies the time zone for the time specified in lpLocalTime.</para>
/// <para>If lpTimeZoneInformation is <c>NULL</c>, the function uses the currently active time zone.</para>
/// </param>
/// <param name="lpLocalTime">
/// <para>
/// A pointer to a <c>SYSTEMTIME</c> structure that specifies the local time to be converted. The function converts this time to the corresponding UTC time.
/// </para>
/// </param>
/// <param name="lpUniversalTime">
/// <para>A pointer to a <c>SYSTEMTIME</c> structure that receives the UTC time.</para>
/// </param>
/// <returns>
/// <para>
/// If the function succeeds, the return value is nonzero, and the function sets the members of the <c>SYSTEMTIME</c> structure pointed to by
/// lpUniversalTime to the appropriate values.
/// </para>
/// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// BOOL WINAPI TzSpecificLocalTimeToSystemTime( _In_opt_ LPTIME_ZONE_INFORMATION lpTimeZoneInformation, _In_ LPSYSTEMTIME lpLocalTime, _Out_ LPSYSTEMTIME lpUniversalTime);
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("Winbase.h", MSDNShortId = "ms725485")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool TzSpecificLocalTimeToSystemTime([In, MarshalAs(UnmanagedType.LPStruct)] TIME_ZONE_INFORMATION lpTimeZoneInformation, [In, MarshalAs(UnmanagedType.LPStruct)] SYSTEMTIME lpLocalTime, [Out] out SYSTEMTIME lpUniversalTime);
/// <summary>Converts a local time to a time with dynamic daylight saving time settings to Coordinated Universal Time (UTC).</summary>
/// <param name="lpTimeZoneInformation">
/// A pointer to a <c>DYNAMIC_TIME_ZONE_INFORMATION</c> structure that specifies the time zone and dynamic daylight saving time.
/// </param>
/// <param name="lpLocalTime">
/// A pointer to a <c>SYSTEMTIME</c> structure that specifies the local time to be converted. The function converts this time to the corresponding UTC time.
/// </param>
/// <param name="lpUniversalTime">A pointer to a <c>SYSTEMTIME</c> structure that receives the UTC time.</param>
/// <returns>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</returns>
// BOOL WINAPI TzSpecificLocalTimeToSystemTimeEx( _In_opt_ const DYNAMIC_TIME_ZONE_INFORMATION *lpTimeZoneInformation, _In_ const SYSTEMTIME
// *lpLocalTime, _Out_ LPSYSTEMTIME lpUniversalTime); https://msdn.microsoft.com/en-us/library/windows/desktop/jj206643(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("Winbase.h", MSDNShortId = "jj206643")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool TzSpecificLocalTimeToSystemTimeEx([In] ref DYNAMIC_TIME_ZONE_INFORMATION lpTimeZoneInformation, [In] ref SYSTEMTIME lpLocalTime, out SYSTEMTIME lpUniversalTime);
/// <summary>Specifies settings for a time zone and dynamic daylight saving time.</summary>
// typedef struct _TIME_DYNAMIC_ZONE_INFORMATION { LONG Bias; WCHAR StandardName[32]; SYSTEMTIME StandardDate; LONG StandardBias; WCHAR DaylightName[32];
// SYSTEMTIME DaylightDate; LONG DaylightBias; WCHAR TimeZoneKeyName[128]; BOOLEAN DynamicDaylightTimeDisabled;} DYNAMIC_TIME_ZONE_INFORMATION,
// *PDYNAMIC_TIME_ZONE_INFORMATION; https://msdn.microsoft.com/en-us/library/windows/desktop/ms724253(v=vs.85).aspx
[PInvokeData("WinBase.h", MSDNShortId = "ms724253")]
[StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Unicode)]
public struct DYNAMIC_TIME_ZONE_INFORMATION
{
/// <summary>
/// <para>
/// The current bias for local time translation on this computer, in minutes. The bias is the difference, in minutes, between Coordinated Universal
/// Time (UTC) and local time. All translations between UTC and local time are based on the following formula:
/// </para>
/// <para>UTC = local time + bias</para>
/// <para>This member is required.</para>
/// </summary>
public int Bias;
/// <summary>
/// A description for standard time. For example, "EST" could indicate Eastern Standard Time. The string will be returned unchanged by the
/// <c>GetDynamicTimeZoneInformation</c> function. This string can be empty.
/// </summary>
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
public string StandardName;
/// <summary>
/// <para>
/// A <c>SYSTEMTIME</c> structure that contains a date and local time when the transition from daylight saving time to standard time occurs on this
/// operating system. If the time zone does not support daylight saving time or if the caller needs to disable daylight saving time, the
/// <c>wMonth</c> member in the <c>SYSTEMTIME</c> structure must be zero. If this date is specified, the <c>DaylightDate</c> member of this structure
/// must also be specified. Otherwise, the system assumes the time zone data is invalid and no changes will be applied.
/// </para>
/// <para>
/// To select the correct day in the month, set the <c>wYear</c> member to zero, the <c>wHour</c> and <c>wMinute</c> members to the transition time,
/// the <c>wDayOfWeek</c> member to the appropriate weekday, and the <c>wDay</c> member to indicate the occurrence of the day of the week within the
/// month (1 to 5, where 5 indicates the final occurrence during the month if that day of the week does not occur 5 times).
/// </para>
/// <para>
/// Using this notation, specify 02:00 on the first Sunday in April as follows: <c>wHour</c> = 2, <c>wMonth</c> = 4, <c>wDayOfWeek</c> = 0,
/// <c>wDay</c> = 1. Specify 02:00 on the last Thursday in October as follows: <c>wHour</c> = 2, <c>wMonth</c> = 10, <c>wDayOfWeek</c> = 4,
/// <c>wDay</c> = 5.
/// </para>
/// <para>
/// If the <c>wYear</c> member is not zero, the transition date is absolute; it will only occur one time. Otherwise, it is a relative date that
/// occurs yearly.
/// </para>
/// </summary>
public SYSTEMTIME StandardDate;
/// <summary>
/// <para>
/// The bias value to be used during local time translations that occur during standard time. This member is ignored if a value for the
/// <c>StandardDate</c> member is not supplied.
/// </para>
/// <para>
/// This value is added to the value of the <c>Bias</c> member to form the bias used during standard time. In most time zones, the value of this
/// member is zero.
/// </para>
/// </summary>
public int StandardBias;
/// <summary>
/// A description for daylight saving time (DST). For example, "PDT" could indicate Pacific Daylight Time. The string will be returned unchanged by
/// the <c>GetDynamicTimeZoneInformation</c> function. This string can be empty.
/// </summary>
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
public string DaylightName;
/// <summary>
/// <para>
/// A <c>SYSTEMTIME</c> structure that contains a date and local time when the transition from standard time to daylight saving time occurs on this
/// operating system. If the time zone does not support daylight saving time or if the caller needs to disable daylight saving time, the
/// <c>wMonth</c> member in the <c>SYSTEMTIME</c> structure must be zero. If this date is specified, the <c>StandardDate</c> member in this structure
/// must also be specified. Otherwise, the system assumes the time zone data is invalid and no changes will be applied.
/// </para>
/// <para>
/// To select the correct day in the month, set the <c>wYear</c> member to zero, the <c>wHour</c> and <c>wMinute</c> members to the transition time,
/// the <c>wDayOfWeek</c> member to the appropriate weekday, and the <c>wDay</c> member to indicate the occurrence of the day of the week within the
/// month (1 to 5, where 5 indicates the final occurrence during the month if that day of the week does not occur 5 times).
/// </para>
/// <para>
/// If the <c>wYear</c> member is not zero, the transition date is absolute; it will only occur one time. Otherwise, it is a relative date that
/// occurs yearly.
/// </para>
/// </summary>
public SYSTEMTIME DaylightDate;
/// <summary>
/// <para>
/// The bias value to be used during local time translations that occur during daylight saving time. This member is ignored if a value for the
/// <c>DaylightDate</c> member is not supplied.
/// </para>
/// <para>
/// This value is added to the value of the <c>Bias</c> member to form the bias used during daylight saving time. In most time zones, the value of
/// this member is 60.
/// </para>
/// </summary>
public int DaylightBias;
/// <summary>The name of the time zone registry key on the local computer. For more information, see Remarks.</summary>
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
public string TimeZoneKeyName;
/// <summary>
/// <para>
/// Indicates whether dynamic daylight saving time is disabled. Setting this member to <c>TRUE</c> disables dynamic daylight saving time, causing the
/// system to use a fixed set of transition dates.
/// </para>
/// <para>
/// To restore dynamic daylight saving time, call the <c>SetDynamicTimeZoneInformation</c> function with <c>DynamicDaylightTimeDisabled</c> set to
/// <c>FALSE</c>. The system will read the transition dates for the current year at the next time update, the next system reboot, or the end of the
/// calendar year (whichever comes first.)
/// </para>
/// <para>
/// When calling the <c>GetDynamicTimeZoneInformation</c> function, this member is <c>TRUE</c> if the time zone was set using the
/// <c>SetTimeZoneInformation</c> function instead of <c>SetDynamicTimeZoneInformation</c> or if the user has disabled this feature using the Date
/// and Time application in Control Panel.
/// </para>
/// <para>
/// To disable daylight saving time, set this member to <c>TRUE</c>, clear the <c>StandardDate</c> and <c>DaylightDate</c> members, and call
/// <c>SetDynamicTimeZoneInformation</c>. To restore daylight saving time, call <c>SetDynamicTimeZoneInformation</c> with
/// <c>DynamicDaylightTimeDisabled</c> set to <c>FALSE</c>.
/// </para>
/// </summary>
[MarshalAs(UnmanagedType.U1)]
public bool DynamicDaylightTimeDisabled;
}
/// <summary>
/// <para>Specifies settings for a time zone.</para>
/// </summary>
// typedef struct _TIME_ZONE_INFORMATION { LONG Bias; WCHAR StandardName[32]; SYSTEMTIME StandardDate; LONG StandardBias; WCHAR DaylightName[32];
// SYSTEMTIME DaylightDate; LONG DaylightBias;} TIME_ZONE_INFORMATION, *PTIME_ZONE_INFORMATION;
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
[PInvokeData("Winbase.h", MSDNShortId = "ms725481")]
public struct TIME_ZONE_INFORMATION
{
/// <summary>
/// <para>
/// The current bias for local time translation on this computer, in minutes. The bias is the difference, in minutes, between Coordinated Universal
/// Time (UTC) and local time. All translations between UTC and local time are based on the following formula:
/// </para>
/// <para>UTC = local time + bias</para>
/// <para>This member is required.</para>
/// </summary>
public int Bias;
/// <summary>
/// <para>
/// A description for standard time. For example, "EST" could indicate Eastern Standard Time. The string will be returned unchanged by the
/// <c>GetTimeZoneInformation</c> function. This string can be empty.
/// </para>
/// </summary>
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
public string StandardName;
/// <summary>
/// <para>
/// A <c>SYSTEMTIME</c> structure that contains a date and local time when the transition from daylight saving time to standard time occurs on this
/// operating system. If the time zone does not support daylight saving time or if the caller needs to disable daylight saving time, the
/// <c>wMonth</c> member in the <c>SYSTEMTIME</c> structure must be zero. If this date is specified, the <c>DaylightDate</c> member of this structure
/// must also be specified. Otherwise, the system assumes the time zone data is invalid and no changes will be applied.
/// </para>
/// <para>
/// To select the correct day in the month, set the <c>wYear</c> member to zero, the <c>wHour</c> and <c>wMinute</c> members to the transition time,
/// the <c>wDayOfWeek</c> member to the appropriate weekday, and the <c>wDay</c> member to indicate the occurrence of the day of the week within the
/// month (1 to 5, where 5 indicates the final occurrence during the month if that day of the week does not occur 5 times).
/// </para>
/// <para>
/// Using this notation, specify 02:00 on the first Sunday in April as follows: <c>wHour</c> = 2, <c>wMonth</c> = 4, <c>wDayOfWeek</c> = 0,
/// <c>wDay</c> = 1. Specify 02:00 on the last Thursday in October as follows: <c>wHour</c> = 2, <c>wMonth</c> = 10, <c>wDayOfWeek</c> = 4,
/// <c>wDay</c> = 5.
/// </para>
/// <para>
/// If the <c>wYear</c> member is not zero, the transition date is absolute; it will only occur one time. Otherwise, it is a relative date that
/// occurs yearly.
/// </para>
/// </summary>
public SYSTEMTIME StandardDate;
/// <summary>
/// <para>
/// The bias value to be used during local time translations that occur during standard time. This member is ignored if a value for the
/// <c>StandardDate</c> member is not supplied.
/// </para>
/// <para>
/// This value is added to the value of the <c>Bias</c> member to form the bias used during standard time. In most time zones, the value of this
/// member is zero.
/// </para>
/// </summary>
public int StandardBias;
/// <summary>
/// <para>
/// A description for daylight saving time. For example, "PDT" could indicate Pacific Daylight Time. The string will be returned unchanged by the
/// <c>GetTimeZoneInformation</c> function. This string can be empty.
/// </para>
/// </summary>
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
public string DaylightName;
/// <summary>
/// <para>
/// A <c>SYSTEMTIME</c> structure that contains a date and local time when the transition from standard time to daylight saving time occurs on this
/// operating system. If the time zone does not support daylight saving time or if the caller needs to disable daylight saving time, the
/// <c>wMonth</c> member in the <c>SYSTEMTIME</c> structure must be zero. If this date is specified, the <c>StandardDate</c> member in this structure
/// must also be specified. Otherwise, the system assumes the time zone data is invalid and no changes will be applied.
/// </para>
/// <para>
/// To select the correct day in the month, set the <c>wYear</c> member to zero, the <c>wHour</c> and <c>wMinute</c> members to the transition time,
/// the <c>wDayOfWeek</c> member to the appropriate weekday, and the <c>wDay</c> member to indicate the occurrence of the day of the week within the
/// month (1 to 5, where 5 indicates the final occurrence during the month if that day of the week does not occur 5 times).
/// </para>
/// <para>
/// If the <c>wYear</c> member is not zero, the transition date is absolute; it will only occur one time. Otherwise, it is a relative date that
/// occurs yearly.
/// </para>
/// </summary>
public SYSTEMTIME DaylightDate;
/// <summary>
/// <para>
/// The bias value to be used during local time translations that occur during daylight saving time. This member is ignored if a value for the
/// <c>DaylightDate</c> member is not supplied.
/// </para>
/// <para>
/// This value is added to the value of the <c>Bias</c> member to form the bias used during daylight saving time. In most time zones, the value of
/// this member is 60.
/// </para>
/// </summary>
public int DaylightBias;
}
}
}

View File

@ -0,0 +1,90 @@
using System;
using System.Runtime.InteropServices;
namespace Vanara.PInvoke
{
public static partial class Kernel32
{
/// <summary>
/// Generates simple tones on the speaker. The function is synchronous; it performs an alertable wait and does not return control to its caller until the
/// sound finishes.
/// </summary>
/// <param name="dwFreq">The frequency of the sound, in hertz. This parameter must be in the range 37 through 32,767 (0x25 through 0x7FFF).</param>
/// <param name="dwDuration">The duration of the sound, in milliseconds.</param>
/// <returns>
/// <para>If the function succeeds, the return value is nonzero.</para>
/// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// BOOL WINAPI Beep( _In_ DWORD dwFreq, _In_ DWORD dwDuration); https://msdn.microsoft.com/en-us/library/windows/desktop/ms679277(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms679277")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool Beep(uint dwFreq, uint dwDuration);
/// <summary>Decodes a pointer that was previously encoded with <c>EncodePointer</c>.</summary>
/// <param name="Ptr">The pointer to be decoded.</param>
/// <returns>The function returns the decoded pointer.</returns>
// PVOID DecodePointer( PVOID Ptr ); https://msdn.microsoft.com/en-us/library/bb432242(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)]
[PInvokeData("UtilApiSet.h", MSDNShortId = "bb432242")]
public static extern IntPtr DecodePointer([In] IntPtr Ptr);
/// <summary>
/// <para>
/// [Some information relates to pre-released product which may be substantially modified before it's commercially released. Microsoft makes no
/// warranties, express or implied, with respect to the information provided here.]
/// </para>
/// <para>Decodes a pointer in a specified process that was previously encoded with <c>EncodePointer</c> or <c>EncodeRemotePointer</c>.</para>
/// </summary>
/// <param name="ProcessHandle">Handle to the remote process that owns the pointer.</param>
/// <param name="Ptr">The pointer to be decoded.</param>
/// <param name="DecodedPtr">The decoded pointer.</param>
/// <returns>Returns S_OK if successful, otherwise the function failed.</returns>
// HRESULT WINAPI DecodeRemotePointer( _In_ HANDLE ProcessHandle, _In_opt_ PVOID Ptr, _Out_ PVOID * DecodedPtr ); https://msdn.microsoft.com/en-us/library/dn877133(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)]
[PInvokeData("UtilApiSet.h", MSDNShortId = "dn877133")]
public static extern HRESULT DecodeRemotePointer(IntPtr ProcessHandle, IntPtr Ptr, out IntPtr DecodedPtr);
/// <summary>Decodes a pointer that was previously encoded with EncodeSystemPointer.</summary>
/// <param name="Ptr">The system pointer to be decoded.</param>
/// <returns>The function returns the decoded pointer.</returns>
// PVOID DecodeSystemPointer( PVOID Ptr ); https://msdn.microsoft.com/en-us/library/bb432243(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)]
[PInvokeData("UtilApiSet.h", MSDNShortId = "bb432243")]
public static extern IntPtr DecodeSystemPointer([In] IntPtr Ptr);
/// <summary>Encodes the specified pointer. Encoded pointers can be used to provide another layer of protection for pointer values.</summary>
/// <param name="Ptr">The pointer to be encoded.</param>
/// <returns>The function returns the encoded pointer.</returns>
// PVOID EncodePointer( _In_ PVOID Ptr ); https://msdn.microsoft.com/en-us/library/bb432254(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)]
[PInvokeData("UtilApiSet.h", MSDNShortId = "bb432254")]
public static extern IntPtr EncodePointer([In] IntPtr Ptr);
/// <summary>
/// <para>
/// [Some information relates to pre-released product which may be substantially modified before it's commercially released. Microsoft makes no
/// warranties, express or implied, with respect to the information provided here.]
/// </para>
/// <para>Encodes the specified pointer of the specified process. Encoded pointers can be used to provide another layer of protection for pointer values.</para>
/// </summary>
/// <param name="ProcessHandle">Handle to the remote process that owns the pointer.</param>
/// <param name="Ptr">The pointer to be encoded.</param>
/// <param name="EncodedPtr">The encoded pointer.</param>
/// <returns>Returns S_OK if successful, otherwise the function failed.</returns>
// HRESULT WINAPI EncodeRemotePointer( _In_ HANDLE ProcessHandle, _In_opt_ PVOID Ptr, _Out_ PVOID * EncodedPtr ); https://msdn.microsoft.com/en-us/library/dn877135(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)]
[PInvokeData("UtilApiSet.h", MSDNShortId = "dn877135")]
public static extern HRESULT EncodeRemotePointer(IntPtr ProcessHandle, IntPtr Ptr, out IntPtr EncodedPtr);
/// <summary>
/// Encodes the specified pointer with a system-specific value. Encoded pointers can be used to provide another layer of protection for pointer values.
/// </summary>
/// <param name="Ptr">The system pointer to be encoded.</param>
/// <returns>The function returns the encoded pointer.</returns>
// PVOID EncodeSystemPointer( PVOID Ptr ); https://msdn.microsoft.com/en-us/library/bb432255(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)]
[PInvokeData("UtilApiSet.h", MSDNShortId = "bb432255")]
public static extern IntPtr EncodeSystemPointer([In] IntPtr Ptr);
}
}

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,111 @@
using System;
// ReSharper disable InconsistentNaming
namespace Vanara.PInvoke
{
public static partial class Kernel32
{
/// <summary>
/// Flags that may be passed to the <see cref="GetVolumeInformation(string, out string, out uint, out uint, out FileSystemFlags, out string)"/> function.
/// </summary>
[Flags]
[PInvokeData("winnt.h")]
public enum FileSystemFlags : uint
{
/// <summary>The specified volume supports case-sensitive file names.</summary>
FILE_CASE_SENSITIVE_SEARCH = 0x00000001,
/// <summary>The specified volume supports preserved case of file names when it places a name on disk.</summary>
FILE_CASE_PRESERVED_NAMES = 0x00000002,
/// <summary>The specified volume supports Unicode in file names as they appear on disk.</summary>
FILE_UNICODE_ON_DISK = 0x00000004,
/// <summary>
/// The specified volume preserves and enforces access control lists (ACL). For example, the NTFS file system preserves and enforces ACLs, and the
/// FAT file system does not.
/// </summary>
FILE_PERSISTENT_ACLS = 0x00000008,
/// <summary>The specified volume supports file-based compression.</summary>
FILE_FILE_COMPRESSION = 0x00000010,
/// <summary>The specified volume supports disk quotas.</summary>
FILE_VOLUME_QUOTAS = 0x00000020,
/// <summary>The specified volume supports sparse files.</summary>
FILE_SUPPORTS_SPARSE_FILES = 0x00000040,
/// <summary>The specified volume supports re-parse points.</summary>
FILE_SUPPORTS_REPARSE_POINTS = 0x00000080,
/// <summary>The file system supports remote storage.</summary>
FILE_SUPPORTS_REMOTE_STORAGE = 0x00000100,
/// <summary></summary>
FILE_RETURNS_CLEANUP_RESULT_INFO = 0x00000200,
/// <summary></summary>
FILE_SUPPORTS_POSIX_UNLINK_RENAME = 0x00000400,
/// <summary>The specified volume is a compressed volume.</summary>
FILE_VOLUME_IS_COMPRESSED = 0x00008000,
/// <summary>The specified volume supports object identifiers.</summary>
FILE_SUPPORTS_OBJECT_IDS = 0x00010000,
/// <summary>
/// The specified volume supports the Encrypted File System (EFS). For more information, see
/// <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/aa364223(v=vs.85).aspx">File Encryption</a>.
/// </summary>
FILE_SUPPORTS_ENCRYPTION = 0x00020000,
/// <summary>The specified volume supports named streams.</summary>
FILE_NAMED_STREAMS = 0x00040000,
/// <summary>The specified volume is read-only.</summary>
FILE_READ_ONLY_VOLUME = 0x00080000,
/// <summary>The specified volume supports a single sequential write.</summary>
FILE_SEQUENTIAL_WRITE_ONCE = 0x00100000,
/// <summary>
/// The specified volume supports transactions. For more information, see
/// <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/aa365993(v=vs.85).aspx">About KTM</a>.
/// </summary>
FILE_SUPPORTS_TRANSACTIONS = 0x00200000,
/// <summary>
/// The specified volume supports hard links. For more information, see
/// <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/aa365006(v=vs.85).aspx">Hard Links and Junctions.</a>
/// <para>
/// <c>Windows Server 2008, Windows Vista, Windows Server 2003 and Windows XP:</c> This value is not supported until Windows Server 2008 R2 and
/// Windows 7.
/// </para>
/// </summary>
FILE_SUPPORTS_HARD_LINKS = 0x00400000,
/// <summary>
/// The specified volume supports extended attributes. An extended attribute is a piece of application-specific metadata that an application can
/// associate with a file and is not part of the file's data.
/// <para>
/// <c>Windows Server 2008, Windows Vista, Windows Server 2003 and Windows XP:</c> This value is not supported until Windows Server 2008 R2 and
/// Windows 7.
/// </para>
/// </summary>
FILE_SUPPORTS_EXTENDED_ATTRIBUTES = 0x00800000,
/// <summary>
/// The file system supports open by FileID. For more information, see FILE_ID_BOTH_DIR_INFO.
/// <para>
/// <c>Windows Server 2008, Windows Vista, Windows Server 2003 and Windows XP:</c> This value is not supported until Windows Server 2008 R2 and
/// Windows 7.
/// </para>
/// </summary>
FILE_SUPPORTS_OPEN_BY_FILE_ID = 0x01000000,
/// <summary>
/// The specified volume supports update sequence number (USN) journals. For more information, see
/// <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/aa363803(v=vs.85).aspx">Change Journal Records</a> .
/// <para>
/// <c>Windows Server 2008, Windows Vista, Windows Server 2003 and Windows XP:</c> This value is not supported until Windows Server 2008 R2 and
/// Windows 7.
/// </para>
/// </summary>
FILE_SUPPORTS_USN_JOURNAL = 0x02000000,
/// <summary>The specified volume supports integrity streams.</summary>
FILE_SUPPORTS_INTEGRITY_STREAMS = 0x04000000,
/// <summary>The specified volume supports block refcounting.</summary>
FILE_SUPPORTS_BLOCK_REFCOUNTING = 0x08000000,
/// <summary>The specified volume supports sparse VDL.</summary>
FILE_SUPPORTS_SPARSE_VDL = 0x10000000,
/// <summary>
/// The specified volume is a direct access (DAX) volume.
/// <para><c>Note</c> This flag was introduced in Windows 10, version 1607.</para>
/// </summary>
FILE_DAX_VOLUME = 0x20000000,
/// <summary>The specified volume supports ghosting.</summary>
FILE_SUPPORTS_GHOSTING = 0x40000000
}
}
}

View File

@ -1,5 +1,4 @@
using System;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Text;
using Vanara.InteropServices;
@ -8,6 +7,32 @@ namespace Vanara.PInvoke
{
public static partial class Kernel32
{
/// <summary>
/// Application-defined callback function used to save data and application state information in the event the application encounters an unhandled
/// exception or becomes unresponsive.
/// </summary>
/// <param name="pvParameter">Context information specified when you called the RegisterApplicationRecoveryCallback function to register for recovery.</param>
/// <returns>The return value is not used and should be 0.</returns>
[UnmanagedFunctionPointer(CallingConvention.Winapi)]
[PInvokeData("Winbase.h", MSDNShortId = "aa373202")]
public delegate uint ApplicationRecoveryCallback(IntPtr pvParameter);
/// <summary>Flags that determine in which section FindActCtxSectionString searches.</summary>
public enum ACTCTX_SECTION
{
ACTIVATION_CONTEXT_SECTION_ASSEMBLY_INFORMATION = 1,
ACTIVATION_CONTEXT_SECTION_DLL_REDIRECTION = 2,
ACTIVATION_CONTEXT_SECTION_WINDOW_CLASS_REDIRECTION = 3,
ACTIVATION_CONTEXT_SECTION_COM_SERVER_REDIRECTION = 4,
ACTIVATION_CONTEXT_SECTION_COM_INTERFACE_REDIRECTION = 5,
ACTIVATION_CONTEXT_SECTION_COM_TYPE_LIBRARY_REDIRECTION = 6,
ACTIVATION_CONTEXT_SECTION_COM_PROGID_REDIRECTION = 7,
ACTIVATION_CONTEXT_SECTION_GLOBAL_OBJECT_RENAME_TABLE = 8,
ACTIVATION_CONTEXT_SECTION_CLR_SURROGATES = 9,
ACTIVATION_CONTEXT_SECTION_APPLICATION_SETTINGS = 10,
ACTIVATION_CONTEXT_SECTION_COMPATIBILITY_INFO = 11
}
/// <summary>Flags that indicate how the values included in <see cref="ACTCTX"/> are to be used.</summary>
[Flags]
[PInvokeData("Winbase.h")]
@ -41,6 +66,56 @@ namespace Vanara.PInvoke
ACTCTX_FLAG_HMODULE_VALID = 0x00000080
}
/// <summary></summary>
public enum ACTIVATION_CONTEXT_INFO_CLASS
{
/// <summary>Not available.</summary>
ActivationContextBasicInformation = 1,
/// <summary>
/// If QueryActCtxW is called with this option and the function succeeds, the returned buffer contains detailed information about the activation
/// context. This information is in the form of the ACTIVATION_CONTEXT_DETAILED_INFORMATION structure.
/// </summary>
ActivationContextDetailedInformation = 2,
/// <summary>
/// If QueryActCtxW is called with this option and the function succeeds, the buffer contains information about the assembly that has the index
/// specified in pvSubInstance. This information is in the form of the ACTIVATION_CONTEXT_ASSEMBLY_DETAILED_INFORMATION structure.
/// </summary>
AssemblyDetailedInformationInActivationContext = 3,
/// <summary>
/// Information about a file in one of the assemblies in Activation Context. The pvSubInstance parameter must point to an
/// ACTIVATION_CONTEXT_QUERY_INDEX structure. If QueryActCtxW is called with this option and the function succeeds, the returned buffer contains
/// information for a file in the assembly. This information is in the form of the ASSEMBLY_FILE_DETAILED_INFORMATION structure.
/// </summary>
FileInformationInAssemblyOfAssemblyInActivationContext = 4,
/// <summary>
/// If QueryActCtxW is called with this option and the function succeeds, the buffer contains information about requested run level of the activation
/// context. This information is in the form of the ACTIVATION_CONTEXT_RUN_LEVEL_INFORMATION structure.Windows Server 2003 and Windows XP: This value
/// is not available.
/// </summary>
RunlevelInformationInActivationContext = 5,
/// <summary>
/// If QueryActCtxW is called with this option and the function succeeds, the buffer contains information about requested compatibility context. This
/// information is in the form of the ACTIVATION_CONTEXT_COMPATIBILITY_INFORMATION structure.Windows Server 2008 and earlier, and Windows Vista and
/// earlier: This value is not available. This option is available beginning with Windows Server 2008 R2 and Windows 7.
/// </summary>
CompatibilityInformationInActivationContext = 6,
/// <summary>The activation context manifest resource name</summary>
ActivationContextManifestResourceName = 7,
/// <summary>The maximum activation context information class</summary>
MaxActivationContextInfoClass,
/// <summary>
/// If QueryActCtxW is called with this option and the function succeeds, the buffer contains information about the assembly that has the index
/// specified in pvSubInstance. This information is in the form of the ACTIVATION_CONTEXT_ASSEMBLY_DETAILED_INFORMATION structure.
/// </summary>
AssemblyDetailedInformationInActivationContxt = 3,
/// <summary>
/// Information about a file in one of the assemblies in Activation Context. The pvSubInstance parameter must point to an
/// ACTIVATION_CONTEXT_QUERY_INDEX structure. If QueryActCtxW is called with this option and the function succeeds, the returned buffer contains
/// information for a file in the assembly. This information is in the form of the ASSEMBLY_FILE_DETAILED_INFORMATION structure.
/// </summary>
FileInformationInAssemblyOfAssemblyInActivationContxt = 4
}
/// <summary></summary>
[Flags]
[PInvokeData("Winbase.h", MSDNShortId = "aa373344")]
@ -59,6 +134,7 @@ namespace Vanara.PInvoke
RESTART_NO_REBOOT = 8,
}
/// <summary></summary>
[PInvokeData("Winbase.h")]
public enum DeactivateActCtxFlag
{
@ -87,153 +163,672 @@ namespace Vanara.PInvoke
DEACTIVATE_ACTCTX_FLAG_FORCE_EARLY_DEACTIVATION = 1
}
/// <summary>
/// Application-defined callback function used to save data and application state information in the event the application encounters an unhandled
/// exception or becomes unresponsive.
/// </summary>
/// <param name="pvParameter">Context information specified when you called the RegisterApplicationRecoveryCallback function to register for recovery.</param>
/// <returns>The return value is not used and should be 0.</returns>
[UnmanagedFunctionPointer(CallingConvention.Winapi)]
[PInvokeData("Winbase.h", MSDNShortId = "aa373202")]
public delegate uint ApplicationRecoveryCallback(IntPtr pvParameter);
/// <summary>Flags that determine how FindActCtxSectionString operates.</summary>
public enum FIND_ACTCTX_SECTION
{
/// <summary>
/// This function returns the activation context handle where the redirection data was found in the hActCtx member of the ACTCTX_SECTION_KEYED_DATA
/// structure. The caller must use ReleaseActCtx to release this activation context.
/// </summary>
FIND_ACTCTX_SECTION_KEY_RETURN_HACTCTX = 0x00000001,
/// <summary>Undocumented.</summary>
FIND_ACTCTX_SECTION_KEY_RETURN_FLAGS = 0x00000002,
/// <summary>Undocumented.</summary>
FIND_ACTCTX_SECTION_KEY_RETURN_ASSEMBLY_METADATA = 0x00000004
}
/// <summary></summary>
[PInvokeData("Winbase.h")]
public enum QueryActCtxFlag : uint
{
/// <summary>
/// QueryActCtxW queries the activation context active on the thread instead of the context specified by hActCtx. This is usually the last activation
/// context passed to ActivateActCtx. If ActivateActCtx has not been called, the active activation context can be the activation context used by the
/// executable of the current process. In other cases, the operating system determines the active activation context. For example, when the callback
/// function to a new thread is called, the active activation context may be the context that was active when you created the thread by calling CreateThread.
/// </summary>
QUERY_ACTCTX_FLAG_USE_ACTIVE_ACTCTX = 0x00000004,
/// <summary>
/// QueryActCtxW interprets hActCtx as an HMODULE data type and queries an activation context that is associated with a DLL or EXE. When a DLL or EXE
/// is loaded, the loader checks for a manifest stored in a resource. If the loader finds an RT_MANIFEST resource with a resource identifier set to
/// ISOLATIONAWARE_MANIFEST_ RESOURCE_ID, the loader associates the resulting activation context with the DLL or EXE. This is the activation context
/// that QueryActCtxW queries when the QUERY_ACTCTX_FLAG_ACTCTX_IS_HMODULE flag has been set.
/// </summary>
QUERY_ACTCTX_FLAG_ACTCTX_IS_HMODULE = 0x00000008,
/// <summary>
/// QueryActCtxW interprets hActCtx as an address within a DLL or EXE and queries an activation context that has been associated with the DLL or EXE.
/// This can be any address within the DLL or EXE. For example, the address of any function within a DLL or EXE or the address of any static data,
/// such as a constant string. When a DLL or EXE is loaded, the loader checks for a manifest stored in a resource in the same way as QUERY_ACTCTX_FLAG_ACTCTX_IS_HMODULE.
/// </summary>
QUERY_ACTCTX_FLAG_ACTCTX_IS_ADDRESS = 0x00000010,
/// <summary>Undocumented.</summary>
QUERY_ACTCTX_FLAG_NO_ADDREF = 0x80000000,
}
/// <summary>
/// The ActivateActCtx function activates the specified activation context. It does this by pushing the specified activation context to the top of the
/// activation stack. The specified activation context is thus associated with the current thread and any appropriate side-by-side API functions.
/// The <c>ActivateActCtx</c> function activates the specified activation context. It does this by pushing the specified activation context to the top of
/// the activation stack. The specified activation context is thus associated with the current thread and any appropriate side-by-side API functions.
/// </summary>
/// <param name="hActCtx">Handle to an ACTCTX structure that contains information on the activation context that is to be made active.</param>
/// <param name="lpCookie">Pointer to a ULONG_PTR that functions as a cookie, uniquely identifying a specific, activated activation context.</param>
/// <returns>If the function succeeds, it returns TRUE. Otherwise, it returns FALSE. This function sets errors that can be retrieved by calling GetLastError.</returns>
[DllImport(Lib.Kernel32, ExactSpelling = true, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
/// <param name="hActCtx">Handle to an <c>ACTCTX</c> structure that contains information on the activation context that is to be made active.</param>
/// <param name="lpCookie">Pointer to a <c>ULONG_PTR</c> that functions as a cookie, uniquely identifying a specific, activated activation context.</param>
/// <returns>
/// <para>If the function succeeds, it returns <c>TRUE</c>. Otherwise, it returns <c>FALSE</c>.</para>
/// <para>
/// This function sets errors that can be retrieved by calling <c>GetLastError</c>. For an example, see Retrieving the Last-Error Code. For a complete
/// list of error codes, see System Error Codes.
/// </para>
/// </returns>
// BOOL ActivateActCtx( _In_ HANDLE hActCtx, _Out_ ULONG_PTR *lpCookie); https://msdn.microsoft.com/en-us/library/windows/desktop/aa374151(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("Winbase.h", MSDNShortId = "aa374151")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool ActivateActCtx(ActCtxSafeHandle hActCtx, out IntPtr lpCookie);
/// <summary>The <c>AddRefActCtx</c> function increments the reference count of the specified activation context.</summary>
/// <param name="hActCtx">
/// Handle to an <c>ACTCTX</c> structure that contains information on the activation context for which the reference count is to be incremented.
/// </param>
/// <returns>This function does not return a value.</returns>
// void AddRefActCtx( _In_ HANDLE hActCtx); https://msdn.microsoft.com/en-us/library/windows/desktop/aa374171(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)]
[PInvokeData("Winbase.h", MSDNShortId = "aa374171")]
public static extern void AddRefActCtx(IntPtr hActCtx);
/// <summary>Indicates that the calling application has completed its data recovery.</summary>
/// <param name="bSuccess">Specify TRUE to indicate that the data was successfully recovered; otherwise, FALSE.</param>
[DllImport(Lib.Kernel32, ExactSpelling = true)]
/// <param name="bSuccess">Specify <c>TRUE</c> to indicate that the data was successfully recovered; otherwise, <c>FALSE</c>.</param>
/// <returns>This function does not return a value.</returns>
// VOID WINAPI ApplicationRecoveryFinished( _In_ BOOL bSuccess); https://msdn.microsoft.com/en-us/library/windows/desktop/aa373328(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)]
[PInvokeData("Winbase.h", MSDNShortId = "aa373328")]
public static extern void ApplicationRecoveryFinished([MarshalAs(UnmanagedType.Bool)] bool bSuccess);
/// <summary>Indicates that the calling application is continuing to recover data.</summary>
/// <param name="pbCanceled">Indicates whether the user has canceled the recovery process. Set by WER if the user clicks the Cancel button.</param>
/// <returns>This function returns S_OK on success or one of the following error codes.</returns>
[DllImport(Lib.Kernel32, ExactSpelling = true)]
/// <returns>
/// <para>This function returns <c>S_OK</c> on success or one of the following error codes.</para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Return code</term>
/// <term>Description</term>
/// </listheader>
/// <item>
/// <term>E_FAIL</term>
/// <term>You can call this function only after Windows Error Reporting has called your recovery callback function.</term>
/// </item>
/// <item>
/// <term>E_INVALIDARG</term>
/// <term>The pbCancelled cannot be NULL.</term>
/// </item>
/// </list>
/// </para>
/// </returns>
// HRESULT WINAPI ApplicationRecoveryInProgress( _Out_ PBOOL pbCanceled); https://msdn.microsoft.com/en-us/library/windows/desktop/aa373329(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)]
[PInvokeData("Winbase.h", MSDNShortId = "aa373329")]
public static extern HRESULT ApplicationRecoveryInProgress([Out, MarshalAs(UnmanagedType.Bool)] out bool pbCanceled);
/// <summary>The CreateActCtx function creates an activation context.</summary>
/// <param name="actctx">Pointer to an ACTCTX structure that contains information about the activation context to be created.</param>
/// <returns>If the function succeeds, it returns a handle to the returned activation context. Otherwise, it returns INVALID_HANDLE_VALUE.</returns>
[DllImport(Lib.Kernel32, CharSet = CharSet.Auto, SetLastError = true)]
/// <summary>The <c>CreateActCtx</c> function creates an activation context.</summary>
/// <param name="pActCtx">Pointer to an <c>ACTCTX</c> structure that contains information about the activation context to be created.</param>
/// <returns>
/// <para>If the function succeeds, it returns a handle to the returned activation context. Otherwise, it returns INVALID_HANDLE_VALUE.</para>
/// <para>
/// This function sets errors that can be retrieved by calling <c>GetLastError</c>. For an example, see Retrieving the Last-Error Code. For a complete
/// list of error codes, see System Error Codes.
/// </para>
/// </returns>
// HANDLE CreateActCtx( _Inout_ PACTCTX pActCtx); https://msdn.microsoft.com/en-us/library/windows/desktop/aa375125(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)]
[PInvokeData("Winbase.h", MSDNShortId = "aa375125")]
public static extern ActCtxSafeHandle CreateActCtx(ref ACTCTX actctx);
/// <summary>The DeactivateActCtx function deactivates the activation context corresponding to the specified cookie.</summary>
/// <param name="dwFlags">Flags that indicate how the deactivation is to occur.</param>
/// <param name="lpCookie">
/// The ULONG_PTR that was passed into the call to ActivateActCtx. This value is used as a cookie to identify a specific activated activation context.
/// <summary>The <c>DeactivateActCtx</c> function deactivates the activation context corresponding to the specified cookie.</summary>
/// <param name="dwFlags">
/// <para>Flags that indicate how the deactivation is to occur.</para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Value</term>
/// <term>Meaning</term>
/// </listheader>
/// <item>
/// <term>0</term>
/// <term>
/// If this value is set and the cookie specified in the ulCookie parameter is in the top frame of the activation stack, the activation context is popped
/// from the stack and thereby deactivated. If this value is set and the cookie specified in the ulCookie parameter is not in the top frame of the
/// activation stack, this function searches down the stack for the cookie.If the cookie is found, a STATUS_SXS_EARLY_DEACTIVATION exception is thrown.If
/// the cookie is not found, a STATUS_SXS_INVALID_DEACTIVATION exception is thrown.This value should be specified in most cases.
/// </term>
/// </item>
/// <item>
/// <term>DEACTIVATE_ACTCTX_FLAG_FORCE_EARLY_DEACTIVATION</term>
/// <term>
/// If this value is set and the cookie specified in the ulCookie parameter is in the top frame of the activation stack, the function returns an
/// ERROR_INVALID_PARAMETER error code. Call GetLastError to obtain this code. If this value is set and the cookie is not on the activation stack, a
/// STATUS_SXS_INVALID_DEACTIVATION exception will be thrown.If this value is set and the cookie is in a lower frame of the activation stack, all of the
/// frames down to and including the frame the cookie is in is popped from the stack.
/// </term>
/// </item>
/// </list>
/// </para>
/// </param>
/// <returns>If the function succeeds, it returns TRUE. Otherwise, it returns FALSE. This function sets errors that can be retrieved by calling GetLastError.</returns>
[DllImport(Lib.Kernel32, ExactSpelling = true, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
/// <param name="ulCookie">
/// The ULONG_PTR that was passed into the call to <c>ActivateActCtx</c>. This value is used as a cookie to identify a specific activated activation context.
/// </param>
/// <returns>
/// <para>If the function succeeds, it returns <c>TRUE</c>. Otherwise, it returns <c>FALSE</c>.</para>
/// <para>
/// This function sets errors that can be retrieved by calling <c>GetLastError</c>. For an example, see Retrieving the Last-Error Code. For a complete
/// list of error codes, see System Error Codes.
/// </para>
/// </returns>
// BOOL DeactivateActCtx( _In_ DWORD dwFlags, _In_ ULONG_PTR ulCookie); https://msdn.microsoft.com/en-us/library/windows/desktop/aa375140(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("Winbase.h", MSDNShortId = "aa375140")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool DeactivateActCtx(DeactivateActCtxFlag dwFlags, IntPtr lpCookie);
/// <summary>
/// The <c>FindActCtxSectionGuid</c> function retrieves information on a specific GUID in the current activation context and returns a
/// <c>ACTCTX_SECTION_KEYED_DATA</c> structure.
/// </summary>
/// <param name="dwFlags">
/// <para>Flags that determine how this function is to operate. Only the following flag is currently defined.</para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Value</term>
/// <term>Meaning</term>
/// </listheader>
/// <item>
/// <term>FIND_ACTCTX_SECTION_KEY_RETURN_HACTCTX</term>
/// <term>
/// This function returns the activation context handle where the redirection data was found in the hActCtx member of the ACTCTX_SECTION_KEYED_DATA
/// structure. The caller must use ReleaseActCtx to release this activation context.
/// </term>
/// </item>
/// </list>
/// </para>
/// </param>
/// <param name="lpExtensionGuid">Reserved; must be null.</param>
/// <param name="ulSectionId">
/// <para>Identifier of the section of the activation context in which to search for the specified GUID.</para>
/// <para>The following are valid GUID section identifiers:</para>
/// <para>The following is a valid GUID section identifier beginning with Windows Server 2003 and Windows XP with SP1:</para>
/// </param>
/// <param name="lpGuidToFind">Pointer to a GUID to be used as the search criteria.</param>
/// <param name="ReturnedData">Pointer to an <c>ACTCTX_SECTION_KEYED_DATA</c> structure to be filled out with the requested GUID information.</param>
/// <returns>
/// <para>If the function succeeds, it returns <c>TRUE</c>. Otherwise, it returns <c>FALSE</c>.</para>
/// <para>
/// This function sets errors that can be retrieved by calling <c>GetLastError</c>. For an example, see Retrieving the Last-Error Code. For a complete
/// list of error codes, see System Error Codes.
/// </para>
/// </returns>
// BOOL FindActCtxSectionGuid( _In_ DWORD dwFlags, _In_ const GUID *lpExtensionGuid, _In_ ULONG ulSectionId, _In_ const GUID *lpGuidToFind, _Out_
// PACTCTX_SECTION_KEYED_DATA ReturnedData); https://msdn.microsoft.com/en-us/library/windows/desktop/aa375148(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("Winbase.h", MSDNShortId = "aa375148")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool FindActCtxSectionGuid(FIND_ACTCTX_SECTION dwFlags, [MarshalAs(UnmanagedType.LPStruct)] Guid lpExtensionGuid, uint ulSectionId, [MarshalAs(UnmanagedType.LPStruct)] Guid lpGuidToFind, out ACTCTX_SECTION_KEYED_DATA ReturnedData);
/// <summary>
/// The <c>FindActCtxSectionString</c> function retrieves information on a specific string in the current activation context and returns a
/// <c>ACTCTX_SECTION_KEYED_DATA</c> structure.
/// </summary>
/// <param name="dwFlags">
/// <para>Flags that determine how this function is to operate. Only the following flag is currently defined.</para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Value</term>
/// <term>Meaning</term>
/// </listheader>
/// <item>
/// <term>FIND_ACTCTX_SECTION_KEY_RETURN_HACTCTX</term>
/// <term>
/// This function returns the activation context handle where the redirection data was found in the hActCtx member of the ACTCTX_SECTION_KEYED_DATA
/// structure. The caller must use ReleaseActCtx to release this activation context.
/// </term>
/// </item>
/// </list>
/// </para>
/// </param>
/// <param name="lpExtensionGuid">Reserved; must be null.</param>
/// <param name="ulSectionId">
/// <para>Identifier of the string section of the activation context in which to search for the specific string.</para>
/// <para>The following are valid string section identifiers:</para>
/// </param>
/// <param name="lpStringToFind">Pointer to a null-terminated string to be used as the search criteria.</param>
/// <param name="ReturnedData">Pointer to an <c>ACTCTX_SECTION_KEYED_DATA</c> structure to be filled out with the requested string information.</param>
/// <returns>
/// <para>If the function succeeds, it returns <c>TRUE</c>. Otherwise, it returns <c>FALSE</c>.</para>
/// <para>
/// This function sets errors that can be retrieved by calling <c>GetLastError</c>. For an example, see Retrieving the Last-Error Code. For a complete
/// list of error codes, see System Error Codes.
/// </para>
/// </returns>
// BOOL FindActCtxSectionString( _In_ DWORD dwFlags, _In_ const GUID *lpExtensionGuid, _In_ ULONG ulSectionId, _In_ LPCTSTR lpStringToFind, _Out_
// PACTCTX_SECTION_KEYED_DATA ReturnedData); https://msdn.microsoft.com/en-us/library/windows/desktop/aa375149(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)]
[PInvokeData("Winbase.h", MSDNShortId = "aa375149")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool FindActCtxSectionString(FIND_ACTCTX_SECTION dwFlags, [MarshalAs(UnmanagedType.LPStruct)] Guid lpExtensionGuid, ACTCTX_SECTION ulSectionId, [In] string lpStringToFind, out ACTCTX_SECTION_KEYED_DATA ReturnedData);
/// <summary>
/// Retrieves a pointer to the callback routine registered for the specified process. The address returned is in the virtual address space of the process.
/// </summary>
/// <param name="hProcess">A handle to the process. This handle must have the PROCESS_VM_READ access right.</param>
/// <param name="pRecoveryCallback">A pointer to the recovery callback function. For more information, see ApplicationRecoveryCallback.</param>
/// <param name="pRecoveryCallback">A pointer to the recovery callback function. For more information, see <c>ApplicationRecoveryCallback</c>.</param>
/// <param name="ppvParameter">A pointer to the callback parameter.</param>
/// <param name="pdwPingInterval">The recovery ping interval, in 100-nanosecond intervals.</param>
/// <param name="pdwFlags">Reserved for future use.</param>
/// <returns>This function returns S_OK on success.</returns>
[DllImport(Lib.Kernel32, ExactSpelling = true)]
/// <returns>
/// <para>This function returns <c>S_OK</c> on success or one of the following error codes.</para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Return code</term>
/// <term>Description</term>
/// </listheader>
/// <item>
/// <term>S_FALSE</term>
/// <term>The application did not register for recovery.</term>
/// </item>
/// <item>
/// <term>E_INVALIDARG</term>
/// <term>One or more parameters are not valid.</term>
/// </item>
/// </list>
/// </para>
/// </returns>
// HRESULT WINAPI GetApplicationRecoveryCallback( _In_ HANDLE hProcess, _Out_ APPLICATION_RECOVERY_CALLBACK *pRecoveryCallback, _Out_ PVOID
// *ppvParameter, _Out_ PDWORD pdwPingInterval, _Out_ PDWORD pdwFlags); https://msdn.microsoft.com/en-us/library/windows/desktop/aa373343(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)]
[PInvokeData("Winbase.h", MSDNShortId = "aa373343")]
public static extern HRESULT GetApplicationRecoveryCallback(IntPtr hProcess, out ApplicationRecoveryCallback pRecoveryCallback, out IntPtr ppvParameter, out uint pdwPingInterval, out int pdwFlags);
/// <summary>Retrieves the restart information registered for the specified process.</summary>
/// <param name="hProcess">A handle to the process. This handle must have the PROCESS_VM_READ access right.</param>
/// <param name="pwzCommandline">
/// A pointer to a buffer that receives the restart command line specified by the application when it called the RegisterApplicationRestart function. The
/// maximum size of the command line, in characters, is RESTART_MAX_CMD_LINE. Can be NULL if pcchSize is zero.
/// A pointer to a buffer that receives the restart command line specified by the application when it called the <c>RegisterApplicationRestart</c>
/// function. The maximum size of the command line, in characters, is RESTART_MAX_CMD_LINE. Can be <c>NULL</c> if pcchSize is zero.
/// </param>
/// <param name="pcchSize">
/// On input, specifies the size of the pwzCommandLine buffer, in characters.
/// <para>On input, specifies the size of the pwzCommandLine buffer, in characters.</para>
/// <para>
/// If the buffer is not large enough to receive the command line, the function fails with HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER) and sets this
/// parameter to the required buffer size, in characters.
/// </para>
/// <para>On output, specifies the size of the buffer that was used.</para>
/// <para>
/// To determine the required buffer size, set pwzCommandLine to NULL and this parameter to zero. The size includes one for the null-terminator
/// character. Note that the function returns S_OK, not HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER) in this case.
/// To determine the required buffer size, set pwzCommandLine to <c>NULL</c> and this parameter to zero. The size includes one for the
/// <c>null</c>-terminator character. Note that the function returns S_OK, not HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER) in this case.
/// </para>
/// </param>
/// <param name="pdwFlags">
/// A pointer to a variable that receives the flags specified by the application when it called the RegisterApplicationRestart function.
/// A pointer to a variable that receives the flags specified by the application when it called the <c>RegisterApplicationRestart</c> function.
/// </param>
/// <returns>This function returns S_OK on success</returns>
[DllImport(Lib.Kernel32, ExactSpelling = true)]
/// <returns>
/// <para>This function returns <c>S_OK</c> on success or one of the following error codes.</para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Return code</term>
/// <term>Description</term>
/// </listheader>
/// <item>
/// <term>E_INVALIDARG</term>
/// <term>One or more parameters are not valid.</term>
/// </item>
/// <item>
/// <term>HRESULT_FROM_WIN32(ERROR_NOT_FOUND)</term>
/// <term>The application did not register for restart.</term>
/// </item>
/// <item>
/// <term>HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER)</term>
/// <term>
/// The pwzCommandLine buffer is too small. The function returns the required buffer size in pcchSize. Use the required size to reallocate the buffer.
/// </term>
/// </item>
/// </list>
/// </para>
/// </returns>
// HRESULT WINAPI GetApplicationRestartSettings( _In_ HANDLE hProcess, _Out_opt_ PWSTR pwzCommandline, _Inout_ PDWORD pcchSize, _Out_opt_ PDWORD
// pdwFlags); https://msdn.microsoft.com/en-us/library/windows/desktop/aa373344(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true, CharSet = CharSet.Unicode)]
[PInvokeData("Winbase.h", MSDNShortId = "aa373344")]
public static extern HRESULT GetApplicationRestartSettings(IntPtr hProcess, [MarshalAs(UnmanagedType.LPWStr)] StringBuilder pwzCommandline, ref uint pcchSize, out ApplicationRestartFlags pdwFlags);
public static extern HRESULT GetApplicationRestartSettings(IntPtr hProcess, [Out] StringBuilder pwzCommandline, ref uint pcchSize, out ApplicationRestartFlags pdwFlags);
/// <summary>The GetCurrentActCtx function returns the handle to the active activation context of the calling thread.</summary>
/// <param name="handle">Pointer to the returned ACTCTX structure that contains information on the active activation context.</param>
/// <returns>If the function succeeds, it returns TRUE. Otherwise, it returns FALSE. This function sets errors that can be retrieved by calling GetLastError.</returns>
[DllImport(Lib.Kernel32, ExactSpelling = true, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
/// <summary>The <c>GetCurrentActCtx</c> function returns the handle to the active activation context of the calling thread.</summary>
/// <param name="lphActCtx">Pointer to the returned <c>ACTCTX</c> structure that contains information on the active activation context.</param>
/// <returns>
/// <para>If the function succeeds, it returns <c>TRUE</c>. Otherwise, it returns <c>FALSE</c>.</para>
/// <para>
/// This function sets errors that can be retrieved by calling <c>GetLastError</c>. For an example, see Retrieving the Last-Error Code. For a complete
/// list of error codes, see System Error Codes.
/// </para>
/// </returns>
// BOOL GetCurrentActCtx( _Out_ HANDLE *lphActCtx); https://msdn.microsoft.com/en-us/library/windows/desktop/aa375152(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("Winbase.h", MSDNShortId = "aa375152")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetCurrentActCtx(out ActCtxSafeHandle handle);
/// <summary>
/// The <c>QueryActCtxSettingsW</c> function specifies the activation context, and the namespace and name of the attribute that is to be queried.
/// </summary>
/// <param name="dwFlags">This value must be 0.</param>
/// <param name="hActCtx">A handle to the activation context that is being queried.</param>
/// <param name="settingsNameSpace">
/// <para>
/// A pointer to a string that contains the value <c>"http://schemas.microsoft.com/SMI/2005/WindowsSettings"</c> or <c>NULL</c>. These values are equivalent.
/// </para>
/// <para>
/// <c>Windows 8 and Windows Server 2012:</c> A pointer to a string that contains the value
/// <c>"http://schemas.microsoft.com/SMI/2011/WindowsSettings"</c> is also a valid parameter. A <c>NULL</c> is still equivalent to the previous value.
/// </para>
/// </param>
/// <param name="settingName">The name of the attribute to be queried.</param>
/// <param name="pvBuffer">A pointer to the buffer that receives the query result.</param>
/// <param name="dwBuffer">The size of the buffer in characters that receives the query result.</param>
/// <param name="pdwWrittenOrRequired">
/// A pointer to a value which is the number of characters written to the buffer specified by pvBuffer or that is required to hold the query result.
/// </param>
/// <returns>
/// <para>If the function succeeds, it returns <c>TRUE</c>. Otherwise, it returns <c>FALSE</c>.</para>
/// <para>
/// This function sets errors that can be retrieved by calling <c>GetLastError</c>. For an example, see Retrieving the Last-Error Code. For a complete
/// list of error codes, see System Error Codes.
/// </para>
/// </returns>
// BOOL QueryActCtxSettingsW( _In_opt_ DWORD dwFlags, _In_opt_ HANDLE hActCtx, _In_opt_ PCWSTR settingsNameSpace, _In_ PCWSTR settingName, _Out_ PWSTR
// pvBuffer, _In_ SIZE_T dwBuffer, _Out_opt_ SIZE_T *pdwWrittenOrRequired); https://msdn.microsoft.com/en-us/library/windows/desktop/aa375700(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
[PInvokeData("Winbase.h", MSDNShortId = "aa375700")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool QueryActCtxSettingsW(QueryActCtxFlag dwFlags, [In] IntPtr hActCtx, string settingsNameSpace, string settingName, [Out] StringBuilder pvBuffer, SizeT dwBuffer, out SizeT pdwWrittenOrRequired);
/// <summary>The <c>QueryActCtxW</c> function queries the activation context.</summary>
/// <param name="dwFlags">
/// <para>This parameter should be set to one of the following flag bits.</para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Flag</term>
/// <term>Meaning</term>
/// </listheader>
/// <item>
/// <term>QUERY_ACTCTX_FLAG_USE_ACTIVE_ACTCTX</term>
/// <term>
/// QueryActCtxW queries the activation context active on the thread instead of the context specified by hActCtx. This is usually the last activation
/// context passed to ActivateActCtx. If ActivateActCtx has not been called, the active activation context can be the activation context used by the
/// executable of the current process. In other cases, the operating system determines the active activation context. For example, when the callback
/// function to a new thread is called, the active activation context may be the context that was active when you created the thread by calling CreateThread.
/// </term>
/// </item>
/// <item>
/// <term>QUERY_ACTCTX_FLAG_ACTCTX_IS_HMODULE</term>
/// <term>
/// QueryActCtxW interprets hActCtx as an HMODULE data type and queries an activation context that is associated with a DLL or EXE. When a DLL or EXE is
/// loaded, the loader checks for a manifest stored in a resource. If the loader finds an RT_MANIFEST resource with a resource identifier set to
/// ISOLATIONAWARE_MANIFEST_ RESOURCE_ID, the loader associates the resulting activation context with the DLL or EXE. This is the activation context that
/// QueryActCtxW queries when the QUERY_ACTCTX_FLAG_ACTCTX_IS_HMODULE flag has been set.
/// </term>
/// </item>
/// <item>
/// <term>QUERY_ACTCTX_FLAG_ACTCTX_IS_ADDRESS</term>
/// <term>
/// QueryActCtxW interprets hActCtx as an address within a DLL or EXE and queries an activation context that has been associated with the DLL or EXE.
/// This can be any address within the DLL or EXE. For example, the address of any function within a DLL or EXE or the address of any static data, such
/// as a constant string. When a DLL or EXE is loaded, the loader checks for a manifest stored in a resource in the same way as QUERY_ACTCTX_FLAG_ACTCTX_IS_HMODULE.
/// </term>
/// </item>
/// </list>
/// </para>
/// </param>
/// <param name="hActCtx">Handle to the activation context that is being queried.</param>
/// <param name="pvSubInstance">
/// <para>
/// Index of the assembly, or assembly and file combination, in the activation context. The meaning of the pvSubInstance depends on the option specified
/// by the value of the ulInfoClass parameter. This parameter may be null.
/// </para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>ulInfoClass Option</term>
/// <term>Meaning</term>
/// </listheader>
/// <item>
/// <term>AssemblyDetailedInformationInActivationContext</term>
/// <term>
/// Pointer to a DWORD that specifies the index of the assembly within the activation context. This is the activation context that QueryActCtxW queries.
/// </term>
/// </item>
/// <item>
/// <term>FileInformationInAssemblyOfAssemblyInActivationContext</term>
/// <term>
/// Pointer to an ACTIVATION_CONTEXT_QUERY_INDEX structure. If QueryActCtxW is called with this option and the function succeeds, the returned buffer
/// contains information for a file in the assembly. This information is in the form of the ASSEMBLY_FILE_DETAILED_INFORMATION structure.
/// </term>
/// </item>
/// </list>
/// </para>
/// </param>
/// <param name="ulInfoClass">
/// <para>This parameter can have only the values shown in the following table.</para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Option</term>
/// <term>Meaning</term>
/// </listheader>
/// <item>
/// <term>ActivationContextBasicInformation1</term>
/// <term>Not available.</term>
/// </item>
/// <item>
/// <term>ActivationContextDetailedInformation2</term>
/// <term>
/// If QueryActCtxW is called with this option and the function succeeds, the returned buffer contains detailed information about the activation context.
/// This information is in the form of the ACTIVATION_CONTEXT_DETAILED_INFORMATION structure.
/// </term>
/// </item>
/// <item>
/// <term>AssemblyDetailedInformationInActivationContext3</term>
/// <term>
/// If QueryActCtxW is called with this option and the function succeeds, the buffer contains information about the assembly that has the index specified
/// in pvSubInstance. This information is in the form of the ACTIVATION_CONTEXT_ASSEMBLY_DETAILED_INFORMATION structure.
/// </term>
/// </item>
/// <item>
/// <term>FileInformationInAssemblyOfAssemblyInActivationContext4</term>
/// <term>
/// Information about a file in one of the assemblies in Activation Context. The pvSubInstance parameter must point to an ACTIVATION_CONTEXT_QUERY_INDEX
/// structure. If QueryActCtxW is called with this option and the function succeeds, the returned buffer contains information for a file in the assembly.
/// This information is in the form of the ASSEMBLY_FILE_DETAILED_INFORMATION structure.
/// </term>
/// </item>
/// <item>
/// <term>RunlevelInformationInActivationContext5</term>
/// <term>
/// If QueryActCtxW is called with this option and the function succeeds, the buffer contains information about requested run level of the activation
/// context. This information is in the form of the ACTIVATION_CONTEXT_RUN_LEVEL_INFORMATION structure.Windows Server 2003 and Windows XP: This value is
/// not available.
/// </term>
/// </item>
/// <item>
/// <term>CompatibilityInformationInActivationContext6</term>
/// <term>
/// If QueryActCtxW is called with this option and the function succeeds, the buffer contains information about requested compatibility context. This
/// information is in the form of the ACTIVATION_CONTEXT_COMPATIBILITY_INFORMATION structure.Windows Server 2008 and earlier, and Windows Vista and
/// earlier: This value is not available. This option is available beginning with Windows Server 2008 R2 and Windows 7.
/// </term>
/// </item>
/// </list>
/// </para>
/// </param>
/// <param name="pvBuffer">
/// Pointer to a buffer that holds the returned information. This parameter is optional. If pvBuffer is <c>null</c>, then cbBuffer must be zero. If the
/// size of the buffer pointed to by pvBuffer is too small, <c>QueryActCtxW</c> returns ERROR_INSUFFICIENT_BUFFER and no data is written into the buffer.
/// See the Remarks section for the method you can use to determine the required size of the buffer.
/// </param>
/// <param name="cbBuffer">Size of the buffer in bytes pointed to by pvBuffer. This parameter is optional.</param>
/// <param name="pcbWrittenOrRequired">
/// Number of bytes written or required. The parameter pcbWrittenOrRequired can only be <c>NULL</c> when pvBuffer is <c>NULL</c>. If pcbWrittenOrRequired
/// is non- <c>NULL</c>, it is filled with the number of bytes required to store the returned buffer.
/// </param>
/// <returns>
/// <para>If the function succeeds, it returns <c>TRUE</c>. Otherwise, it returns <c>FALSE</c>.</para>
/// <para>
/// This function sets errors that can be retrieved by calling <c>GetLastError</c>. For an example, see Retrieving the Last-Error Code. For a complete
/// list of error codes, see System Error Codes.
/// </para>
/// </returns>
// BOOL QueryActCtxW( _In_ DWORD dwFlags, _In_ HANDLE hActCtx, _In_opt_ PVOID pvSubInstance, _In_ ULONG ulInfoClass, _Out_ PVOID pvBuffer, _In_opt_
// SIZE_T cbBuffer, _Out_opt_ SIZE_T *pcbWrittenOrRequired); https://msdn.microsoft.com/en-us/library/windows/desktop/aa375704(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("Winbase.h", MSDNShortId = "aa375704")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool QueryActCtxW(QueryActCtxFlag dwFlags, [In] IntPtr hActCtx, [In] IntPtr pvSubInstance, ACTIVATION_CONTEXT_INFO_CLASS ulInfoClass, IntPtr pvBuffer, SizeT cbBuffer, out SizeT pcbWrittenOrRequired);
/// <summary>Registers the active instance of an application for recovery.</summary>
/// <param name="pRecoveryCallback">A pointer to the recovery callback function. For more information, see ApplicationRecoveryCallback.</param>
/// <param name="pvParameter">A pointer to a variable to be passed to the callback function. Can be NULL.</param>
/// <param name="pRecoveryCallback">A pointer to the recovery callback function. For more information, see <c>ApplicationRecoveryCallback</c>.</param>
/// <param name="pvParameter">A pointer to a variable to be passed to the callback function. Can be <c>NULL</c>.</param>
/// <param name="dwPingInterval">
/// <para>
/// The recovery ping interval, in milliseconds. By default, the interval is 5 seconds (RECOVERY_DEFAULT_PING_INTERVAL). The maximum interval is 5
/// minutes. If you specify zero, the default interval is used.
/// </para>
/// <para>
/// You must call the ApplicationRecoveryInProgress function within the specified interval to indicate to ARR that you are still actively recovering;
/// otherwise, WER terminates recovery. Typically, you perform recovery in a loop with each iteration lasting no longer than the ping interval. Each
/// iteration performs a block of recovery work followed by a call to ApplicationRecoveryInProgress. Since you also use ApplicationRecoveryInProgress to
/// determine if the user wants to cancel recovery, you should consider a smaller interval, so you do not perform a lot of work unnecessarily.
/// You must call the <c>ApplicationRecoveryInProgress</c> function within the specified interval to indicate to ARR that you are still actively
/// recovering; otherwise, WER terminates recovery. Typically, you perform recovery in a loop with each iteration lasting no longer than the ping
/// interval. Each iteration performs a block of recovery work followed by a call to <c>ApplicationRecoveryInProgress</c>. Since you also use
/// <c>ApplicationRecoveryInProgress</c> to determine if the user wants to cancel recovery, you should consider a smaller interval, so you do not perform
/// a lot of work unnecessarily.
/// </para>
/// </param>
/// <param name="dwFlags">Reserved for future use. Set to zero.</param>
/// <returns>This function returns S_OK on success</returns>
[DllImport(Lib.Kernel32, ExactSpelling = true)]
/// <returns>
/// <para>This function returns <c>S_OK</c> on success or one of the following error codes.</para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Return code</term>
/// <term>Description</term>
/// </listheader>
/// <item>
/// <term>E_FAIL</term>
/// <term>Internal error; the registration failed.</term>
/// </item>
/// <item>
/// <term>E_INVALIDARG</term>
/// <term>The ping interval cannot be more than five minutes.</term>
/// </item>
/// </list>
/// </para>
/// </returns>
// HRESULT WINAPI RegisterApplicationRecoveryCallback( _In_ APPLICATION_RECOVERY_CALLBACK pRecoveryCallback, _In_opt_ PVOID pvParameter, _In_ DWORD
// dwPingInterval, _In_ DWORD dwFlags); https://msdn.microsoft.com/en-us/library/windows/desktop/aa373345(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)]
[PInvokeData("Winbase.h", MSDNShortId = "aa373345")]
public static extern HRESULT RegisterApplicationRecoveryCallback(ApplicationRecoveryCallback pRecoveryCallback, IntPtr pvParameter, uint dwPingInterval, uint dwFlags);
/// <summary>Registers the active instance of an application for restart.</summary>
/// <param name="pwzCommandline">
/// A string that specifies the command-line arguments for the application when it is restarted. The maximum size of the command line that you can
/// specify is RESTART_MAX_CMD_LINE characters. Do not include the name of the executable in the command line; this function adds it for you.
/// <para>
/// If this parameter is NULL or an empty string, the previously registered command line is removed. If the argument contains spaces, use quotes around
/// the argument.
/// A pointer to a Unicode string that specifies the command-line arguments for the application when it is restarted. The maximum size of the command
/// line that you can specify is RESTART_MAX_CMD_LINE characters. Do not include the name of the executable in the command line; this function adds it
/// for you.
/// </para>
/// <para>
/// If this parameter is <c>NULL</c> or an empty string, the previously registered command line is removed. If the argument contains spaces, use quotes
/// around the argument.
/// </para>
/// </param>
/// <param name="dwFlags">Options</param>
/// <returns>This function returns S_OK on success</returns>
[DllImport(Lib.Kernel32, ExactSpelling = true)]
[PInvokeData("Winbase.h", MSDNShortId = "aa373347")]
public static extern HRESULT RegisterApplicationRestart([MarshalAs(UnmanagedType.BStr)] string pwzCommandline, ApplicationRestartFlags dwFlags);
/// <summary>The ReleaseActCtx function decrements the reference count of the specified activation context.</summary>
/// <param name="hActCtx">
/// Handle to the ACTCTX structure that contains information on the activation context for which the reference count is to be decremented.
/// <param name="dwFlags">
/// <para>This parameter can be 0 or one or more of the following values.</para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Value</term>
/// <term>Meaning</term>
/// </listheader>
/// <item>
/// <term>RESTART_NO_CRASH1</term>
/// <term>Do not restart the process if it terminates due to an unhandled exception.</term>
/// </item>
/// <item>
/// <term>RESTART_NO_HANG2</term>
/// <term>Do not restart the process if it terminates due to the application not responding.</term>
/// </item>
/// <item>
/// <term>RESTART_NO_PATCH4</term>
/// <term>Do not restart the process if it terminates due to the installation of an update.</term>
/// </item>
/// <item>
/// <term>RESTART_NO_REBOOT8</term>
/// <term>Do not restart the process if the computer is restarted as the result of an update.</term>
/// </item>
/// </list>
/// </para>
/// </param>
[DllImport(Lib.Kernel32, ExactSpelling = true, SetLastError = true)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
/// <returns>
/// <para>This function returns <c>S_OK</c> on success or one of the following error codes.</para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Return code</term>
/// <term>Description</term>
/// </listheader>
/// <item>
/// <term>E_FAIL</term>
/// <term>Internal error.</term>
/// </item>
/// <item>
/// <term>E_INVALIDARG</term>
/// <term>The specified command line is too long.</term>
/// </item>
/// </list>
/// </para>
/// </returns>
// HRESULT WINAPI RegisterApplicationRestart( _In_opt_ PCWSTR pwzCommandline, _In_ DWORD dwFlags); https://msdn.microsoft.com/en-us/library/windows/desktop/aa373347(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true, CharSet = CharSet.Unicode)]
[PInvokeData("Winbase.h", MSDNShortId = "aa373347")]
public static extern HRESULT RegisterApplicationRestart(string pwzCommandline, ApplicationRestartFlags dwFlags);
/// <summary>The <c>ReleaseActCtx</c> function decrements the reference count of the specified activation context.</summary>
/// <param name="hActCtx">
/// Handle to the <c>ACTCTX</c> structure that contains information on the activation context for which the reference count is to be decremented.
/// </param>
/// <returns>
/// This function does not return a value. On successful completion, the activation context reference count is decremented. The recipient of the
/// reference-counted object must decrement the reference count when the object is no longer required.
/// </returns>
// void ReleaseActCtx( _In_ HANDLE hActCtx); https://msdn.microsoft.com/en-us/library/windows/desktop/aa375713(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)]
[PInvokeData("Winbase.h", MSDNShortId = "aa375713")]
public static extern void ReleaseActCtx(IntPtr hActCtx);
/// <summary>Removes the active instance of an application from the recovery list.</summary>
/// <remarks>You do not need to call this function before exiting. You need to remove the registration only if you choose to not recover data.</remarks>
/// <returns>This function returns S_OK on success</returns>
[DllImport(Lib.Kernel32, ExactSpelling = true)]
/// <param name="RegisterApplicationRecoveryCallback"></param>
/// <returns>
/// <para>This function returns <c>S_OK</c> on success or one of the following error codes.</para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Return code</term>
/// <term>Description</term>
/// </listheader>
/// <item>
/// <term>E_FAIL</term>
/// <term>Internal error.</term>
/// </item>
/// </list>
/// </para>
/// </returns>
// HRESULT WINAPI UnregisterApplicationRecoveryCallback(void); https://msdn.microsoft.com/en-us/library/windows/desktop/aa373348(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)]
[PInvokeData("Winbase.h", MSDNShortId = "aa373348")]
public static extern HRESULT UnregisterApplicationRecoveryCallback();
@ -248,6 +843,24 @@ namespace Vanara.PInvoke
[PInvokeData("Winbase.h", MSDNShortId = "aa373349")]
public static extern HRESULT UnregisterApplicationRestart();
/// <summary>The <c>ZombifyActCtx</c> function deactivates the specified activation context, but does not deallocate it.</summary>
/// <param name="hActCtx">Handle to the activation context that is to be deactivated.</param>
/// <returns>
/// <para>
/// If the function succeeds, it returns <c>TRUE</c>. If a <c>null</c> handle is passed in the hActCtx parameter, NULL_INVALID_PARAMETER will be
/// returned. Otherwise, it returns <c>FALSE</c>.
/// </para>
/// <para>
/// This function sets errors that can be retrieved by calling <c>GetLastError</c>. For an example, see Retrieving the Last-Error Code. For a complete
/// list of error codes, see System Error Codes.
/// </para>
/// </returns>
// BOOL ZombifyActCtx( _In_ HANDLE hActCtx); https://msdn.microsoft.com/en-us/library/windows/desktop/aa376622(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("Winbase.h", MSDNShortId = "aa376622")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool ZombifyActCtx(IntPtr hActCtx);
/// <summary>The ACTCTX structure is used by the CreateActCtx function to create the activation context.</summary>
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
[PInvokeData("Winbase.h", MSDNShortId = "aa374149")]
@ -328,6 +941,98 @@ namespace Vanara.PInvoke
public static ACTCTX Empty = new ACTCTX { cbSize = Marshal.SizeOf(typeof(ACTCTX)) };
}
/// <summary>
/// The <c>ACTCTX_SECTION_KEYED_DATA</c> structure is used by the <c>FindActCtxSectionString</c> and <c>FindActCtxSectionGuid</c> functions to return the
/// activation context information along with either the GUID or 32-bit integer-tagged activation context section.
/// </summary>
// typedef struct tagACTCTX_SECTION_KEYED_DATA { ULONG cbSize; ULONG ulDataFormatVersion; PVOID lpData; ULONG ulLength; PVOID lpSectionGlobalData; ULONG
// ulSectionGlobalDataLength; PVOID lpSectionBase; ULONG ulSectionTotalLength; HANDLE hActCtx; HANDLE ulAssemblyRosterIndex;} ACTCTX_SECTION_KEYED_DATA, *PACTCTX_SECTION_KEYED_DATA;
[StructLayout(LayoutKind.Sequential)]
[PInvokeData("Winbase.h", MSDNShortId = "aa374148")]
public struct ACTCTX_SECTION_KEYED_DATA
{
/// <summary>
/// <para>The size, in bytes, of the activation context keyed data structure.</para>
/// </summary>
public uint cbSize;
/// <summary>
/// <para>
/// Number that indicates the format of the data in the section where the key was found. Clients should verify that the data format version is as
/// expected rather than trying to interpret the values of unfamiliar data formats. This number is only changed when major non-backward-compatible
/// changes to the section data formats need to be made. The current format version is 1.
/// </para>
/// </summary>
public uint ulDataFormatVersion;
/// <summary>
/// <para>Pointer to the redirection data found associated with the section identifier and key.</para>
/// </summary>
public IntPtr lpData;
/// <summary>
/// <para>
/// Number of bytes in the structure referred to by <c>lpData</c>. Note that the data structures grow over time; do not access members in the
/// instance data that extend beyond <c>ulLength</c>.
/// </para>
/// </summary>
public uint ulLength;
/// <summary>
/// <para>
/// Returned pointer to a section-specific data structure which is global to the activation context section where the key was found. Its
/// interpretation depends on the section identifier requested.
/// </para>
/// </summary>
public IntPtr lpSectionGlobalData;
/// <summary>
/// <para>Number of bytes in the section global data block referred to by <c>lpSectionGlobalData</c>.</para>
/// <para>
/// Note that the data structures grow over time and you may receive an old format activation context data block; do not access members in the
/// section global data that extend beyond <c>ulSectionGlobalDataLength</c>.
/// </para>
/// </summary>
public uint ulSectionGlobalDataLength;
/// <summary>
/// <para>
/// Pointer to the base of the section where the key was found. Some instance data contains offsets relative to the section base address, in which
/// case this pointer value is used.
/// </para>
/// </summary>
public IntPtr lpSectionBase;
/// <summary>
/// <para>
/// Number of bytes for the entire section starting at <c>lpSectionBase</c>. May be used to verify that offset/length pairs, which are specified as
/// relative to the section base are wholly contained in the section.
/// </para>
/// </summary>
public uint ulSectionTotalLength;
/// <summary>
/// <para>
/// Handle to the activation context where the key was found. First, the active activation context for the thread is searched, followed by the
/// process-default activation context and then the system-compatible-default-activation context. This member indicates which activation context
/// contained the section and key requested. This is only returned if the FIND_ACTCTX_SECTION_KEY_RETURN_HACTCTX flag is passed.
/// </para>
/// <para>
/// Note that when this is returned, the caller must call <c>ReleaseActCtx</c>() on the activation context handle returned to release system
/// resources when all other references to the activation context have been released.
/// </para>
/// </summary>
public IntPtr hActCtx;
/// <summary>
/// <para>
/// Cardinal number of the assembly in the activation context that provided the redirection information found. This value can be presented to
/// <c>QueryActCtxW</c> for more information about the contributing assembly.
/// </para>
/// </summary>
public uint ulAssemblyRosterIndex;
}
/// <summary>A safe handle for an Activation Context.</summary>
/// <seealso cref="GenericSafeHandle"/>
[PInvokeData("Winbase.h")]

View File

@ -0,0 +1,204 @@
using System.Runtime.InteropServices;
using System.Text;
namespace Vanara.PInvoke
{
public static partial class Kernel32
{
/// <summary>Adds a character string to the local atom table and returns a unique value (an atom) identifying the string.</summary>
/// <param name="lpString">
/// <para>Type: <c>LPCTSTR</c></para>
/// <para>
/// The null-terminated string to be added. The string can have a maximum size of 255 bytes. Strings differing only in case are considered identical. The
/// case of the first string added is preserved and returned by the <c>GetAtomName</c> function.
/// </para>
/// <para>Alternatively, you can use an integer atom that has been converted using the <c>MAKEINTATOM</c> macro. See the Remarks for more information.</para>
/// </param>
/// <returns>
/// <para>Type: <c>ATOM</c></para>
/// <para>If the function succeeds, the return value is the newly created atom.</para>
/// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// ATOM WINAPI AddAtom( _In_ LPCTSTR lpString); https://msdn.microsoft.com/en-us/library/windows/desktop/ms649056(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)]
[PInvokeData("Winbase.h", MSDNShortId = "ms649056")]
public static extern ushort AddAtom([In] string lpString);
/// <summary>
/// Decrements the reference count of a local string atom. If the atom's reference count is reduced to zero, <c>DeleteAtom</c> removes the string
/// associated with the atom from the local atom table.
/// </summary>
/// <param name="nAtom">
/// <para>Type: <c>ATOM</c></para>
/// <para>The atom to be deleted.</para>
/// </param>
/// <returns>
/// <para>Type: <c>ATOM</c></para>
/// <para>If the function succeeds, the return value is zero.</para>
/// <para>If the function fails, the return value is the nAtom parameter. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// ATOM WINAPI DeleteAtom( _In_ ATOM nAtom); https://msdn.microsoft.com/en-us/library/windows/desktop/ms649057(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("Winbase.h", MSDNShortId = "ms649057")]
public static extern ushort DeleteAtom(ushort nAtom);
/// <summary>Searches the local atom table for the specified character string and retrieves the atom associated with that string.</summary>
/// <param name="lpString">
/// <para>Type: <c>LPCTSTR</c></para>
/// <para>The character string for which to search.</para>
/// <para>Alternatively, you can use an integer atom that has been converted using the <c>MAKEINTATOM</c> macro. See Remarks for more information.</para>
/// </param>
/// <returns>
/// <para>Type: <c>ATOM</c></para>
/// <para>If the function succeeds, the return value is the atom associated with the given string.</para>
/// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// ATOM WINAPI FindAtom( _In_ LPCTSTR lpString); https://msdn.microsoft.com/en-us/library/windows/desktop/ms649058(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)]
[PInvokeData("Winbase.h", MSDNShortId = "ms649058")]
public static extern ushort FindAtom([In] string lpString);
/// <summary>Retrieves a copy of the character string associated with the specified local atom.</summary>
/// <param name="nAtom">
/// <para>Type: <c>ATOM</c></para>
/// <para>The local atom that identifies the character string to be retrieved.</para>
/// </param>
/// <param name="lpBuffer">
/// <para>Type: <c>LPTSTR</c></para>
/// <para>The character string.</para>
/// </param>
/// <param name="nSize">
/// <para>Type: <c>int</c></para>
/// <para>The size, in characters, of the buffer.</para>
/// </param>
/// <returns>
/// <para>Type: <c>UINT</c></para>
/// <para>
/// If the function succeeds, the return value is the length of the string copied to the buffer, in characters, not including the terminating null character.
/// </para>
/// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// UINT WINAPI GetAtomName( _In_ ATOM nAtom, _Out_ LPTSTR lpBuffer, _In_ int nSize); https://msdn.microsoft.com/en-us/library/windows/desktop/ms649059(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)]
[PInvokeData("Winbase.h", MSDNShortId = "ms649059")]
public static extern uint GetAtomName(ushort nAtom, [Out] StringBuilder lpBuffer, int nSize);
/// <summary>Adds a character string to the global atom table and returns a unique value (an atom) identifying the string.</summary>
/// <param name="lpString">
/// <para>Type: <c>LPCTSTR</c></para>
/// <para>
/// The null-terminated string to be added. The string can have a maximum size of 255 bytes. Strings that differ only in case are considered identical.
/// The case of the first string of this name added to the table is preserved and returned by the <c>GlobalGetAtomName</c> function.
/// </para>
/// <para>Alternatively, you can use an integer atom that has been converted using the <c>MAKEINTATOM</c> macro. See the Remarks for more information.</para>
/// </param>
/// <returns>
/// <para>Type: <c>ATOM</c></para>
/// <para>If the function succeeds, the return value is the newly created atom.</para>
/// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// ATOM WINAPI GlobalAddAtom( _In_ LPCTSTR lpString); https://msdn.microsoft.com/en-us/library/windows/desktop/ms649060(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)]
[PInvokeData("Winbase.h", MSDNShortId = "ms649060")]
public static extern ushort GlobalAddAtom([In] string lpString);
/// <summary>Adds a character string to the global atom table and returns a unique value (an atom) identifying the string.</summary>
/// <param name="lpString">
/// <para>Type: <c>LPCTSTR</c></para>
/// <para>
/// The null-terminated string to be added. The string can have a maximum size of 255 bytes. Strings that differ only in case are considered identical.
/// The case of the first string of this name added to the table is preserved and returned by the <c>GlobalGetAtomName</c> function.
/// </para>
/// <para>Alternatively, you can use an integer atom that has been converted using the <c>MAKEINTATOM</c> macro. See the Remarks for more information.</para>
/// </param>
/// <param name="Flags">The flags.</param>
/// <returns>
/// <para>Type: <c>ATOM</c></para>
/// <para>If the function succeeds, the return value is the newly created atom.</para>
/// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// ATOM WINAPI GlobalAddAtom( _In_ LPCTSTR lpString); https://msdn.microsoft.com/en-us/library/windows/desktop/dn764994(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)]
[PInvokeData("Winbase.h", MSDNShortId = "dn764994")]
public static extern ushort GlobalAddAtomEx([In] string lpString, uint Flags);
/// <summary>
/// Decrements the reference count of a global string atom. If the atom's reference count reaches zero, <c>GlobalDeleteAtom</c> removes the string
/// associated with the atom from the global atom table.
/// </summary>
/// <param name="nAtom">
/// <para>Type: <c>ATOM</c></para>
/// <para>The atom and character string to be deleted.</para>
/// </param>
/// <returns>
/// <para>Type: <c>ATOM</c></para>
/// <para>The function always returns ( <c>ATOM</c>) 0.</para>
/// <para>
/// To determine whether the function has failed, call <c>SetLastError</c> with <c>ERROR_SUCCESS</c> before calling <c>GlobalDeleteAtom</c>, then call
/// <c>GetLastError</c>. If the last error code is still <c>ERROR_SUCCESS</c>, <c>GlobalDeleteAtom</c> has succeeded.
/// </para>
/// </returns>
// ATOM WINAPI GlobalDeleteAtom( _In_ ATOM nAtom); https://msdn.microsoft.com/en-us/library/windows/desktop/ms649061(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("Winbase.h", MSDNShortId = "ms649061")]
public static extern ushort GlobalDeleteAtom(ushort nAtom);
/// <summary>Searches the global atom table for the specified character string and retrieves the global atom associated with that string.</summary>
/// <param name="lpString">
/// <para>Type: <c>LPCTSTR</c></para>
/// <para>The null-terminated character string for which to search.</para>
/// <para>Alternatively, you can use an integer atom that has been converted using the <c>MAKEINTATOM</c> macro. See the Remarks for more information.</para>
/// </param>
/// <returns>
/// <para>Type: <c>ATOM</c></para>
/// <para>If the function succeeds, the return value is the global atom associated with the given string.</para>
/// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// ATOM WINAPI GlobalFindAtom( _In_ LPCTSTR lpString); https://msdn.microsoft.com/en-us/library/windows/desktop/ms649062(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)]
[PInvokeData("Winbase.h", MSDNShortId = "ms649062")]
public static extern ushort GlobalFindAtom([In] string lpString);
/// <summary>Retrieves a copy of the character string associated with the specified global atom.</summary>
/// <param name="nAtom">
/// <para>Type: <c>ATOM</c></para>
/// <para>The global atom associated with the character string to be retrieved.</para>
/// </param>
/// <param name="lpBuffer">
/// <para>Type: <c>LPTSTR</c></para>
/// <para>The buffer for the character string.</para>
/// </param>
/// <param name="nSize">
/// <para>Type: <c>int</c></para>
/// <para>The size, in characters, of the buffer.</para>
/// </param>
/// <returns>
/// <para>Type: <c>UINT</c></para>
/// <para>
/// If the function succeeds, the return value is the length of the string copied to the buffer, in characters, not including the terminating null character.
/// </para>
/// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// UINT WINAPI GlobalGetAtomName( _In_ ATOM nAtom, _Out_ LPTSTR lpBuffer, _In_ int nSize); https://msdn.microsoft.com/en-us/library/windows/desktop/ms649063(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)]
[PInvokeData("Winbase.h", MSDNShortId = "ms649063")]
public static extern uint GlobalGetAtomName(ushort nAtom, [Out] StringBuilder lpBuffer, int nSize);
/// <summary>Initializes the local atom table and sets the number of hash buckets to the specified size.</summary>
/// <param name="nSize">
/// <para>Type: <c>DWORD</c></para>
/// <para>The number of hash buckets to use for the atom table. If this parameter is zero, the default number of hash buckets are created.</para>
/// <para>To achieve better performance, specify a prime number in nSize.</para>
/// </param>
/// <returns>
/// <para>Type: <c>BOOL</c></para>
/// <para>If the function succeeds, the return value is nonzero.</para>
/// <para>If the function fails, the return value is zero.</para>
/// </returns>
// BOOL WINAPI InitAtomTable( _In_ DWORD nSize); https://msdn.microsoft.com/en-us/library/windows/desktop/ms649064(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)]
[PInvokeData("Winbase.h", MSDNShortId = "ms649064")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool InitAtomTable(uint nSize);
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,131 @@
using System;
using System.Runtime.InteropServices;
namespace Vanara.PInvoke
{
public static partial class Kernel32
{
/// <summary>
/// Causes a breakpoint exception to occur in the specified process. This allows the calling thread to signal the debugger to handle the exception.
/// </summary>
/// <param name="Process">A handle to the process.</param>
/// <returns>
/// <para>If the function succeeds, the return value is nonzero.</para>
/// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// BOOL WINAPI DebugBreakProcess( _In_ HANDLE Process);
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms679298(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms679298")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool DebugBreakProcess([In] IntPtr Process);
/// <summary>Sets the action to be performed when the calling thread exits.</summary>
/// <param name="KillOnExit">
/// If this parameter is <c>TRUE</c>, the thread terminates all attached processes on exit (note that this is the default). Otherwise, the thread
/// detaches from all processes being debugged on exit.
/// </param>
/// <returns>
/// <para>If the function succeeds, the return value is nonzero.</para>
/// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// BOOL WINAPI DebugSetProcessKillOnExit( _In_ BOOL KillOnExit); https://msdn.microsoft.com/en-us/library/windows/desktop/ms679307(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms679307")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool DebugSetProcessKillOnExit([MarshalAs(UnmanagedType.Bool)] bool KillOnExit);
/// <summary>Transfers execution control to the debugger. The behavior of the debugger thereafter is specific to the type of debugger used.</summary>
/// <param name="ExitCode">The error code associated with the exit.</param>
/// <returns>This function does not return a value.</returns>
// void WINAPI FatalExit( _In_ int ExitCode);
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms679337(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms679337")]
public static extern void FatalExit(int ExitCode);
/// <summary>Retrieves a descriptor table entry for the specified selector and thread.</summary>
/// <param name="hThread">
/// A handle to the thread containing the specified selector. The handle must have THREAD_QUERY_INFORMATION access. For more information, see Thread
/// Security and Access Rights.
/// </param>
/// <param name="dwSelector">The global or local selector value to look up in the thread's descriptor tables.</param>
/// <param name="lpSelectorEntry">
/// A pointer to an <c>LDT_ENTRY</c> structure that receives a copy of the descriptor table entry if the specified selector has an entry in the specified
/// thread's descriptor table. This information can be used to convert a segment-relative address to a linear virtual address.
/// </param>
/// <returns>
/// <para>
/// If the function succeeds, the return value is nonzero. In that case, the structure pointed to by the lpSelectorEntry parameter receives a copy of the
/// specified descriptor table entry.
/// </para>
/// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// BOOL WINAPI GetThreadSelectorEntry( _In_ HANDLE hThread, _In_ DWORD dwSelector, _Out_ LPLDT_ENTRY lpSelectorEntry);
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms679363(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms679363")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetThreadSelectorEntry([In] IntPtr hThread, uint dwSelector, out LDT_ENTRY lpSelectorEntry);
/// <summary>Describes an entry in the descriptor table. This structure is valid only on x86-based systems.</summary>
// typedef struct _LDT_ENTRY { WORD LimitLow; WORD BaseLow; union { struct { BYTE BaseMid; BYTE Flags1; BYTE Flags2; BYTE BaseHi; } Bytes; struct { DWORD BaseMid :8; DWORD Type :5; DWORD Dpl :2; DWORD Pres :1; DWORD LimitHi :4; DWORD Sys :1; DWORD Reserved_0 :1; DWORD Default_Big :1; DWORD Granularity :1; DWORD BaseHi :8; } Bits; } HighWord;} LDT_ENTRY, *PLDT_ENTRY;
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms680348(v=vs.85).aspx
[PInvokeData("WinNT.h", MSDNShortId = "ms680348")]
[StructLayout(LayoutKind.Sequential, Pack = 2)]
public struct LDT_ENTRY
{
/// <summary>The low-order part of the address of the last byte in the segment.</summary>
public ushort LimitLow;
/// <summary>The low-order part of the base address of the segment.</summary>
public ushort BaseLow;
private uint bits;
/// <summary>The middle bits (16–23) of the base address of the segment.</summary>
public byte BaseMid { get => GetBits(0, 8); set => SetBits(0, 8, value); }
/// <summary>The type of segment. This member can be one of the following values:
/// <list type="bullet">
/// <item><term>0: Read-only data segment</term></item>
/// <item><term>1: Read-write data segment</term></item>
/// <item><term>2: Unused segment</term></item>
/// <item><term>3: Read-write expand-down data segment</term></item>
/// <item><term>4: Execute-only code segment</term></item>
/// <item><term>5: Executable-readable code segment</term></item>
/// <item><term>6: Execute-only "conforming" code segment</term></item>
/// <item><term>7: Executable-readable "conforming" code segment</term></item>
/// </list></summary>
public byte Type { get => GetBits(8, 5); set => SetBits(8, 5, value); }
/// <summary>The privilege level of the descriptor. This member is an integer value in the range 0 (most privileged) through 3 (least privileged).</summary>
public byte Dpl { get => GetBits(13, 2); set => SetBits(13, 2, value); }
/// <summary>The present flag. This member is 1 if the segment is present in physical memory or 0 if it is not.</summary>
public byte Pres { get => GetBits(15, 1); set => SetBits(15, 1, value); }
/// <summary>The high bits (16–19) of the address of the last byte in the segment.</summary>
public byte LimitHi { get => GetBits(16, 4); set => SetBits(16, 4, value); }
/// <summary>The space that is available to system programmers. This member might be used for marking segments in some system-specific way.</summary>
public byte Sys { get => GetBits(20, 1); set => SetBits(20, 1, value); }
/// <summary>Reserved.</summary>
public byte Reserved_0 { get => GetBits(21, 1); set => SetBits(21, 1, value); }
/// <summary>The size of segment. If the segment is a data segment, this member contains 1 if the segment is larger than 64 kilobytes (K) or 0 if the segment is smaller than or equal to 64K.
/// <para>If the segment is a code segment, this member contains 1 if the segment is a code segment and runs with the default (native mode) instruction set.This member contains 0 if the code segment is an 80286 code segment and runs with 16-bit offsets and the 80286-compatible instruction set.</para></summary>
public byte Default_Big { get => GetBits(22, 1); set => SetBits(22, 1, value); }
/// <summary>The granularity. This member contains 0 if the segment is byte granular, 1 if the segment is page granular.</summary>
public byte Granularity { get => GetBits(23, 1); set => SetBits(23, 1, value); }
/// <summary>The high bits (24–31) of the base address of the segment.</summary>
public byte BaseHi { get => GetBits(24, 8); set => SetBits(24, 8, value); }
private byte GetBits(int offset, int len) => (byte)((bits & (((1 << len) - 1) << offset)) >> offset);
private void SetBits(int offset, int len, byte value) { var mask = (uint)(((1 << len) - 1) << offset); bits = (bits & ~mask) | (uint)(value << offset); }
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,81 @@
using System;
using System.Runtime.InteropServices;
using System.Text;
namespace Vanara.PInvoke
{
public static partial class Kernel32
{
/// <summary>Retrieves the application-specific portion of the search path used to locate DLLs for the application.</summary>
/// <param name="nBufferLength">The size of the output buffer, in characters.</param>
/// <param name="lpBuffer">A pointer to a buffer that receives the application-specific portion of the search path.</param>
/// <returns>
/// <para>
/// If the function succeeds, the return value is the length of the string copied to lpBuffer, in characters, not including the terminating null
/// character. If the return value is greater than nBufferLength, it specifies the size of the buffer required for the path.
/// </para>
/// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// DWORD WINAPI GetDllDirectory( _In_ DWORD nBufferLength, _Out_ LPTSTR lpBuffer); https://msdn.microsoft.com/en-us/library/windows/desktop/ms683186(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)]
[PInvokeData("WinBase.h", MSDNShortId = "ms683186")]
public static extern uint GetDllDirectory(uint nBufferLength, [Out] StringBuilder lpBuffer);
/// <summary>Loads and executes an application or creates a new instance of an existing application.</summary>
/// <param name="lpModuleName">
/// The file name of the application to be run. When specifying a path, be sure to use backslashes (\), not forward slashes (/). If the lpModuleName
/// parameter does not contain a directory path, the system searches for the executable file in this order:
/// </param>
/// <param name="lpParameterBlock">
/// A pointer to an application-defined <c>LOADPARMS32</c> structure that defines the new application's parameter block. Set all unused members to NULL,
/// except for <c>lpCmdLine</c>, which must point to a null-terminated string if it is not used. For more information, see Remarks.
/// </param>
/// <returns>
/// <para>If the function succeeds, the return value is greater than 31.</para>
/// <para>If the function fails, the return value is an error value, which may be one of the following values.</para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Return code/value</term>
/// <term>Description</term>
/// </listheader>
/// <item>
/// <term>0</term>
/// <term>The system is out of memory or resources.</term>
/// </item>
/// <item>
/// <term>ERROR_BAD_FORMAT11L</term>
/// <term>The .exe file is invalid.</term>
/// </item>
/// <item>
/// <term>ERROR_FILE_NOT_FOUND2L</term>
/// <term>The specified file was not found.</term>
/// </item>
/// <item>
/// <term>ERROR_PATH_NOT_FOUND3L</term>
/// <term>The specified path was not found.</term>
/// </item>
/// </list>
/// </para>
/// </returns>
// DWORD WINAPI LoadModule( _In_ LPCSTR lpModuleName, _In_ LPVOID lpParameterBlock); https://msdn.microsoft.com/en-us/library/windows/desktop/ms684183(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true, CharSet = CharSet.Ansi)]
[PInvokeData("Winbase.h", MSDNShortId = "ms684183")]
public static extern Win32Error LoadModule([In] string lpModuleName, [In] IntPtr lpParameterBlock);
/// <summary>Adds a directory to the search path used to locate DLLs for the application.</summary>
/// <param name="lpPathName">
/// The directory to be added to the search path. If this parameter is an empty string (""), the call removes the current directory from the default DLL
/// search order. If this parameter is NULL, the function restores the default search order.
/// </param>
/// <returns>
/// <para>If the function succeeds, the return value is nonzero.</para>
/// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// BOOL WINAPI SetDllDirectory( _In_opt_ LPCTSTR lpPathName); https://msdn.microsoft.com/en-us/library/windows/desktop/ms686203(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)]
[PInvokeData("Winbase.h", MSDNShortId = "ms686203")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetDllDirectory([In] string lpPathName);
}
}

View File

@ -0,0 +1,139 @@
using System;
using System.Runtime.InteropServices;
namespace Vanara.PInvoke
{
public static partial class Kernel32
{
/// <summary>Waits forever for a message.</summary>
public const uint MAILSLOT_WAIT_FOREVER = unchecked((uint)-1);
/// <summary>
/// Creates a mailslot with the specified name and returns a handle that a mailslot server can use to perform operations on the mailslot. The mailslot is
/// local to the computer that creates it. An error occurs if a mailslot with the specified name already exists.
/// </summary>
/// <param name="lpName">
/// <para>The name of the mailslot. This name must have the following form:</para>
/// <para>\\.\mailslot\[path]name</para>
/// <para>
/// The name field must be unique. The name may include multiple levels of pseudo directories separated by backslashes. For example, both
/// \\.\mailslot\example_mailslot_name and \\.\mailslot\abc\def\ghi are valid names.
/// </para>
/// </param>
/// <param name="nMaxMessageSize">
/// The maximum size of a single message that can be written to the mailslot, in bytes. To specify that the message can be of any size, set this value to zero.
/// </param>
/// <param name="lReadTimeout">
/// <para>
/// The time a read operation can wait for a message to be written to the mailslot before a time-out occurs, in milliseconds. The following values have
/// special meanings.
/// </para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Value</term>
/// <term>Meaning</term>
/// </listheader>
/// <item>
/// <term>0</term>
/// <term>Returns immediately if no message is present. (The system does not treat an immediate return as an error.)</term>
/// </item>
/// <item>
/// <term>MAILSLOT_WAIT_FOREVER((DWORD)-1)</term>
/// <term>Waits forever for a message.</term>
/// </item>
/// </list>
/// </para>
/// <para>This time-out value applies to all subsequent read operations and all inherited mailslot handles.</para>
/// </param>
/// <param name="lpSecurityAttributes">
/// A pointer to a <c>SECURITY_ATTRIBUTES</c> structure. The <c>bInheritHandle</c> member of the structure determines whether the returned handle can be
/// inherited by child processes. If lpSecurityAttributes is <c>NULL</c>, the handle cannot be inherited.
/// </param>
/// <returns>
/// <para>
/// If the function succeeds, the return value is a handle to the mailslot, for use in server mailslot operations. The handle returned by this function
/// is asynchronous, or overlapped.
/// </para>
/// <para>If the function fails, the return value is <c>INVALID_HANDLE_VALUE</c>. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// HANDLE WINAPI CreateMailslot( _In_ LPCTSTR lpName, _In_ DWORD nMaxMessageSize, _In_ DWORD lReadTimeout, _In_opt_ LPSECURITY_ATTRIBUTES
// lpSecurityAttributes); https://msdn.microsoft.com/en-us/library/windows/desktop/aa365147(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)]
[PInvokeData("Winbase.h", MSDNShortId = "aa365147")]
public static extern IntPtr CreateMailslot([In] string lpName, uint nMaxMessageSize, uint lReadTimeout, [In] ref SECURITY_ATTRIBUTES lpSecurityAttributes);
/// <summary>Retrieves information about the specified mailslot.</summary>
/// <param name="hMailslot">A handle to a mailslot. The <c>CreateMailslot</c> function must create this handle.</param>
/// <param name="lpMaxMessageSize">
/// The maximum message size, in bytes, allowed for this mailslot. This value can be greater than or equal to the value specified in the cbMaxMsg
/// parameter of the <c>CreateMailslot</c> function that created the mailslot. This parameter can be <c>NULL</c>.
/// </param>
/// <param name="lpNextSize">
/// <para>The size of the next message, in bytes. The following value has special meaning.</para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Value</term>
/// <term>Meaning</term>
/// </listheader>
/// <item>
/// <term>MAILSLOT_NO_MESSAGE((DWORD)-1)</term>
/// <term>There is no next message.</term>
/// </item>
/// </list>
/// </para>
/// <para>This parameter can be <c>NULL</c>.</para>
/// </param>
/// <param name="lpMessageCount">The total number of messages waiting to be read, when the function returns. This parameter can be <c>NULL</c>.</param>
/// <param name="lpReadTimeout">
/// The amount of time, in milliseconds, a read operation can wait for a message to be written to the mailslot before a time-out occurs. This parameter
/// is filled in when the function returns. This parameter can be <c>NULL</c>.
/// </param>
/// <returns>
/// <para>If the function succeeds, the return value is nonzero.</para>
/// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// BOOL WINAPI GetMailslotInfo( _In_ HANDLE hMailslot, _Out_opt_ LPDWORD lpMaxMessageSize, _Out_opt_ LPDWORD lpNextSize, _Out_opt_ LPDWORD
// lpMessageCount, _Out_opt_ LPDWORD lpReadTimeout); https://msdn.microsoft.com/en-us/library/windows/desktop/aa365435(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("Winbase.h", MSDNShortId = "aa365435")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetMailslotInfo([In] IntPtr hMailslot, out uint lpMaxMessageSize, out uint lpNextSize, out uint lpMessageCount, out uint lpReadTimeout);
/// <summary>Sets the time-out value used by the specified mailslot for a read operation.</summary>
/// <param name="hMailslot">A handle to a mailslot. The <c>CreateMailslot</c> function must create this handle.</param>
/// <param name="lReadTimeout">
/// <para>
/// The time a read operation can wait for a message to be written to the mailslot before a time-out occurs, in milliseconds. The following values have
/// special meanings.
/// </para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Value</term>
/// <term>Meaning</term>
/// </listheader>
/// <item>
/// <term>0</term>
/// <term>Returns immediately if no message is present. (The system does not treat an immediate return as an error.)</term>
/// </item>
/// <item>
/// <term>MAILSLOT_WAIT_FOREVER((DWORD)-1)</term>
/// <term>Waits forever for a message.</term>
/// </item>
/// </list>
/// </para>
/// <para>This time-out value applies to all subsequent read operations and to all inherited mailslot handles.</para>
/// </param>
/// <returns>
/// <para>If the function succeeds, the return value is nonzero.</para>
/// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// BOOL WINAPI SetMailslotInfo( _In_ HANDLE hMailslot, _In_ DWORD lReadTimeout); https://msdn.microsoft.com/en-us/library/windows/desktop/aa365786(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("Winbase.h", MSDNShortId = "aa365786")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetMailslotInfo([In] IntPtr hMailslot, uint lReadTimeout);
}
}

View File

@ -0,0 +1,651 @@
using System;
using System.Runtime.InteropServices;
namespace Vanara.PInvoke
{
public static partial class Kernel32
{
/// <summary>The memory allocation attributes.</summary>
[Flags]
public enum GMEM
{
/// <summary>Combines GMEM_MOVEABLE and GMEM_ZEROINIT.</summary>
GHND = 0x0042,
/// <summary>Allocates fixed memory. The return value is a pointer.</summary>
GMEM_FIXED = 0x0000,
/// <summary>
/// Allocates movable memory. Memory blocks are never moved in physical memory, but they can be moved within the default heap.
/// <para>The return value is a handle to the memory object. To translate the handle into a pointer, use the GlobalLock function.</para>
/// <para>This value cannot be combined with GMEM_FIXED.</para>
/// </summary>
GMEM_MOVEABLE = 0x0002,
/// <summary>Initializes memory contents to zero.</summary>
GMEM_ZEROINIT = 0x0040,
/// <summary>Combines GMEM_FIXED and GMEM_ZEROINIT.</summary>
GPTR = 0x0040,
}
/// <summary>The memory allocation attributes.</summary>
[PInvokeData("MinWinBase.h")]
[Flags]
public enum LMEM
{
/// <summary>Allocates fixed memory. The return value is a pointer to the memory object.</summary>
LMEM_FIXED = 0x0000,
/// <summary>
/// Allocates movable memory. Memory blocks are never moved in physical memory, but they can be moved within the default heap. The return value is a
/// handle to the memory object. To translate the handle to a pointer, use the LocalLock function. This value cannot be combined with LMEM_FIXED.
/// </summary>
LMEM_MOVEABLE = 0x0002,
/// <summary>Obsolete.</summary>
[Obsolete]
LMEM_NOCOMPACT = 0x0010,
/// <summary>Obsolete.</summary>
[Obsolete]
LMEM_NODISCARD = 0x0020,
/// <summary>Initializes memory contents to zero.</summary>
LMEM_ZEROINIT = 0x0040,
/// <summary>
/// If the LMEM_MODIFY flag is specified in LocalReAlloc, this parameter modifies the attributes of the memory object, and the uBytes parameter is ignored.
/// </summary>
LMEM_MODIFY = 0x0080,
/// <summary>Obsolete.</summary>
[Obsolete]
LMEM_DISCARDABLE = 0x0F00,
/// <summary>Valid flags.</summary>
LMEM_VALID_FLAGS = 0x0F72,
/// <summary>Indicates that the local handle is not valid</summary>
LMEM_INVALID_HANDLE = 0x8000,
/// <summary>Combines LMEM_MOVEABLE and LMEM_ZEROINIT.</summary>
LHND = (LMEM_MOVEABLE | LMEM_ZEROINIT),
/// <summary>Combines LMEM_FIXED and LMEM_ZEROINIT.</summary>
LPTR = (LMEM_FIXED | LMEM_ZEROINIT),
/// <summary>Same as LMEM_MOVEABLE.</summary>
NONZEROLHND = (LMEM_MOVEABLE),
/// <summary>Same as LMEM_FIXED.</summary>
NONZEROLPTR = (LMEM_FIXED)
}
/// <summary>Allocates the specified number of bytes from the heap.</summary>
/// <param name="uFlags">
/// <para>
/// The memory allocation attributes. If zero is specified, the default is <c>GMEM_FIXED</c>. This parameter can be one or more of the following values,
/// except for the incompatible combinations that are specifically noted.
/// </para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Value</term>
/// <term>Meaning</term>
/// </listheader>
/// <item>
/// <term>GHND0x0042</term>
/// <term>Combines GMEM_MOVEABLE and GMEM_ZEROINIT.</term>
/// </item>
/// <item>
/// <term>GMEM_FIXED0x0000</term>
/// <term>Allocates fixed memory. The return value is a pointer.</term>
/// </item>
/// <item>
/// <term>GMEM_MOVEABLE0x0002</term>
/// <term>
/// Allocates movable memory. Memory blocks are never moved in physical memory, but they can be moved within the default heap.The return value is a
/// handle to the memory object. To translate the handle into a pointer, use the GlobalLock function.This value cannot be combined with GMEM_FIXED.
/// </term>
/// </item>
/// <item>
/// <term>GMEM_ZEROINIT0x0040</term>
/// <term>Initializes memory contents to zero.</term>
/// </item>
/// <item>
/// <term>GPTR0x0040</term>
/// <term>Combines GMEM_FIXED and GMEM_ZEROINIT.</term>
/// </item>
/// </list>
/// </para>
/// <para>The following values are obsolete, but are provided for compatibility with 16-bit Windows. They are ignored.</para>
/// </param>
/// <param name="dwBytes">
/// The number of bytes to allocate. If this parameter is zero and the uFlags parameter specifies <c>GMEM_MOVEABLE</c>, the function returns a handle to
/// a memory object that is marked as discarded.
/// </param>
/// <returns>
/// <para>If the function succeeds, the return value is a handle to the newly allocated memory object.</para>
/// <para>If the function fails, the return value is <c>NULL</c>. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// HGLOBAL WINAPI GlobalAlloc( _In_ UINT uFlags, _In_ SIZE_T dwBytes); https://msdn.microsoft.com/en-us/library/windows/desktop/aa366574(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "aa366574")]
public static extern IntPtr GlobalAlloc(GMEM uFlags, SizeT dwBytes);
/// <summary>Retrieves information about the specified global memory object.</summary>
/// <param name="hMem">A handle to the global memory object. This handle is returned by either the <c>GlobalAlloc</c> or <c>GlobalReAlloc</c> function.</param>
/// <returns>
/// <para>If the function succeeds, the return value specifies the allocation values and the lock count for the memory object.</para>
/// <para>
/// If the function fails, the return value is <c>GMEM_INVALID_HANDLE</c>, indicating that the global handle is not valid. To get extended error
/// information, call <c>GetLastError</c>.
/// </para>
/// </returns>
// UINT WINAPI GlobalFlags( _In_ HGLOBAL hMem); https://msdn.microsoft.com/en-us/library/windows/desktop/aa366577(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "aa366577")]
public static extern GMEM GlobalFlags([In] IntPtr hMem);
/// <summary>Frees the specified global memory object and invalidates its handle.</summary>
/// <param name="hMem">
/// A handle to the global memory object. This handle is returned by either the <c>GlobalAlloc</c> or <c>GlobalReAlloc</c> function. It is not safe to
/// free memory allocated with <c>LocalAlloc</c>.
/// </param>
/// <returns>
/// <para>If the function succeeds, the return value is <c>NULL</c>.</para>
/// <para>If the function fails, the return value is equal to a handle to the global memory object. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// HGLOBAL WINAPI GlobalFree( _In_ HGLOBAL hMem); https://msdn.microsoft.com/en-us/library/windows/desktop/aa366579(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "aa366579")]
public static extern IntPtr GlobalFree(IntPtr hMem);
/// <summary>Retrieves the handle associated with the specified pointer to a global memory block.</summary>
/// <param name="pMem">A pointer to the first byte of the global memory block. This pointer is returned by the <c>GlobalLock</c> function.</param>
/// <returns>
/// <para>If the function succeeds, the return value is a handle to the specified global memory object.</para>
/// <para>If the function fails, the return value is <c>NULL</c>. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// HGLOBAL WINAPI GlobalHandle( _In_ LPCVOID pMem); https://msdn.microsoft.com/en-us/library/windows/desktop/aa366582(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "aa366582")]
public static extern IntPtr GlobalHandle([In] IntPtr pMem);
/// <summary>
/// The GlobalLock function locks a global memory object and returns a pointer to the first byte of the object's memory block. GlobalLock function
/// increments the lock count by one. Needed for the clipboard functions when getting the data from IDataObject
/// </summary>
/// <param name="hMem"></param>
/// <returns></returns>
[DllImport(Lib.Kernel32, ExactSpelling = true, SetLastError = true)]
[PInvokeData("WinBase.h", MSDNShortId = "aa366584")]
public static extern IntPtr GlobalLock(IntPtr hMem);
/// <summary>Changes the size or attributes of a specified global memory object. The size can increase or decrease.</summary>
/// <param name="hMem">
/// A handle to the global memory object to be reallocated. This handle is returned by either the <c>GlobalAlloc</c> or <c>GlobalReAlloc</c> function.
/// </param>
/// <param name="dwBytes">The new size of the memory block, in bytes. If uFlags specifies <c>GMEM_MODIFY</c>, this parameter is ignored.</param>
/// <param name="uFlags">
/// <para>
/// The reallocation options. If <c>GMEM_MODIFY</c> is specified, the function modifies the attributes of the memory object only (the dwBytes parameter
/// is ignored.) Otherwise, the function reallocates the memory object.
/// </para>
/// <para>You can optionally combine <c>GMEM_MODIFY</c> with the following value.</para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Value</term>
/// <term>Meaning</term>
/// </listheader>
/// <item>
/// <term>GMEM_MOVEABLE0x0002</term>
/// <term>
/// Allocates movable memory.If the memory is a locked GMEM_MOVEABLE memory block or a GMEM_FIXED memory block and this flag is not specified, the memory
/// can only be reallocated in place.
/// </term>
/// </item>
/// </list>
/// </para>
/// <para>If this parameter does not specify <c>GMEM_MODIFY</c>, you can use the following value.</para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Value</term>
/// <term>Meaning</term>
/// </listheader>
/// <item>
/// <term>GMEM_ZEROINIT0x0040</term>
/// <term>Causes the additional memory contents to be initialized to zero if the memory object is growing in size.</term>
/// </item>
/// </list>
/// </para>
/// </param>
/// <returns>
/// <para>If the function succeeds, the return value is a handle to the reallocated memory object.</para>
/// <para>If the function fails, the return value is <c>NULL</c>. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// HGLOBAL WINAPI GlobalReAlloc( _In_ HGLOBAL hMem, _In_ SIZE_T dwBytes, _In_ UINT uFlags); https://msdn.microsoft.com/en-us/library/windows/desktop/aa366590(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "aa366590")]
public static extern IntPtr GlobalReAlloc([In] IntPtr hMem, SizeT dwBytes, GMEM uFlags);
/// <summary>Retrieves the current size of the specified global memory object, in bytes.</summary>
/// <param name="hMem">A handle to the global memory object. This handle is returned by either the <c>GlobalAlloc</c> or <c>GlobalReAlloc</c> function.</param>
/// <returns>
/// <para>If the function succeeds, the return value is the size of the specified global memory object, in bytes.</para>
/// <para>
/// If the specified handle is not valid or if the object has been discarded, the return value is zero. To get extended error information, call <c>GetLastError</c>.
/// </para>
/// </returns>
// SIZE_T WINAPI GlobalSize( _In_ HGLOBAL hMem); https://msdn.microsoft.com/en-us/library/windows/desktop/aa366593(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "aa366593")]
public static extern SizeT GlobalSize([In] IntPtr hMem);
/// <summary>The GlobalUnlock function decrements the lock count associated with a memory object.</summary>
/// <param name="hMem"></param>
/// <returns></returns>
[DllImport(Lib.Kernel32, ExactSpelling = true, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
[PInvokeData("WinBase.h", MSDNShortId = "aa366595")]
public static extern bool GlobalUnlock(IntPtr hMem);
/// <summary>Determines whether the calling process has read access to the memory at the specified address.</summary>
/// <param name="lpfn">A pointer to a memory address.</param>
/// <returns>
/// <para>If the calling process has read access to the specified memory, the return value is zero.</para>
/// <para>
/// If the calling process does not have read access to the specified memory, the return value is nonzero. To get extended error information, call <c>GetLastError</c>.
/// </para>
/// <para>
/// If the application is compiled as a debugging version, and the process does not have read access to the specified memory location, the function
/// causes an assertion and breaks into the debugger. Leaving the debugger, the function continues as usual, and returns a nonzero value. This behavior
/// is by design, as a debugging aid.
/// </para>
/// </returns>
// BOOL WINAPI IsBadCodePtr( _In_ FARPROC lpfn); https://msdn.microsoft.com/en-us/library/windows/desktop/aa366712(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "aa366712")]
[Obsolete("This function is obsolete and should not be used. Despite its name, it does not guarantee that the pointer is valid or that the memory pointed to is safe to use.")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool IsBadCodePtr(IntPtr lpfn);
/// <summary>Verifies that the calling process has read access to the specified range of memory.</summary>
/// <param name="lp">A pointer to the first byte of the memory block.</param>
/// <param name="ucb">The size of the memory block, in bytes. If this parameter is zero, the return value is zero.</param>
/// <returns>
/// <para>If the calling process has read access to all bytes in the specified memory range, the return value is zero.</para>
/// <para>If the calling process does not have read access to all bytes in the specified memory range, the return value is nonzero.</para>
/// <para>
/// If the application is compiled as a debugging version, and the process does not have read access to all bytes in the specified memory range, the
/// function causes an assertion and breaks into the debugger. Leaving the debugger, the function continues as usual, and returns a nonzero value. This
/// behavior is by design, as a debugging aid.
/// </para>
/// </returns>
// BOOL WINAPI IsBadReadPtr( _In_ const VOID *lp, _In_ UINT_PTR ucb); https://msdn.microsoft.com/en-us/library/windows/desktop/aa366713(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "aa366713")]
[Obsolete("This function is obsolete and should not be used. Despite its name, it does not guarantee that the pointer is valid or that the memory pointed to is safe to use.")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool IsBadReadPtr([In] IntPtr lp, UIntPtr ucb);
/// <summary>Verifies that the calling process has read access to the specified range of memory.</summary>
/// <param name="lpsz">A pointer to a null-terminated string, either Unicode or ASCII.</param>
/// <param name="ucchMax">
/// The maximum size of the string, in <c>TCHARs</c>. The function checks for read access in all characters up to the string's terminating null character
/// or up to the number of characters specified by this parameter, whichever is smaller. If this parameter is zero, the return value is zero.
/// </param>
/// <returns>
/// <para>
/// If the calling process has read access to all characters up to the string's terminating null character or up to the number of characters specified by
/// ucchMax, the return value is zero.
/// </para>
/// <para>
/// If the calling process does not have read access to all characters up to the string's terminating null character or up to the number of characters
/// specified by ucchMax, the return value is nonzero.
/// </para>
/// <para>
/// If the application is compiled as a debugging version, and the process does not have read access to the entire memory range specified, the function
/// causes an assertion and breaks into the debugger. Leaving the debugger, the function continues as usual, and returns a nonzero value This behavior is
/// by design, as a debugging aid.
/// </para>
/// </returns>
// BOOL WINAPI IsBadStringPtr( _In_ LPCTSTR lpsz, _In_ UINT_PTR ucchMax); https://msdn.microsoft.com/en-us/library/windows/desktop/aa366714(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, CharSet = CharSet.Auto)]
[PInvokeData("WinBase.h", MSDNShortId = "aa366714")]
[Obsolete("This function is obsolete and should not be used. Despite its name, it does not guarantee that the pointer is valid or that the memory pointed to is safe to use.")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool IsBadStringPtr([In] string lpsz, UIntPtr ucchMax);
/// <summary>Verifies that the calling process has write access to the specified range of memory.</summary>
/// <param name="lp">A pointer to the first byte of the memory block.</param>
/// <param name="ucb">The size of the memory block, in bytes. If this parameter is zero, the return value is zero.</param>
/// <returns>
/// <para>If the calling process has write access to all bytes in the specified memory range, the return value is zero.</para>
/// <para>If the calling process does not have write access to all bytes in the specified memory range, the return value is nonzero.</para>
/// <para>
/// If the application is run under a debugger and the process does not have write access to all bytes in the specified memory range, the function causes
/// a first chance STATUS_ACCESS_VIOLATION exception. The debugger can be configured to break for this condition. After resuming process execution in the
/// debugger, the function continues as usual and returns a nonzero value This behavior is by design and serves as a debugging aid.
/// </para>
/// </returns>
// BOOL WINAPI IsBadWritePtr( _In_ LPVOID lp, _In_ UINT_PTR ucb); https://msdn.microsoft.com/en-us/library/windows/desktop/aa366716(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "aa366716")]
[Obsolete("This function is obsolete and should not be used. Despite its name, it does not guarantee that the pointer is valid or that the memory pointed to is safe to use.")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool IsBadWritePtr([In] IntPtr lp, UIntPtr ucb);
/// <summary>
/// Allocates the specified number of bytes from the heap. <note>The local functions have greater overhead and provide fewer features than other memory
/// management functions. New applications should use the heap functions unless documentation states that a local function should be used. For more
/// information, see Global and Local Functions.</note>
/// </summary>
/// <param name="uFlags">
/// The memory allocation attributes. The default is the LMEM_FIXED value. This parameter can be one or more of the following values, except for the
/// incompatible combinations that are specifically noted.
/// <list type="table">
/// <listheader>
/// <term>Value</term>
/// <term>Meaning</term>
/// </listheader>
/// <item>
/// <term>
/// <c>LHND</c>
/// <para>0x0042</para>
/// </term>
/// <term>Combines LMEM_MOVEABLE and LMEM_ZEROINIT.</term>
/// </item>
/// <item>
/// <term>
/// <c>LMEM_FIXED</c>
/// <para>0x0000</para>
/// </term>
/// <term>Allocates fixed memory. The return value is a pointer to the memory object.</term>
/// </item>
/// <item>
/// <term>
/// <c>LMEM_MOVEABLE</c>
/// <para>0x0002</para>
/// </term>
/// <term>
/// Allocates movable memory. Memory blocks are never moved in physical memory, but they can be moved within the default heap.
/// <para>The return value is a handle to the memory object. To translate the handle to a pointer, use the LocalLock function.</para>
/// <para>This value cannot be combined with LMEM_FIXED.</para>
/// </term>
/// </item>
/// <item>
/// <term>
/// <c>LMEM_ZEROINIT</c>
/// <para>0x0040</para>
/// </term>
/// <term>Initializes memory contents to zero.</term>
/// </item>
/// <item>
/// <term>
/// <c>LPTR</c>
/// <para>0x0040</para>
/// </term>
/// <term>Combines LMEM_FIXED and LMEM_ZEROINIT.</term>
/// </item>
/// <item>
/// <term><c>NONZEROLHND</c></term>
/// <term>Same as LMEM_MOVEABLE.</term>
/// </item>
/// <item>
/// <term><c>NONZEROLPTR</c></term>
/// <term>Same as LMEM_FIXED.</term>
/// </item>
/// </list>
/// <para>The following values are obsolete, but are provided for compatibility with 16-bit Windows. They are ignored.</para>
/// <list type="bullet">
/// <item>
/// <term>LMEM_DISCARDABLE</term>
/// </item>
/// <item>
/// <term>LMEM_NOCOMPACT</term>
/// </item>
/// <item>
/// <term>LMEM_NODISCARD</term>
/// </item>
/// </list>
/// </param>
/// <param name="uBytes">
/// The number of bytes to allocate. If this parameter is zero and the uFlags parameter specifies LMEM_MOVEABLE, the function returns a handle to a
/// memory object that is marked as discarded.
/// </param>
/// <returns>
/// If the function succeeds, the return value is a handle to the newly allocated memory object. If the function fails, the return value is NULL. To get
/// extended error information, call GetLastError.
/// </returns>
/// <remarks>
/// Windows memory management does not provide a separate local heap and global heap. Therefore, the LocalAlloc and GlobalAlloc functions are essentially
/// the same.
/// <para>
/// The movable-memory flags LHND, LMEM_MOVABLE, and NONZEROLHND add unnecessary overhead and require locking to be used safely. They should be avoided
/// unless documentation specifically states that they should be used.
/// </para>
/// <para>
/// New applications should use the heap functions unless the documentation specifically states that a local function should be used. For example, some
/// Windows functions allocate memory that must be freed with LocalFree.
/// </para>
/// <para>
/// If the heap does not contain sufficient free space to satisfy the request, LocalAlloc returns NULL. Because NULL is used to indicate an error,
/// virtual address zero is never allocated. It is, therefore, easy to detect the use of a NULL pointer.
/// </para>
/// <para>
/// If the LocalAlloc function succeeds, it allocates at least the amount requested. If the amount allocated is greater than the amount requested, the
/// process can use the entire amount. To determine the actual number of bytes allocated, use the LocalSize function.
/// </para>
/// <para>To free the memory, use the LocalFree function. It is not safe to free memory allocated with LocalAlloc using GlobalFree.</para>
/// </remarks>
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "aa366723")]
public static extern IntPtr LocalAlloc(LMEM uFlags, UIntPtr uBytes);
/// <summary>Retrieves information about the specified local memory object.</summary>
/// <param name="hMem">A handle to the local memory object. This handle is returned by either the <c>LocalAlloc</c> or <c>LocalReAlloc</c> function.</param>
/// <returns>
/// <para>If the function succeeds, the return value specifies the allocation values and the lock count for the memory object.</para>
/// <para>
/// If the function fails, the return value is <c>LMEM_INVALID_HANDLE</c>, indicating that the local handle is not valid. To get extended error
/// information, call <c>GetLastError</c>.
/// </para>
/// </returns>
// UINT WINAPI LocalFlags( _In_ HLOCAL hMem); https://msdn.microsoft.com/en-us/library/windows/desktop/aa366728(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "aa366728")]
public static extern LMEM LocalFlags([In] IntPtr hMem);
/// <summary>
/// Frees the specified local memory object and invalidates its handle. <note>The local functions have greater overhead and provide fewer features than
/// other memory management functions. New applications should use the heap functions unless documentation states that a local function should be used.
/// For more information, see Global and Local Functions.</note>
/// </summary>
/// <param name="hMem">
/// A handle to the local memory object. This handle is returned by either the LocalAlloc or LocalReAlloc function. It is not safe to free memory
/// allocated with GlobalAlloc.
/// </param>
/// <returns>
/// If the function succeeds, the return value is NULL. If the function fails, the return value is equal to a handle to the local memory object. To get
/// extended error information, call GetLastError.
/// </returns>
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "aa366730")]
public static extern IntPtr LocalFree(IntPtr hMem);
/// <summary>Retrieves the handle associated with the specified pointer to a local memory object.</summary>
/// <param name="pMem">A pointer to the first byte of the local memory object. This pointer is returned by the <c>LocalLock</c> function.</param>
/// <returns>
/// <para>If the function succeeds, the return value is a handle to the specified local memory object.</para>
/// <para>If the function fails, the return value is <c>NULL</c>. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// HLOCAL WINAPI LocalHandle( _In_ LPCVOID pMem); https://msdn.microsoft.com/en-us/library/windows/desktop/aa366733(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "aa366733")]
public static extern IntPtr LocalHandle([In] IntPtr pMem);
/// <summary>Locks a local memory object and returns a pointer to the first byte of the object's memory block.</summary>
/// <param name="hMem">A handle to the local memory object. This handle is returned by either the <c>LocalAlloc</c> or <c>LocalReAlloc</c> function.</param>
/// <returns>
/// <para>If the function succeeds, the return value is a pointer to the first byte of the memory block.</para>
/// <para>If the function fails, the return value is <c>NULL</c>. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// LPVOID WINAPI LocalLock( _In_ HLOCAL hMem); https://msdn.microsoft.com/en-us/library/windows/desktop/aa366737(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "aa366737")]
public static extern IntPtr LocalLock([In] IntPtr hMem);
/// <summary>
/// Changes the size or the attributes of a specified local memory object. The size can increase or decrease. <note>The local functions have greater
/// overhead and provide fewer features than other memory management functions. New applications should use the heap functions unless documentation
/// states that a local function should be used. For more information, see Global and Local Functions.</note>
/// </summary>
/// <param name="hMem">A handle to the local memory object to be reallocated. This handle is returned by either the LocalAlloc or LocalReAlloc function.</param>
/// <param name="uBytes">The new size of the memory block, in bytes. If uFlags specifies LMEM_MODIFY, this parameter is ignored.</param>
/// <param name="uFlags">
/// The reallocation options. If LMEM_MODIFY is specified, the function modifies the attributes of the memory object only (the uBytes parameter is
/// ignored.) Otherwise, the function reallocates the memory object.
/// <para>You can optionally combine LMEM_MODIFY with the following value.</para>
/// <list type="table">
/// <listheader>
/// <term>Value</term>
/// <term>Meaning</term>
/// </listheader>
/// <item>
/// <term>
/// <c>LMEM_MOVEABLE</c>
/// <para>0x0002</para>
/// </term>
/// <term>
/// Allocates fixed or movable memory.
/// <para>
/// If the memory is a locked LMEM_MOVEABLE memory block or a LMEM_FIXED memory block and this flag is not specified, the memory can only be reallocated
/// in place.
/// </para>
/// </term>
/// </item>
/// </list>
/// <para>
/// If the memory is a locked LMEM_MOVEABLE memory block or a LMEM_FIXED memory block and this flag is not specified, the memory can only be reallocated
/// in place.
/// </para>
/// <para>If this parameter does not specify LMEM_MODIFY, you can use the following value.</para>
/// <list type="table">
/// <listheader>
/// <term>Value</term>
/// <term>Meaning</term>
/// </listheader>
/// <item>
/// <term>
/// <c>LMEM_ZEROINIT</c>
/// <para>0x0040</para>
/// </term>
/// <term>Causes the additional memory contents to be initialized to zero if the memory object is growing in size.</term>
/// </item>
/// </list>
/// </param>
/// <returns>
/// If the function succeeds, the return value is a handle to the reallocated memory object. If the function fails, the return value is NULL. To get
/// extended error information, call GetLastError.
/// </returns>
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "aa366742")]
public static extern IntPtr LocalReAlloc(IntPtr hMem, UIntPtr uBytes, LMEM uFlags);
/// <summary>
/// Retrieves the current size of the specified local memory object, in bytes. <note>The local functions have greater overhead and provide fewer features
/// than other memory management functions. New applications should use the heap functions unless documentation states that a local function should be
/// used. For more information, see Global and Local Functions.</note>
/// </summary>
/// <param name="hMem">A handle to the local memory object. This handle is returned by the LocalAlloc, LocalReAlloc, or LocalHandle function.</param>
/// <returns>
/// If the function succeeds, the return value is the size of the specified local memory object, in bytes. If the specified handle is not valid or if the
/// object has been discarded, the return value is zero. To get extended error information, call GetLastError.
/// </returns>
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "aa366745")]
public static extern uint LocalSize(IntPtr hMem);
/// <summary>
/// Decrements the lock count associated with a memory object that was allocated with <c>LMEM_MOVEABLE</c>. This function has no effect on memory objects
/// allocated with <c>LMEM_FIXED</c>.
/// </summary>
/// <param name="hMem">A handle to the local memory object. This handle is returned by either the <c>LocalAlloc</c> or <c>LocalReAlloc</c> function.</param>
/// <returns>
/// <para>
/// If the memory object is still locked after decrementing the lock count, the return value is nonzero. If the memory object is unlocked after
/// decrementing the lock count, the function returns zero and <c>GetLastError</c> returns <c>NO_ERROR</c>.
/// </para>
/// <para>If the function fails, the return value is zero and <c>GetLastError</c> returns a value other than <c>NO_ERROR</c>.</para>
/// </returns>
// BOOL WINAPI LocalUnlock( _In_ HLOCAL hMem); https://msdn.microsoft.com/en-us/library/windows/desktop/aa366747(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "aa366747")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool LocalUnlock([In] IntPtr hMem);
/// <summary>
/// <para>Maps previously allocated physical memory pages at a specified address in an Address Windowing Extensions (AWE) region.</para>
/// <para>
/// <c>64-bit Windows on Itanium-based systems:</c> Due to the difference in page sizes, <c>MapUserPhysicalPagesScatter</c> is not supported for 32-bit applications.
/// </para>
/// </summary>
/// <param name="VirtualAddresses">
/// <para>A pointer to an array of starting addresses of the regions of memory to remap.</para>
/// <para>
/// Each entry in VirtualAddresses must be within the address range that the <c>VirtualAlloc</c> function returns when the Address Windowing Extensions
/// (AWE) region is allocated. The value in NumberOfPages indicates the size of the array. Entries can be from multiple Address Windowing Extensions
/// (AWE) regions.
/// </para>
/// </param>
/// <param name="NumberOfPages">
/// <para>The size of the physical memory and virtual address space for which to establish translations, in pages.</para>
/// <para>The array at VirtualAddresses specifies the virtual address range.</para>
/// </param>
/// <param name="PageArray">
/// <para>A pointer to an array of values that indicates how each corresponding page in VirtualAddresses should be treated.</para>
/// <para>A 0 (zero) indicates that the corresponding entry in VirtualAddresses should be unmapped, and any nonzero value that it has should be mapped.</para>
/// <para>If this parameter is <c>NULL</c>, then every address in the VirtualAddresses array is unmapped.</para>
/// <para>The value in NumberOfPages indicates the size of the array.</para>
/// </param>
/// <returns>
/// <para>If the function succeeds, the return value is <c>TRUE</c>.</para>
/// <para>
/// If the function fails, the return value is <c>FALSE</c>, and the function does not map or unmap—partial or otherwise. To get extended error
/// information, call <c>GetLastError</c>.
/// </para>
/// </returns>
// BOOL WINAPI MapUserPhysicalPagesScatter( _In_ PVOID *VirtualAddresses, _In_ ULONG_PTR NumberOfPages, _In_ PULONG_PTR PageArray); https://msdn.microsoft.com/en-us/library/windows/desktop/aa366755(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "aa366755")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool MapUserPhysicalPagesScatter(IntPtr VirtualAddresses, UIntPtr NumberOfPages, [In] IntPtr PageArray);
/// <summary>Changes the protection on a region of committed pages in the virtual address space of a specified process.</summary>
/// <param name="hProcess">
/// A handle to the process whose memory protection is to be changed. The handle must have the <c>PROCESS_VM_OPERATION</c> access right. For more
/// information, see Process Security and Access Rights.
/// </param>
/// <param name="lpAddress">
/// <para>A pointer to the base address of the region of pages whose access protection attributes are to be changed.</para>
/// <para>
/// All pages in the specified region must be within the same reserved region allocated when calling the <c>VirtualAlloc</c> or <c>VirtualAllocEx</c>
/// function using <c>MEM_RESERVE</c>. The pages cannot span adjacent reserved regions that were allocated by separate calls to <c>VirtualAlloc</c> or
/// <c>VirtualAllocEx</c> using <c>MEM_RESERVE</c>.
/// </para>
/// </param>
/// <param name="dwSize">
/// The size of the region whose access protection attributes are changed, in bytes. The region of affected pages includes all pages containing one or
/// more bytes in the range from the lpAddress parameter to . This means that a 2-byte range straddling a page boundary causes the protection attributes
/// of both pages to be changed.
/// </param>
/// <param name="flNewProtect">
/// <para>The memory protection option. This parameter can be one of the memory protection constants.</para>
/// <para>
/// For mapped views, this value must be compatible with the access protection specified when the view was mapped (see <c>MapViewOfFile</c>,
/// <c>MapViewOfFileEx</c>, and <c>MapViewOfFileExNuma</c>).
/// </para>
/// </param>
/// <param name="lpflOldProtect">
/// A pointer to a variable that receives the previous access protection of the first page in the specified region of pages. If this parameter is
/// <c>NULL</c> or does not point to a valid variable, the function fails.
/// </param>
/// <returns>
/// <para>If the function succeeds, the return value is nonzero.</para>
/// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// BOOL WINAPI VirtualProtectEx( _In_ HANDLE hProcess, _In_ LPVOID lpAddress, _In_ SIZE_T dwSize, _In_ DWORD flNewProtect, _Out_ PDWORD lpflOldProtect); https://msdn.microsoft.com/en-us/library/windows/desktop/aa366899(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "aa366899")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool VirtualProtectEx([In] IntPtr hProcess, [In] IntPtr lpAddress, SizeT dwSize, uint flNewProtect, out uint lpflOldProtect);
}
}

View File

@ -0,0 +1,245 @@
using System;
using System.Runtime.InteropServices;
namespace Vanara.PInvoke
{
public static partial class Kernel32
{
/// <summary>The AC power status.</summary>
public enum AC_STATUS : byte
{
/// <summary>Offline</summary>
AC_OFFLINE = 0,
/// <summary>Online</summary>
AC_ONLINE = 1,
/// <summary>Unknown status</summary>
AC_UNKNOWN = 255
}
/// <summary>The battery charge status.</summary>
[Flags]
public enum BATTERY_STATUS : byte
{
/// <summary>High—the battery capacity is at more than 66 percent</summary>
BATTERY_HIGH = 1,
/// <summary>Low—the battery capacity is at less than 33 percent</summary>
BATTERY_LOW = 2,
/// <summary>Critical—the battery capacity is at less than five percent</summary>
BATTERY_CRITICAL = 4,
/// <summary>Charging</summary>
BATTERY_CHARGING = 8,
/// <summary>No system battery</summary>
BATTERY_NONE = 128,
/// <summary>Unknown status—unable to read the battery flag information</summary>
BATTERY_UNKNOWN = 255
}
/// <summary>The latency requirement for the time is takes to wake the computer.</summary>
public enum LATENCY_TIME
{
/// <summary>Any latency (default).</summary>
LT_DONT_CARE,
/// <summary>PowerSystemSleeping1 state (equivalent to ACPI state S0 and APM state Working).</summary>
LT_LOWEST_LATENCY,
}
/// <summary>Retrieves the current power state of the specified device. This function cannot be used to query the power state of a display device.</summary>
/// <param name="hDevice">A handle to an object on the device, such as a file or socket, or a handle to the device itself.</param>
/// <param name="pfOn">
/// A pointer to the variable that receives the power state. This value is <c>TRUE</c> if the device is in the working state. Otherwise, it is <c>FALSE</c>.
/// </param>
/// <returns>
/// <para>If the function succeeds, the return value is nonzero.</para>
/// <para>If the function fails, the return value is zero.</para>
/// </returns>
// BOOL WINAPI GetDevicePowerState( _In_ HANDLE hDevice, _Out_ BOOL *pfOn); https://msdn.microsoft.com/en-us/library/windows/desktop/aa372690(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)]
[PInvokeData("Winbase.h", MSDNShortId = "aa372690")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetDevicePowerState([In] IntPtr hDevice, [Out, MarshalAs(UnmanagedType.Bool)] out bool pfOn);
/// <summary>
/// Retrieves the power status of the system. The status indicates whether the system is running on AC or DC power, whether the battery is currently
/// charging, how much battery life remains, and if battery saver is on or off.
/// </summary>
/// <param name="lpSystemPowerStatus">A pointer to a <c>SYSTEM_POWER_STATUS</c> structure that receives status information.</param>
/// <returns>
/// <para>If the function succeeds, the return value is nonzero.</para>
/// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// BOOL WINAPI GetSystemPowerStatus( _Out_ LPSYSTEM_POWER_STATUS lpSystemPowerStatus); https://msdn.microsoft.com/en-us/library/windows/desktop/aa372693(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("Winbase.h", MSDNShortId = "aa372693")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetSystemPowerStatus(out SYSTEM_POWER_STATUS lpSystemPowerStatus);
/// <summary>Determines the current state of the computer.</summary>
/// <returns>
/// If the system was restored to the working state automatically and the user is not active, the function returns <c>TRUE</c>. Otherwise, the function
/// returns <c>FALSE</c>.
/// </returns>
// BOOL WINAPI IsSystemResumeAutomatic(void); https://msdn.microsoft.com/en-us/library/windows/desktop/aa372708(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)]
[PInvokeData("Winbase.h", MSDNShortId = "aa372708")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool IsSystemResumeAutomatic();
/// <summary>
/// <para>
/// [ <c>RequestWakeupLatency</c> is available for use in the operating systems specified in the Requirements section. It may be altered or unavailable
/// in subsequent versions.]
/// </para>
/// <para>Has no effect and returns <c>STATUS_NOT_SUPPORTED</c>. This function is provided only for compatibility with earlier versions of Windows.</para>
/// <para><c>Windows Server 2008 and Windows Vista:</c> Has no effect and always returns success.</para>
/// </summary>
/// <param name="latency">
/// <para>The latency requirement for the time is takes to wake the computer. This parameter can be one of the following values.</para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Value</term>
/// <term>Meaning</term>
/// </listheader>
/// <item>
/// <term>LT_LOWEST_LATENCY1</term>
/// <term>PowerSystemSleeping1 state (equivalent to ACPI state S0 and APM state Working).</term>
/// </item>
/// <item>
/// <term>LT_DONT_CARE0</term>
/// <term>Any latency (default).</term>
/// </item>
/// </list>
/// </para>
/// </param>
/// <returns>The return value is nonzero.</returns>
// BOOL WINAPI RequestWakeupLatency( _In_ LATENCY_TIME latency); https://msdn.microsoft.com/en-us/library/windows/desktop/aa373199(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "aa373199")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool RequestWakeupLatency(LATENCY_TIME latency);
/// <summary>
/// <para>
/// [ <c>SetSystemPowerState</c> is available for use in the operating systems specified in the Requirements section. It may be altered or unavailable in
/// subsequent versions. Applications written for Windows Vista and later should use <c>SetSuspendState</c> instead.]
/// </para>
/// <para>
/// Suspends the system by shutting power down. Depending on the ForceFlag parameter, the function either suspends operation immediately or requests
/// permission from all applications and device drivers before doing so.
/// </para>
/// </summary>
/// <param name="fSuspend">If this parameter is <c>TRUE</c>, the system is suspended. If the parameter is <c>FALSE</c>, the system hibernates.</param>
/// <param name="fForce">This parameter has no effect.</param>
/// <returns>
/// <para>If power has been suspended and subsequently restored, the return value is nonzero.</para>
/// <para>If the system was not suspended, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// BOOL WINAPI SetSystemPowerState( _In_ BOOL fSuspend, _In_ BOOL fForce); https://msdn.microsoft.com/en-us/library/windows/desktop/aa373206(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "aa373206")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetSystemPowerState([MarshalAs(UnmanagedType.Bool)] bool fSuspend, [MarshalAs(UnmanagedType.Bool)] bool fForce);
/// <summary>Contains information about the power status of the system.</summary>
// typedef struct _SYSTEM_POWER_STATUS { BYTE ACLineStatus; BYTE BatteryFlag; BYTE BatteryLifePercent; BYTE SystemStatusFlag; DWORD BatteryLifeTime;
// DWORD BatteryFullLifeTime;} SYSTEM_POWER_STATUS, *LPSYSTEM_POWER_STATUS; https://msdn.microsoft.com/en-us/library/windows/desktop/aa373232(v=vs.85).aspx
[PInvokeData("Winbase.h", MSDNShortId = "aa373232")]
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct SYSTEM_POWER_STATUS
{
/// <summary>
/// <para>The AC power status. This member can be one of the following values.</para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Value</term>
/// <term>Meaning</term>
/// </listheader>
/// <item>
/// <term>0</term>
/// <term>Offline</term>
/// </item>
/// <item>
/// <term>1</term>
/// <term>Online</term>
/// </item>
/// <item>
/// <term>255</term>
/// <term>Unknown status</term>
/// </item>
/// </list>
/// </para>
/// </summary>
public AC_STATUS ACLineStatus;
/// <summary>
/// <para>The battery charge status. This member can contain one or more of the following flags.</para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Value</term>
/// <term>Meaning</term>
/// </listheader>
/// <item>
/// <term>1</term>
/// <term>High—the battery capacity is at more than 66 percent</term>
/// </item>
/// <item>
/// <term>2</term>
/// <term>Low—the battery capacity is at less than 33 percent</term>
/// </item>
/// <item>
/// <term>4</term>
/// <term>Critical—the battery capacity is at less than five percent</term>
/// </item>
/// <item>
/// <term>8</term>
/// <term>Charging</term>
/// </item>
/// <item>
/// <term>128</term>
/// <term>No system battery</term>
/// </item>
/// <item>
/// <term>255</term>
/// <term>Unknown status—unable to read the battery flag information</term>
/// </item>
/// </list>
/// </para>
/// <para>The value is zero if the battery is not being charged and the battery capacity is between low and high.</para>
/// </summary>
public BATTERY_STATUS BatteryFlag;
/// <summary>The percentage of full battery charge remaining. This member can be a value in the range 0 to 100, or 255 if status is unknown.</summary>
public byte BatteryLifePercent;
/// <summary>
/// <para>
/// The status of battery saver. To participate in energy conservation, avoid resource intensive tasks when battery saver is on. To be notified when
/// this value changes, call the <c>RegisterPowerSettingNotification</c> function with the <c>power setting GUID</c>, <c>GUID_POWER_SAVING_STATUS</c>.
/// </para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Value</term>
/// <term>Meaning</term>
/// </listheader>
/// <item>
/// <term>0</term>
/// <term>Battery saver is off.</term>
/// </item>
/// <item>
/// <term>1</term>
/// <term>Battery saver on. Save energy where possible.</term>
/// </item>
/// </list>
/// </para>
/// <para>For general information about battery saver, see battery saver (in the hardware component guidelines).</para>
/// </summary>
public byte SystemStatusFlag;
/// <summary>The number of seconds of battery life remaining, or 1 if remaining seconds are unknown or if the device is connected to AC power.</summary>
public uint BatteryLifeTime;
/// <summary>
/// The number of seconds of battery life when at full charge, or 1 if full battery lifetime is unknown or if the device is connected to AC power.
/// </summary>
public uint BatteryFullLifeTime;
}
}
}

View File

@ -0,0 +1,483 @@
using System;
using System.Runtime.InteropServices;
namespace Vanara.PInvoke
{
public static partial class Kernel32
{
/// <summary>
/// An application-defined function used with the <c>CreateFiber</c> function. It serves as the starting address for a fiber. The
/// <c>LPFIBER_START_ROUTINE</c> type defines a pointer to this callback function. <c>FiberProc</c> is a placeholder for the application-defined function name.
/// </summary>
/// <param name="lpParameter">The fiber data passed using the lpParameter parameter of the <c>CreateFiber</c> function.</param>
/// <returns>This function does not return a value.</returns>
// VOID CALLBACK FiberProc( _In_ PVOID lpParameter); https://msdn.microsoft.com/en-us/library/windows/desktop/ms682660(v=vs.85).aspx
[UnmanagedFunctionPointer(CallingConvention.Winapi)]
[PInvokeData("WinBase.h", MSDNShortId = "ms682660")]
public delegate void FiberProc(IntPtr lpFiberParameter);
/// <summary>The thread's execution requirements.</summary>
public enum EXECUTION_STATE : uint
{
/// <summary>
/// Enables away mode. This value must be specified with ES_CONTINUOUS.
/// <para>
/// Away mode should be used only by media-recording and media-distribution applications that must perform critical background processing on desktop
/// computers while the computer appears to be sleeping. See Remarks.
/// </para>
/// </summary>
ES_AWAYMODE_REQUIRED = 0x00000040,
/// <summary>
/// Informs the system that the state being set should remain in effect until the next call that uses ES_CONTINUOUS and one of the other state flags
/// is cleared.
/// </summary>
ES_CONTINUOUS = 0x80000000,
/// <summary>Forces the display to be on by resetting the display idle timer.</summary>
ES_DISPLAY_REQUIRED = 0x00000002,
/// <summary>Forces the system to be in the working state by resetting the system idle timer.</summary>
ES_SYSTEM_REQUIRED = 0x00000001,
/// <summary>
/// This value is not supported. If ES_USER_PRESENT is combined with other esFlags values, the call will fail and none of the specified states will
/// be set.
/// </summary>
ES_USER_PRESENT = 0x00000004,
}
/// <summary>Flags for <c>CreateFiberEx</c>.</summary>
public enum FIBER_FLAG
{
/// <summary>The floating-point state on x86 systems is not switched and data can be corrupted if a fiber uses floating-point arithmetic.</summary>
FIBER_FLAG_UNSPECIFIED = 0,
/// <summary>The floating-point state is switched for the fiber.</summary>
FIBER_FLAG_FLOAT_SWITCH = 1
}
/// <summary>Converts the current fiber into a thread.</summary>
/// <returns>
/// <para>If the function succeeds, the return value is nonzero.</para>
/// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// BOOL WINAPI ConvertFiberToThread(void); https://msdn.microsoft.com/en-us/library/windows/desktop/ms682112(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms682112")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool ConvertFiberToThread();
/// <summary>Converts the current thread into a fiber. You must convert a thread into a fiber before you can schedule other fibers.</summary>
/// <param name="lpParameter">
/// A pointer to a variable that is passed to the fiber. The fiber can retrieve this data by using the <c>GetFiberData</c> macro.
/// </param>
/// <returns>
/// <para>If the function succeeds, the return value is the address of the fiber.</para>
/// <para>If the function fails, the return value is NULL. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// LPVOID WINAPI ConvertThreadToFiber( _In_opt_ LPVOID lpParameter); https://msdn.microsoft.com/en-us/library/windows/desktop/ms682115(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms682115")]
public static extern IntPtr ConvertThreadToFiber([In] IntPtr lpParameter);
/// <summary>
/// Allocates a fiber object, assigns it a stack, and sets up execution to begin at the specified start address, typically the fiber function. This
/// function does not schedule the fiber.
/// </summary>
/// <param name="dwStackSize">
/// The initial size of the stack, in bytes. If this parameter is zero, the new fiber uses the default stack size for the executable. For more
/// information, see Thread Stack Size.
/// </param>
/// <param name="lpStartAddress">
/// A pointer to the application-defined function to be executed by the fiber and represents the starting address of the fiber. Execution of the newly
/// created fiber does not begin until another fiber calls the SwitchToFiber function with this address. For more information of the fiber callback
/// function, see FiberProc.
/// </param>
/// <param name="lpParameter">A pointer to a variable that is passed to the fiber. The fiber can retrieve this data by using the GetFiberData macro.</param>
/// <returns>
/// If the function succeeds, the return value is the address of the fiber. If the function fails, the return value is NULL.To get extended error
/// information, call GetLastError.
/// </returns>
// VOID CALLBACK FiberProc( _In_ PVOID lpParameter); https://msdn.microsoft.com/en-us/library/windows/desktop/ms682402(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms682402")]
public static extern IntPtr CreateFiber(SizeT dwStackSize, FiberProc lpStartAddress, [In] IntPtr lpParameter);
/// <summary>
/// Allocates a fiber object, assigns it a stack, and sets up execution to begin at the specified start address, typically the fiber function. This
/// function does not schedule the fiber.
/// </summary>
/// <param name="dwStackCommitSize">
/// The initial commit size of the stack, in bytes. If this parameter is zero, the new fiber uses the default commit stack size for the executable. For
/// more information, see <c>Thread Stack Size</c>.
/// </param>
/// <param name="dwStackReserveSize">
/// The initial reserve size of the stack, in bytes. If this parameter is zero, the new fiber uses the default reserved stack size for the executable.
/// For more information, see <c>Thread Stack Size</c>.
/// </param>
/// <param name="dwFlags">
/// <para>
/// If this parameter is zero, the floating-point state on x86 systems is not switched and data can be corrupted if a fiber uses floating-point
/// arithmetic. If this parameter is <c>FIBER_FLAG_FLOAT_SWITCH</c>, the floating-point state is switched for the fiber.
/// </para>
/// <para><c>Windows XP:</c> The <c>FIBER_FLAG_FLOAT_SWITCH</c> flag is not supported.</para>
/// </param>
/// <param name="lpStartAddress">
/// A pointer to the application-defined function to be executed by the fiber and represents the starting address of the fiber. Execution of the newly
/// created fiber does not begin until another fiber calls the <c>SwitchToFiber</c> function with this address. For more information on the fiber
/// callback function, see <c>FiberProc</c>.
/// </param>
/// <param name="lpParameter">
/// A pointer to a variable that is passed to the fiber. The fiber can retrieve this data by using the <c>GetFiberData</c> macro.
/// </param>
/// <returns>
/// <para>If the function succeeds, the return value is the address of the fiber.</para>
/// <para>If the function fails, the return value is NULL. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// LPVOID WINAPI CreateFiberEx( _In_ SIZE_T dwStackCommitSize, _In_ SIZE_T dwStackReserveSize, _In_ DWORD dwFlags, _In_ LPFIBER_START_ROUTINE
// lpStartAddress, _In_opt_ LPVOID lpParameter); https://msdn.microsoft.com/en-us/library/windows/desktop/ms682406(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms682406")]
public static extern IntPtr CreateFiberEx(SizeT dwStackCommitSize, SizeT dwStackReserveSize, FIBER_FLAG dwFlags, FiberProc lpStartAddress, [In] IntPtr lpParameter);
/// <summary>Deletes an existing fiber.</summary>
/// <param name="lpFiber">The address of the fiber to be deleted.</param>
/// <returns>This function does not return a value.</returns>
// VOID WINAPI DeleteFiber( _In_ LPVOID lpFiber); https://msdn.microsoft.com/en-us/library/windows/desktop/ms682556(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms682556")]
public static extern void DeleteFiber([In] IntPtr lpFiber);
/// <summary>Retrieves a pseudo handle for the current process.</summary>
/// <returns>The return value is a pseudo handle to the current process.</returns>
// HANDLE WINAPI GetCurrentProcess(void);
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms683179(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms683179")]
public static extern IntPtr GetCurrentProcess();
/// <summary>
/// <para>Retrieves the amount of memory available in the specified node.</para>
/// <para>Use the <c>GetNumaAvailableMemoryNodeEx</c> function to specify the node as a <c>USHORT</c> value.</para>
/// </summary>
/// <param name="Node">The number of the node.</param>
/// <param name="AvailableBytes">The amount of available memory for the node, in bytes.</param>
/// <returns>
/// <para>If the function succeeds, the return value is nonzero.</para>
/// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// BOOL WINAPI GetNumaAvailableMemoryNode( _In_ UCHAR Node, _Out_ PULONGLONG AvailableBytes); https://msdn.microsoft.com/en-us/library/windows/desktop/ms683202(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms683202")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetNumaAvailableMemoryNode(byte Node, out ulong AvailableBytes);
/// <summary>
/// <para>Retrieves the processor mask for the specified node.</para>
/// <para>Use the <c>GetNumaNodeProcessorMaskEx</c> function to retrieve the processor mask for a node in any processor group.</para>
/// </summary>
/// <param name="Node">The number of the node.</param>
/// <param name="ProcessorMask">
/// <para>The processor mask for the node. A processor mask is a bit vector in which each bit represents a processor and whether it is in the node.</para>
/// <para>If the node has no processors configured, the processor mask is zero.</para>
/// <para>
/// On systems with more than 64 processors, this parameter is set to the processor mask for the node only if the node is in the same processor group as
/// the calling thread. Otherwise, the parameter is set to zero.
/// </para>
/// </param>
/// <returns>
/// <para>If the function succeeds, the return value is nonzero.</para>
/// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// BOOL WINAPI GetNumaNodeProcessorMask( _In_ UCHAR Node, _Out_ PULONGLONG ProcessorMask); https://msdn.microsoft.com/en-us/library/windows/desktop/ms683204(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms683204")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetNumaNodeProcessorMask(byte Node, out ulong ProcessorMask);
/// <summary>
/// <para>Retrieves the node number for the specified processor.</para>
/// <para>Use the <c>GetNumaProcessorNodeEx</c> function to specify a processor group and retrieve the node number as a <c>USHORT</c> value.</para>
/// </summary>
/// <param name="Processor">
/// <para>The processor number.</para>
/// <para>
/// On a system with more than 64 logical processors, the processor number is relative to the processor group that contains the processor on which the
/// calling thread is running.
/// </para>
/// </param>
/// <param name="NodeNumber">The node number. If the processor does not exist, this parameter is 0xFF.</param>
/// <returns>
/// <para>If the function succeeds, the return value is nonzero.</para>
/// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// BOOL WINAPI GetNumaProcessorNode( _In_ UCHAR Processor, _Out_ PUCHAR NodeNumber); https://msdn.microsoft.com/en-us/library/windows/desktop/ms683205(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms683205")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetNumaProcessorNode(byte Processor, out byte NodeNumber);
/// <summary>Retrieves the process affinity mask for the specified process and the system affinity mask for the system.</summary>
/// <param name="hProcess">
/// <para>A handle to the process whose affinity mask is desired.</para>
/// <para>
/// This handle must have the <c>PROCESS_QUERY_INFORMATION</c> or <c>PROCESS_QUERY_LIMITED_INFORMATION</c> access right. For more information, see
/// Process Security and Access Rights.
/// </para>
/// <para><c>Windows Server 2003 and Windows XP:</c> The handle must have the <c>PROCESS_QUERY_INFORMATION</c> access right.</para>
/// </param>
/// <param name="lpProcessAffinityMask">A pointer to a variable that receives the affinity mask for the specified process.</param>
/// <param name="lpSystemAffinityMask">A pointer to a variable that receives the affinity mask for the system.</param>
/// <returns>
/// <para>
/// If the function succeeds, the return value is nonzero and the function sets the variables pointed to by lpProcessAffinityMask and
/// lpSystemAffinityMask to the appropriate affinity masks.
/// </para>
/// <para>
/// On a system with more than 64 processors, if the threads of the calling process are in a single processor group, the function sets the variables
/// pointed to by lpProcessAffinityMask and lpSystemAffinityMask to the process affinity mask and the processor mask of active logical processors for
/// that group. If the calling process contains threads in multiple groups, the function returns zero for both affinity masks.
/// </para>
/// <para>
/// If the function fails, the return value is zero, and the values of the variables pointed to by lpProcessAffinityMask and lpSystemAffinityMask are
/// undefined. To get extended error information, call <c>GetLastError</c>.
/// </para>
/// </returns>
// BOOL WINAPI GetProcessAffinityMask( _In_ HANDLE hProcess, _Out_ PDWORD_PTR lpProcessAffinityMask, _Out_ PDWORD_PTR lpSystemAffinityMask); https://msdn.microsoft.com/en-us/library/windows/desktop/ms683213(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms683213")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetProcessAffinityMask([In] IntPtr hProcess, out UIntPtr lpProcessAffinityMask, out UIntPtr lpSystemAffinityMask);
/// <summary>Retrieves accounting information for all I/O operations performed by the specified process.</summary>
/// <param name="hProcess">
/// <para>
/// A handle to the process. The handle must have the <c>PROCESS_QUERY_INFORMATION</c> or <c>PROCESS_QUERY_LIMITED_INFORMATION</c> access right. For more
/// information, see Process Security and Access Rights.
/// </para>
/// <para><c>Windows Server 2003 and Windows XP:</c> The handle must have the <c>PROCESS_QUERY_INFORMATION</c> access right.</para>
/// </param>
/// <param name="lpIoCounters">A pointer to an <c>IO_COUNTERS</c> structure that receives the I/O accounting information for the process.</param>
/// <returns>
/// <para>If the function succeeds, the return value is nonzero.</para>
/// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// BOOL WINAPI GetProcessIoCounters( _In_ HANDLE hProcess, _Out_ PIO_COUNTERS lpIoCounters); https://msdn.microsoft.com/en-us/library/windows/desktop/ms683218(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms683218")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetProcessIoCounters([In] IntPtr hProcess, out IO_COUNTERS lpIoCounters);
/// <summary>Retrieves the minimum and maximum working set sizes of the specified process.</summary>
/// <param name="hProcess">
/// <para>
/// A handle to the process whose working set sizes will be obtained. The handle must have the <c>PROCESS_QUERY_INFORMATION</c> or
/// <c>PROCESS_QUERY_LIMITED_INFORMATION</c> access right. For more information, see Process Security and Access Rights.
/// </para>
/// <para><c>Windows Server 2003 and Windows XP:</c> The handle must have the <c>PROCESS_QUERY_INFORMATION</c> access right.</para>
/// </param>
/// <param name="lpMinimumWorkingSetSize">
/// A pointer to a variable that receives the minimum working set size of the specified process, in bytes. The virtual memory manager attempts to keep at
/// least this much memory resident in the process whenever the process is active.
/// </param>
/// <param name="lpMaximumWorkingSetSize">
/// A pointer to a variable that receives the maximum working set size of the specified process, in bytes. The virtual memory manager attempts to keep no
/// more than this much memory resident in the process whenever the process is active when memory is in short supply.
/// </param>
/// <returns>
/// <para>If the function succeeds, the return value is nonzero.</para>
/// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// BOOL WINAPI GetProcessWorkingSetSize( _In_ HANDLE hProcess, _Out_ PSIZE_T lpMinimumWorkingSetSize, _Out_ PSIZE_T lpMaximumWorkingSetSize);
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms683226")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetProcessWorkingSetSize([In] IntPtr hProcess, [Out] out SizeT lpMinimumWorkingSetSize, [Out] out SizeT lpMaximumWorkingSetSize);
/// <summary>Sets a processor affinity mask for the threads of the specified process.</summary>
/// <param name="hProcess">
/// A handle to the process whose affinity mask is to be set. This handle must have the <c>PROCESS_SET_INFORMATION</c> access right. For more
/// information, see Process Security and Access Rights.
/// </param>
/// <param name="dwProcessAffinityMask">
/// <para>The affinity mask for the threads of the process.</para>
/// <para>On a system with more than 64 processors, the affinity mask must specify processors in a single processor group.</para>
/// </param>
/// <returns>
/// <para>If the function succeeds, the return value is nonzero.</para>
/// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para>
/// <para>If the process affinity mask requests a processor that is not configured in the system, the last error code is <c>ERROR_INVALID_PARAMETER</c>.</para>
/// <para>
/// On a system with more than 64 processors, if the calling process contains threads in more than one processor group, the last error code is <c>ERROR_INVALID_PARAMETER</c>.
/// </para>
/// </returns>
// BOOL WINAPI SetProcessAffinityMask( _In_ HANDLE hProcess, _In_ DWORD_PTR dwProcessAffinityMask); https://msdn.microsoft.com/en-us/library/windows/desktop/ms686223(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms686223")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetProcessAffinityMask([In] IntPtr hProcess, UIntPtr dwProcessAffinityMask);
/// <summary>Sets the minimum and maximum working set sizes for the specified process.</summary>
/// <param name="hProcess">
/// <para>A handle to the process whose working set sizes is to be set.</para>
/// <para>The handle must have the <c>PROCESS_SET_QUOTA</c> access right. For more information, see Process Security and Access Rights.</para>
/// </param>
/// <param name="dwMinimumWorkingSetSize">
/// <para>
/// The minimum working set size for the process, in bytes. The virtual memory manager attempts to keep at least this much memory resident in the process
/// whenever the process is active.
/// </para>
/// <para>
/// This parameter must be greater than zero but less than or equal to the maximum working set size. The default size is 50 pages (for example, this is
/// 204,800 bytes on systems with a 4K page size). If the value is greater than zero but less than 20 pages, the minimum value is set to 20 pages.
/// </para>
/// <para>
/// If both dwMinimumWorkingSetSize and dwMaximumWorkingSetSize have the value ( <c>SIZE_T</c>)1, the function removes as many pages as possible from
/// the working set of the specified process.
/// </para>
/// </param>
/// <param name="dwMaximumWorkingSetSize">
/// <para>
/// The maximum working set size for the process, in bytes. The virtual memory manager attempts to keep no more than this much memory resident in the
/// process whenever the process is active and available memory is low.
/// </para>
/// <para>
/// This parameter must be greater than or equal to 13 pages (for example, 53,248 on systems with a 4K page size), and less than the system-wide maximum
/// (number of available pages minus 512 pages). The default size is 345 pages (for example, this is 1,413,120 bytes on systems with a 4K page size).
/// </para>
/// <para>
/// If both dwMinimumWorkingSetSize and dwMaximumWorkingSetSize have the value ( <c>SIZE_T</c>)1, the function removes as many pages as possible from
/// the working set of the specified process.
/// </para>
/// </param>
/// <returns>
/// <para>If the function succeeds, the return value is nonzero.</para>
/// <para>If the function fails, the return value is zero. Call <c>GetLastError</c> to obtain extended error information.</para>
/// </returns>
// BOOL WINAPI SetProcessWorkingSetSize( _In_ HANDLE hProcess, _In_ SIZE_T dwMinimumWorkingSetSize, _In_ SIZE_T dwMaximumWorkingSetSize); https://msdn.microsoft.com/en-us/library/windows/desktop/ms686234(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms686234")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetProcessWorkingSetSize([In] IntPtr hProcess, SizeT dwMinimumWorkingSetSize, SizeT dwMaximumWorkingSetSize);
/// <summary>Sets a processor affinity mask for the specified thread.</summary>
/// <param name="hThread">
/// <para>A handle to the thread whose affinity mask is to be set.</para>
/// <para>
/// This handle must have the <c>THREAD_SET_INFORMATION</c> or <c>THREAD_SET_LIMITED_INFORMATION</c> access right and the <c>THREAD_QUERY_INFORMATION</c>
/// or <c>THREAD_QUERY_LIMITED_INFORMATION</c> access right. For more information, see Thread Security and Access Rights.
/// </para>
/// <para>
/// <c>Windows Server 2003 and Windows XP:</c> The handle must have the <c>THREAD_SET_INFORMATION</c> and <c>THREAD_QUERY_INFORMATION</c> access rights.
/// </para>
/// </param>
/// <param name="dwThreadAffinityMask">
/// <para>The affinity mask for the thread.</para>
/// <para>On a system with more than 64 processors, the affinity mask must specify processors in the thread's current processor group.</para>
/// </param>
/// <returns>
/// <para>If the function succeeds, the return value is the thread's previous affinity mask.</para>
/// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para>
/// <para>If the thread affinity mask requests a processor that is not selected for the process affinity mask, the last error code is <c>ERROR_INVALID_PARAMETER</c>.</para>
/// </returns>
// DWORD_PTR WINAPI SetThreadAffinityMask( _In_ HANDLE hThread, _In_ DWORD_PTR dwThreadAffinityMask); https://msdn.microsoft.com/en-us/library/windows/desktop/ms686247(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms686247")]
public static extern UIntPtr SetThreadAffinityMask([In] IntPtr hThread, UIntPtr dwThreadAffinityMask);
/// <summary>
/// Enables an application to inform the system that it is in use, thereby preventing the system from entering sleep or turning off the display while the
/// application is running.
/// </summary>
/// <param name="esFlags">
/// <para>The thread's execution requirements. This parameter can be one or more of the following values.</para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Value</term>
/// <term>Meaning</term>
/// </listheader>
/// <item>
/// <term>ES_AWAYMODE_REQUIRED0x00000040</term>
/// <term>
/// Enables away mode. This value must be specified with ES_CONTINUOUS.Away mode should be used only by media-recording and media-distribution
/// applications that must perform critical background processing on desktop computers while the computer appears to be sleeping. See Remarks.
/// </term>
/// </item>
/// <item>
/// <term>ES_CONTINUOUS0x80000000</term>
/// <term>
/// Informs the system that the state being set should remain in effect until the next call that uses ES_CONTINUOUS and one of the other state flags is cleared.
/// </term>
/// </item>
/// <item>
/// <term>ES_DISPLAY_REQUIRED0x00000002</term>
/// <term>Forces the display to be on by resetting the display idle timer.</term>
/// </item>
/// <item>
/// <term>ES_SYSTEM_REQUIRED0x00000001</term>
/// <term>Forces the system to be in the working state by resetting the system idle timer.</term>
/// </item>
/// <item>
/// <term>ES_USER_PRESENT0x00000004</term>
/// <term>
/// This value is not supported. If ES_USER_PRESENT is combined with other esFlags values, the call will fail and none of the specified states will be set.
/// </term>
/// </item>
/// </list>
/// </para>
/// </param>
/// <returns>
/// <para>If the function succeeds, the return value is the previous thread execution state.</para>
/// <para>If the function fails, the return value is <c>NULL</c>.</para>
/// </returns>
// EXECUTION_STATE WINAPI SetThreadExecutionState( _In_ EXECUTION_STATE esFlags); https://msdn.microsoft.com/en-us/library/windows/desktop/aa373208(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)]
[PInvokeData("Winbase.h", MSDNShortId = "aa373208")]
public static extern EXECUTION_STATE SetThreadExecutionState(EXECUTION_STATE esFlags);
/// <summary>Schedules a fiber. The function must be called on a fiber.</summary>
/// <param name="lpFiber">The address of the fiber to be scheduled.</param>
/// <returns>This function does not return a value.</returns>
// VOID WINAPI SwitchToFiber( _In_ LPVOID lpFiber); https://msdn.microsoft.com/en-us/library/windows/desktop/ms686350(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms686350")]
public static extern void SwitchToFiber([In] IntPtr lpFiber);
/// <summary>Runs the specified application.</summary>
/// <param name="lpCmdLine">
/// The command line (file name plus optional parameters) for the application to be executed. If the name of the executable file in the lpCmdLine
/// parameter does not contain a directory path, the system searches for the executable file in this sequence:
/// </param>
/// <param name="uCmdShow">
/// The display options. For a list of the acceptable values, see the description of the nCmdShow parameter of the <c>ShowWindow</c> function.
/// </param>
/// <returns>
/// <para>If the function succeeds, the return value is greater than 31.</para>
/// <para>If the function fails, the return value is one of the following error values.</para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Return code/value</term>
/// <term>Description</term>
/// </listheader>
/// <item>
/// <term>0</term>
/// <term>The system is out of memory or resources.</term>
/// </item>
/// <item>
/// <term>ERROR_BAD_FORMAT</term>
/// <term>The .exe file is invalid.</term>
/// </item>
/// <item>
/// <term>ERROR_FILE_NOT_FOUND</term>
/// <term>The specified file was not found.</term>
/// </item>
/// <item>
/// <term>ERROR_PATH_NOT_FOUND</term>
/// <term>The specified path was not found.</term>
/// </item>
/// </list>
/// </para>
/// </returns>
// UINT WINAPI WinExec( _In_ LPCSTR lpCmdLine, _In_ UINT uCmdShow); https://msdn.microsoft.com/en-us/library/windows/desktop/ms687393(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms687393")]
public static extern uint WinExec([In] [MarshalAs(UnmanagedType.LPStr)] string lpCmdLine, ShowWindowCommand uCmdShow);
}
}

View File

@ -0,0 +1,343 @@
using System;
using System.Runtime.InteropServices;
using System.Text;
namespace Vanara.PInvoke
{
public static partial class Kernel32
{
/// <summary>Retrieves an integer associated with a key in the specified section of an initialization file.</summary>
/// <param name="lpAppName">The name of the section in the initialization file.</param>
/// <param name="lpKeyName">
/// The name of the key whose value is to be retrieved. This value is in the form of a string; the <c>GetPrivateProfileInt</c> function converts the
/// string into an integer and returns the integer.
/// </param>
/// <param name="nDefault">The default value to return if the key name cannot be found in the initialization file.</param>
/// <param name="lpFileName">
/// The name of the initialization file. If this parameter does not contain a full path to the file, the system searches for the file in the Windows directory.
/// </param>
/// <returns>
/// The return value is the integer equivalent of the string following the specified key name in the specified initialization file. If the key is not
/// found, the return value is the specified default value.
/// </returns>
// UINT WINAPI GetPrivateProfileInt( _In_ LPCTSTR lpAppName, _In_ LPCTSTR lpKeyName, _In_ INT nDefault, _In_ LPCTSTR lpFileName); https://msdn.microsoft.com/en-us/library/windows/desktop/ms724345(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, CharSet = CharSet.Auto)]
[PInvokeData("Winbase.h", MSDNShortId = "ms724345")]
public static extern uint GetPrivateProfileInt([In] string lpAppName, [In] string lpKeyName, int nDefault, [In] string lpFileName);
/// <summary>Retrieves all the keys and values for the specified section of an initialization file.</summary>
/// <param name="lpAppName">The name of the section in the initialization file.</param>
/// <param name="lpReturnedString">
/// A pointer to a buffer that receives the key name and value pairs associated with the named section. The buffer is filled with one or more
/// null-terminated strings; the last string is followed by a second null character.
/// </param>
/// <param name="nSize">
/// The size of the buffer pointed to by the lpReturnedString parameter, in characters. The maximum profile section size is 32,767 characters.
/// </param>
/// <param name="lpFileName">
/// The name of the initialization file. If this parameter does not contain a full path to the file, the system searches for the file in the Windows directory.
/// </param>
/// <returns>
/// The return value specifies the number of characters copied to the buffer, not including the terminating null character. If the buffer is not large
/// enough to contain all the key name and value pairs associated with the named section, the return value is equal to nSize minus two.
/// </returns>
// DWORD WINAPI GetPrivateProfileSection( _In_ LPCTSTR lpAppName, _Out_ LPTSTR lpReturnedString, _In_ DWORD nSize, _In_ LPCTSTR lpFileName); https://msdn.microsoft.com/en-us/library/windows/desktop/ms724348(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, CharSet = CharSet.Auto)]
[PInvokeData("Winbase.h", MSDNShortId = "ms724348")]
public static extern uint GetPrivateProfileSection([In] string lpAppName, [Out] StringBuilder lpReturnedString, uint nSize, [In] string lpFileName);
/// <summary>Retrieves the names of all sections in an initialization file.</summary>
/// <param name="lpszReturnBuffer">
/// A pointer to a buffer that receives the section names associated with the named file. The buffer is filled with one or more <c>null</c>-terminated
/// strings; the last string is followed by a second <c>null</c> character.
/// </param>
/// <param name="nSize">The size of the buffer pointed to by the lpszReturnBuffer parameter, in characters.</param>
/// <param name="lpFileName">
/// The name of the initialization file. If this parameter is <c>NULL</c>, the function searches the Win.ini file. If this parameter does not contain a
/// full path to the file, the system searches for the file in the Windows directory.
/// </param>
/// <returns>
/// The return value specifies the number of characters copied to the specified buffer, not including the terminating <c>null</c> character. If the
/// buffer is not large enough to contain all the section names associated with the specified initialization file, the return value is equal to the size
/// specified by nSize minus two.
/// </returns>
// DWORD WINAPI GetPrivateProfileSectionNames( _Out_ LPTSTR lpszReturnBuffer, _In_ DWORD nSize, _In_ LPCTSTR lpFileName); https://msdn.microsoft.com/en-us/library/windows/desktop/ms724352(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, CharSet = CharSet.Auto)]
[PInvokeData("Winbase.h", MSDNShortId = "ms724352")]
public static extern uint GetPrivateProfileSectionNames([Out] StringBuilder lpszReturnBuffer, uint nSize, [In] string lpFileName);
/// <summary>Retrieves a string from the specified section in an initialization file.</summary>
/// <param name="lpAppName">
/// The name of the section containing the key name. If this parameter is <c>NULL</c>, the <c>GetPrivateProfileString</c> function copies all section
/// names in the file to the supplied buffer.
/// </param>
/// <param name="lpKeyName">
/// The name of the key whose associated string is to be retrieved. If this parameter is <c>NULL</c>, all key names in the section specified by the
/// lpAppName parameter are copied to the buffer specified by the lpReturnedString parameter.
/// </param>
/// <param name="lpDefault">
/// <para>
/// A default string. If the lpKeyName key cannot be found in the initialization file, <c>GetPrivateProfileString</c> copies the default string to the
/// lpReturnedString buffer. If this parameter is <c>NULL</c>, the default is an empty string, "".
/// </para>
/// <para>
/// Avoid specifying a default string with trailing blank characters. The function inserts a <c>null</c> character in the lpReturnedString buffer to
/// strip any trailing blanks.
/// </para>
/// </param>
/// <param name="lpReturnedString">A pointer to the buffer that receives the retrieved string.</param>
/// <param name="nSize">The size of the buffer pointed to by the lpReturnedString parameter, in characters.</param>
/// <param name="lpFileName">
/// The name of the initialization file. If this parameter does not contain a full path to the file, the system searches for the file in the Windows directory.
/// </param>
/// <returns>
/// <para>The return value is the number of characters copied to the buffer, not including the terminating <c>null</c> character.</para>
/// <para>
/// If neither lpAppName nor lpKeyName is <c>NULL</c> and the supplied destination buffer is too small to hold the requested string, the string is
/// truncated and followed by a <c>null</c> character, and the return value is equal to nSize minus one.
/// </para>
/// <para>
/// If either lpAppName or lpKeyName is <c>NULL</c> and the supplied destination buffer is too small to hold all the strings, the last string is
/// truncated and followed by two <c>null</c> characters. In this case, the return value is equal to nSize minus two.
/// </para>
/// <para>
/// In the event the initialization file specified by lpFileName is not found, or contains invalid values, this function will set <c>errorno</c> with a
/// value of '0x2' (File Not Found). To retrieve extended error information, call GetLastError.
/// </para>
/// </returns>
// DWORD WINAPI GetPrivateProfileString( _In_ LPCTSTR lpAppName, _In_ LPCTSTR lpKeyName, _In_ LPCTSTR lpDefault, _Out_ LPTSTR lpReturnedString, _In_
// DWORD nSize, _In_ LPCTSTR lpFileName); https://msdn.microsoft.com/en-us/library/windows/desktop/ms724353(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)]
[PInvokeData("Winbase.h", MSDNShortId = "ms724353")]
public static extern uint GetPrivateProfileString([In] string lpAppName, [In] string lpKeyName, [In] string lpDefault, [Out] StringBuilder lpReturnedString, uint nSize, [In] string lpFileName);
/// <summary>
/// Retrieves the data associated with a key in the specified section of an initialization file. As it retrieves the data, the function calculates a
/// checksum and compares it with the checksum calculated by the <c>WritePrivateProfileStruct</c> function when the data was added to the file.
/// </summary>
/// <param name="lpszSection">The name of the section in the initialization file.</param>
/// <param name="lpszKey">The name of the key whose data is to be retrieved.</param>
/// <param name="lpStruct">A pointer to the buffer that receives the data associated with the file, section, and key names.</param>
/// <param name="uSizeStruct">The size of the buffer pointed to by the lpStruct parameter, in bytes.</param>
/// <param name="szFile">
/// The name of the initialization file. If this parameter does not contain a full path to the file, the system searches for the file in the Windows directory.
/// </param>
/// <returns>
/// <para>If the function succeeds, the return value is nonzero.</para>
/// <para>If the function fails, the return value is zero.</para>
/// </returns>
// BOOL WINAPI GetPrivateProfileStruct( _In_ LPCTSTR lpszSection, _In_ LPCTSTR lpszKey, _Out_ LPVOID lpStruct, _In_ UINT uSizeStruct, _In_ LPCTSTR
// szFile); https://msdn.microsoft.com/en-us/library/windows/desktop/ms724356(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, CharSet = CharSet.Auto)]
[PInvokeData("Winbase.h", MSDNShortId = "ms724356")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetPrivateProfileStruct([In] string lpszSection, [In] string lpszKey, IntPtr lpStruct, uint uSizeStruct, [In] string szFile);
/// <summary>Retrieves an integer from a key in the specified section of the Win.ini file.</summary>
/// <param name="lpAppName">The name of the section containing the key name.</param>
/// <param name="lpKeyName">
/// The name of the key whose value is to be retrieved. This value is in the form of a string; the <c>GetProfileInt</c> function converts the string into
/// an integer and returns the integer.
/// </param>
/// <param name="nDefault">The default value to return if the key name cannot be found in the initialization file.</param>
/// <returns>
/// The return value is the integer equivalent of the string following the key name in Win.ini. If the function cannot find the key, the return value is
/// the default value. If the value of the key is less than zero, the return value is zero.
/// </returns>
// UINT WINAPI GetProfileInt( _In_ LPCTSTR lpAppName, _In_ LPCTSTR lpKeyName, _In_ INT nDefault); https://msdn.microsoft.com/en-us/library/windows/desktop/ms724360(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, CharSet = CharSet.Auto)]
[PInvokeData("Winbase.h", MSDNShortId = "ms724360")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern uint GetProfileInt([In] string lpAppName, [In] string lpKeyName, int nDefault);
/// <summary>Retrieves all the keys and values for the specified section of the Win.ini file.</summary>
/// <param name="lpAppName">The name of the section in the Win.ini file.</param>
/// <param name="lpReturnedString">
/// A pointer to a buffer that receives the keys and values associated with the named section. The buffer is filled with one or more null-terminated
/// strings; the last string is followed by a second null character.
/// </param>
/// <param name="nSize">
/// The size of the buffer pointed to by the lpReturnedString parameter, in characters. The maximum profile section size is 32,767 characters.
/// </param>
/// <returns>
/// The return value specifies the number of characters copied to the specified buffer, not including the terminating null character. If the buffer is
/// not large enough to contain all the keys and values associated with the named section, the return value is equal to the size specified by nSize minus two.
/// </returns>
// DWORD WINAPI GetProfileSection( _In_ LPCTSTR lpAppName, _Out_ LPTSTR lpReturnedString, _In_ DWORD nSize); https://msdn.microsoft.com/en-us/library/windows/desktop/ms724363(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, CharSet = CharSet.Auto)]
[PInvokeData("Winbase.h", MSDNShortId = "ms724363")]
public static extern uint GetProfileSection([In] string lpAppName, [Out] StringBuilder lpReturnedString, uint nSize);
/// <summary>Retrieves the string associated with a key in the specified section of the Win.ini file.</summary>
/// <param name="lpAppName">
/// The name of the section containing the key. If this parameter is <c>NULL</c>, the function copies all section names in the file to the supplied buffer.
/// </param>
/// <param name="lpKeyName">
/// The name of the key whose associated string is to be retrieved. If this parameter is <c>NULL</c>, the function copies all keys in the given section
/// to the supplied buffer. Each string is followed by a <c>null</c> character, and the final string is followed by a second <c>null</c> character.
/// </param>
/// <param name="lpDefault">
/// <para>
/// A default string. If the lpKeyName key cannot be found in the initialization file, <c>GetProfileString</c> copies the default string to the
/// lpReturnedString buffer. If this parameter is <c>NULL</c>, the default is an empty string, "".
/// </para>
/// <para>
/// Avoid specifying a default string with trailing blank characters. The function inserts a <c>null</c> character in the lpReturnedString buffer to
/// strip any trailing blanks.
/// </para>
/// </param>
/// <param name="lpReturnedString">A pointer to a buffer that receives the character string.</param>
/// <param name="nSize">The size of the buffer pointed to by the lpReturnedString parameter, in characters.</param>
/// <returns>
/// <para>The return value is the number of characters copied to the buffer, not including the <c>null</c>-terminating character.</para>
/// <para>
/// If neither lpAppName nor lpKeyName is <c>NULL</c> and the supplied destination buffer is too small to hold the requested string, the string is
/// truncated and followed by a <c>null</c> character, and the return value is equal to nSize minus one.
/// </para>
/// <para>
/// If either lpAppName or lpKeyName is <c>NULL</c> and the supplied destination buffer is too small to hold all the strings, the last string is
/// truncated and followed by two <c>null</c> characters. In this case, the return value is equal to nSize minus two.
/// </para>
/// </returns>
// DWORD WINAPI GetProfileString( _In_ LPCTSTR lpAppName, _In_ LPCTSTR lpKeyName, _In_ LPCTSTR lpDefault, _Out_ LPTSTR lpReturnedString, _In_ DWORD
// nSize); https://msdn.microsoft.com/en-us/library/windows/desktop/ms724366(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, CharSet = CharSet.Auto)]
[PInvokeData("Winbase.h", MSDNShortId = "ms724366")]
public static extern uint GetProfileString([In] string lpAppName, [In] string lpKeyName, [In] string lpDefault, [Out] StringBuilder lpReturnedString, uint nSize);
/// <summary>Replaces the keys and values for the specified section in an initialization file.</summary>
/// <param name="lpAppName">The name of the section in which data is written. This section name is typically the name of the calling application.</param>
/// <param name="lpString">The new key names and associated values that are to be written to the named section. This string is limited to 65,535 bytes.</param>
/// <param name="lpFileName">
/// <para>
/// The name of the initialization file. If this parameter does not contain a full path for the file, the function searches the Windows directory for the
/// file. If the file does not exist and lpFileName does not contain a full path, the function creates the file in the Windows directory.
/// </para>
/// <para>
/// If the file exists and was created using Unicode characters, the function writes Unicode characters to the file. Otherwise, the function creates a
/// file using ANSI characters.
/// </para>
/// </param>
/// <returns>
/// <para>If the function succeeds, the return value is nonzero.</para>
/// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// BOOL WINAPI WritePrivateProfileSection( _In_ LPCTSTR lpAppName, _In_ LPCTSTR lpString, _In_ LPCTSTR lpFileName); https://msdn.microsoft.com/en-us/library/windows/desktop/ms725500(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)]
[PInvokeData("Winbase.h", MSDNShortId = "ms725500")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool WritePrivateProfileSection([In] string lpAppName, [In] string lpString, [In] string lpFileName);
/// <summary>Copies a string into the specified section of an initialization file.</summary>
/// <param name="lpAppName">
/// The name of the section to which the string will be copied. If the section does not exist, it is created. The name of the section is
/// case-independent; the string can be any combination of uppercase and lowercase letters.
/// </param>
/// <param name="lpKeyName">
/// The name of the key to be associated with a string. If the key does not exist in the specified section, it is created. If this parameter is
/// <c>NULL</c>, the entire section, including all entries within the section, is deleted.
/// </param>
/// <param name="lpString">
/// A <c>null</c>-terminated string to be written to the file. If this parameter is <c>NULL</c>, the key pointed to by the lpKeyName parameter is deleted.
/// </param>
/// <param name="lpFileName">
/// <para>The name of the initialization file.</para>
/// <para>
/// If the file was created using Unicode characters, the function writes Unicode characters to the file. Otherwise, the function writes ANSI characters.
/// </para>
/// </param>
/// <returns>
/// <para>If the function successfully copies the string to the initialization file, the return value is nonzero.</para>
/// <para>
/// If the function fails, or if it flushes the cached version of the most recently accessed initialization file, the return value is zero. To get
/// extended error information, call <c>GetLastError</c>.
/// </para>
/// </returns>
// BOOL WINAPI WritePrivateProfileString( _In_ LPCTSTR lpAppName, _In_ LPCTSTR lpKeyName, _In_ LPCTSTR lpString, _In_ LPCTSTR lpFileName); https://msdn.microsoft.com/en-us/library/windows/desktop/ms725501(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)]
[PInvokeData("Winbase.h", MSDNShortId = "ms725501")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool WritePrivateProfileString([In] string lpAppName, [In] string lpKeyName, [In] string lpString, [In] string lpFileName);
/// <summary>
/// Copies data into a key in the specified section of an initialization file. As it copies the data, the function calculates a checksum and appends it
/// to the end of the data. The <c>GetPrivateProfileStruct</c> function uses the checksum to ensure the integrity of the data.
/// </summary>
/// <param name="lpszSection">
/// The name of the section to which the string will be copied. If the section does not exist, it is created. The name of the section is case
/// independent, the string can be any combination of uppercase and lowercase letters.
/// </param>
/// <param name="lpszKey">
/// The name of the key to be associated with a string. If the key does not exist in the specified section, it is created. If this parameter is
/// <c>NULL</c>, the entire section, including all keys and entries within the section, is deleted.
/// </param>
/// <param name="lpStruct">The data to be copied. If this parameter is <c>NULL</c>, the key is deleted.</param>
/// <param name="uSizeStruct">The size of the buffer pointed to by the lpStruct parameter, in bytes.</param>
/// <param name="szFile">
/// <para>The name of the initialization file. If this parameter is <c>NULL</c>, the information is copied into the Win.ini file.</para>
/// <para>
/// If the file was created using Unicode characters, the function writes Unicode characters to the file. Otherwise, the function writes ANSI characters.
/// </para>
/// </param>
/// <returns>
/// <para>If the function successfully copies the string to the initialization file, the return value is nonzero.</para>
/// <para>
/// If the function fails, or if it flushes the cached version of the most recently accessed initialization file, the return value is zero. To get
/// extended error information, call <c>GetLastError</c>.
/// </para>
/// </returns>
// BOOL WINAPI WritePrivateProfileStruct( _In_ LPCTSTR lpszSection, _In_ LPCTSTR lpszKey, _In_ LPVOID lpStruct, _In_ UINT uSizeStruct, _In_ LPCTSTR
// szFile); https://msdn.microsoft.com/en-us/library/windows/desktop/ms725502(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)]
[PInvokeData("Winbase.h", MSDNShortId = "ms725502")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool WritePrivateProfileStruct([In] string lpszSection, [In] string lpszKey, [In] IntPtr lpStruct, uint uSizeStruct, [In] string szFile);
/// <summary>
/// Replaces the contents of the specified section in the Win.ini file with specified keys and values. If Win.ini uses Unicode characters, the function
/// writes Unicode characters to the file. Otherwise, the function writes ANSI characters.
/// </summary>
/// <param name="lpAppName">The name of the section. This section name is typically the name of the calling application.</param>
/// <param name="lpString">
/// <para>The new key names and associated values that are to be written to the named section. This string is limited to 65,535 bytes.</para>
/// <para>
/// If the file exists and was created using Unicode characters, the function writes Unicode characters to the file. Otherwise, the function creates a
/// file using ANSI characters.
/// </para>
/// </param>
/// <returns>
/// <para>If the function succeeds, the return value is nonzero.</para>
/// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// BOOL WINAPI WriteProfileSection( _In_ LPCTSTR lpAppName, _In_ LPCTSTR lpString); https://msdn.microsoft.com/en-us/library/windows/desktop/ms725503(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)]
[PInvokeData("Winbase.h", MSDNShortId = "ms725503")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool WriteProfileSection([In] string lpAppName, [In] string lpString);
/// <summary>
/// Copies a string into the specified section of the Win.ini file. If Win.ini uses Unicode characters, the function writes Unicode characters to the
/// file. Otherwise, the function writes ANSI characters.
/// </summary>
/// <param name="lpAppName">
/// The section to which the string is to be copied. If the section does not exist, it is created. The name of the section is not case-sensitive; the
/// string can be any combination of uppercase and lowercase letters.
/// </param>
/// <param name="lpKeyName">
/// The key to be associated with the string. If the key does not exist in the specified section, it is created. If this parameter is <c>NULL</c>, the
/// entire section, including all entries in the section, is deleted.
/// </param>
/// <param name="lpString">
/// A <c>null</c>-terminated string to be written to the file. If this parameter is <c>NULL</c>, the key pointed to by the lpKeyName parameter is deleted.
/// </param>
/// <returns>
/// <para>If the function successfully copies the string to the Win.ini file, the return value is nonzero.</para>
/// <para>If the function fails, or if it flushes the cached version of Win.ini, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// BOOL WINAPI WriteProfileString( _In_ LPCTSTR lpAppName, _In_ LPCTSTR lpKeyName, _In_ LPCTSTR lpString); https://msdn.microsoft.com/en-us/library/windows/desktop/ms725504(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)]
[PInvokeData("Winbase.h", MSDNShortId = "ms725504")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool WriteProfileString([In] string lpAppName, [In] string lpKeyName, [In] string lpString);
}
}

View File

@ -1,206 +0,0 @@
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Security;
namespace Vanara.PInvoke
{
public static partial class Kernel32
{
/// <summary>
/// An application-defined callback function used with the EnumResourceNames and EnumResourceNamesEx functions. It receives the type and name of a
/// resource. The ENUMRESNAMEPROC type defines a pointer to this callback function. EnumResNameProc is a placeholder for the application-defined function name.
/// </summary>
/// <param name="hModule">
/// A handle to the module whose executable file contains the resources that are being enumerated. If this parameter is NULL, the function enumerates the
/// resource names in the module used to create the current process.
/// </param>
/// <param name="lpszType">
/// The type of resource for which the name is being enumerated. Alternately, rather than a pointer, this parameter can be MAKEINTRESOURCE(ID), where ID
/// is an integer value representing a predefined resource type. For standard resource types, see Resource Types. For more information, see the Remarks
/// section below.
/// </param>
/// <param name="lpszName">
/// The name of a resource of the type being enumerated. Alternately, rather than a pointer, this parameter can be MAKEINTRESOURCE(ID), where ID is the
/// integer identifier of the resource. For more information, see the Remarks section below.
/// </param>
/// <param name="lParam">
/// An application-defined parameter passed to the EnumResourceNames or EnumResourceNamesEx function. This parameter can be used in error checking.
/// </param>
/// <returns>Returns TRUE to continue enumeration or FALSE to stop enumeration.</returns>
[UnmanagedFunctionPointer(CallingConvention.Winapi, SetLastError = true, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
[PInvokeData("winbase.h")]
public delegate bool EnumResNameProc(IntPtr hModule, string lpszType, string lpszName, IntPtr lParam);
[UnmanagedFunctionPointer(CallingConvention.Winapi, SetLastError = true, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
[PInvokeData("winbase.h")]
private delegate bool EnumResNameProcManaged(IntPtr hModule, IntPtr lpszType, IntPtr lpszName, ResList lParam);
/// <summary>
/// Enumerates resources of a specified type within a binary module. For Windows Vista and later, this is typically a language-neutral Portable
/// Executable (LN file), and the enumeration will also include resources from the corresponding language-specific resource files (.mui files) that
/// contain localizable language resources. It is also possible for hModule to specify an .mui file, in which case only that file is searched for resources.
/// </summary>
/// <param name="hModule">
/// A handle to a module to be searched. Starting with Windows Vista, if this is an LN file, then appropriate .mui files (if any exist) are included in
/// the search.
/// <para>If this parameter is NULL, that is equivalent to passing in a handle to the module used to create the current process.</para>
/// </param>
/// <param name="lpszType">
/// The type of the resource for which the name is being enumerated. Alternately, rather than a pointer, this parameter can be MAKEINTRESOURCE(ID), where
/// ID is an integer value representing a predefined resource type.
/// </param>
/// <param name="lpEnumFunc">A pointer to the callback function to be called for each enumerated resource name or ID.</param>
/// <param name="lParam">An application-defined value passed to the callback function. This parameter can be used in error checking.</param>
/// <returns>
/// The return value is TRUE if the function succeeds or FALSE if the function does not find a resource of the type specified, or if the function fails
/// for another reason. To get extended error information, call GetLastError.
/// </returns>
[DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)]
[SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
[PInvokeData("WinBase.h", MSDNShortId = "ms648037")]
public static extern bool EnumResourceNames(SafeLibraryHandle hModule, string lpszType, EnumResNameProc lpEnumFunc, IntPtr lParam);
/// <summary>
/// Enumerates resources of a specified type within a binary module. For Windows Vista and later, this is typically a language-neutral Portable
/// Executable (LN file), and the enumeration will also include resources from the corresponding language-specific resource files (.mui files) that
/// contain localizable language resources. It is also possible for hModule to specify an .mui file, in which case only that file is searched for resources.
/// </summary>
/// <param name="hModule">
/// A handle to a module to be searched. Starting with Windows Vista, if this is an LN file, then appropriate .mui files (if any exist) are included in
/// the search.
/// <para>If this parameter is NULL, that is equivalent to passing in a handle to the module used to create the current process.</para>
/// </param>
/// <param name="type">
/// The type of the resource for which the name is being enumerated. Alternately, rather than a string, this parameter can be MAKEINTRESOURCE(ID), where
/// ID is an integer value representing a predefined resource type.
/// </param>
/// <returns>A list of strings for each of the resources matching <paramref name="type"/>.</returns>
[PInvokeData("WinBase.h", MSDNShortId = "ms648037")]
public static IList<SafeResourceId> EnumResourceNames(SafeLibraryHandle hModule, SafeResourceId type)
{
var list = new ResList();
if (!EnumResourceNames(hModule, type, (ptr, intPtr, name, param) => { param.L.Add(new SafeResourceId(name)); return true; }, list))
Win32Error.ThrowLastError();
return list.L;
}
/// <summary>
/// Determines the location of a resource with the specified type and name in the specified module.
/// <para>To specify a language, use the FindResourceEx function.</para>
/// </summary>
/// <param name="hModule">
/// A handle to the module whose portable executable file or an accompanying MUI file contains the resource. If this parameter is Null, the function
/// searches the module used to create the current process.
/// </param>
/// <param name="lpName">
/// The name of the resource. Alternately, rather than a pointer, this parameter can be MAKEINTRESOURCE, where wInteger is the integer identifier of the resource.
/// </param>
/// <param name="lpType">
/// The resource type. Alternately, rather than a pointer, this parameter can be MAKEINTRESOURCE, where wInteger is the integer identifier of the given
/// resource type.
/// </param>
/// <returns>
/// If the function succeeds, the return value is a handle to the specified resource's information block. To obtain a handle to the resource, pass this
/// handle to the <see cref="LoadResource"/> function.
/// <para>If the function fails, the return value is NULL. To get extended error information, call GetLastError.</para>
/// </returns>
[DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)]
[SuppressUnmanagedCodeSecurity]
[PInvokeData("WinBase.h", MSDNShortId = "ms648042")]
public static extern IntPtr FindResource(SafeLibraryHandle hModule, IntPtr lpName, IntPtr lpType);
/// <summary>
/// Determines the location of a resource with the specified type and name in the specified module.
/// <para>To specify a language, use the FindResourceEx function.</para>
/// </summary>
/// <param name="hModule">
/// A handle to the module whose portable executable file or an accompanying MUI file contains the resource. If this parameter is Null, the function
/// searches the module used to create the current process.
/// </param>
/// <param name="lpName">
/// The name of the resource. Alternately, rather than a pointer, this parameter can be MAKEINTRESOURCE, where wInteger is the integer identifier of the resource.
/// </param>
/// <param name="lpType">
/// The resource type. Alternately, rather than a pointer, this parameter can be MAKEINTRESOURCE, where wInteger is the integer identifier of the given
/// resource type.
/// </param>
/// <returns>
/// If the function succeeds, the return value is a handle to the specified resource's information block. To obtain a handle to the resource, pass this
/// handle to the <see cref="LoadResource"/> function.
/// <para>If the function fails, the return value is NULL. To get extended error information, call GetLastError.</para>
/// </returns>
[DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "FindResourceW")]
[SuppressUnmanagedCodeSecurity]
[PInvokeData("WinBase.h", MSDNShortId = "ms648042")]
public static extern IntPtr FindResource(SafeLibraryHandle hModule, SafeResourceId lpName, SafeResourceId lpType);
/// <summary>Retrieves a handle that can be used to obtain a pointer to the first byte of the specified resource in memory.</summary>
/// <param name="hModule">
/// A handle to the module whose executable file contains the resource. If hModule is <see cref="SafeLibraryHandle.Null"/>, the system loads the resource
/// from the module that was used to create the current process.
/// </param>
/// <param name="hResInfo">A handle to the resource to be loaded. This handle is returned by the FindResource or FindResourceEx function.</param>
/// <returns>
/// If the function succeeds, the return value is a handle to the data associated with the resource.
/// <para>If the function fails, the return value is NULL. To get extended error information, call GetLastError.</para>
/// </returns>
[DllImport(Lib.Kernel32, ExactSpelling = true, SetLastError = true)]
[SuppressUnmanagedCodeSecurity]
[PInvokeData("WinBase.h", MSDNShortId = "ms648046")]
public static extern IntPtr LoadResource(SafeLibraryHandle hModule, IntPtr hResInfo);
/// <summary>Retrieves a pointer to the specified resource in memory.</summary>
/// <param name="hResData">A handle to the resource to be accessed. The <see cref="LoadResource"/> function returns this handle.</param>
/// <returns>If the loaded resource is available, the return value is a pointer to the first byte of the resource; otherwise, it is NULL.</returns>
[DllImport(Lib.Kernel32, ExactSpelling = true, SetLastError = true)]
[SuppressUnmanagedCodeSecurity]
[PInvokeData("WinBase.h", MSDNShortId = "ms648047")]
public static extern IntPtr LockResource(IntPtr hResData);
/// <summary>Retrieves the size, in bytes, of the specified resource.</summary>
/// <param name="hModule">A handle to the module whose executable file contains the resource.</param>
/// <param name="hResInfo">A handle to the resource. This handle must be created by using the FindResource or FindResourceEx function.</param>
/// <returns>
/// If the function succeeds, the return value is the number of bytes in the resource. If the function fails, the return value is zero. To get extended
/// error information, call GetLastError.
/// </returns>
[DllImport(Lib.Kernel32, ExactSpelling = true, SetLastError = true)]
[SuppressUnmanagedCodeSecurity]
[PInvokeData("WinBase.h", MSDNShortId = "ms648048")]
public static extern int SizeofResource(SafeLibraryHandle hModule, IntPtr hResInfo);
/// <summary>
/// Enumerates resources of a specified type within a binary module. For Windows Vista and later, this is typically a language-neutral Portable
/// Executable (LN file), and the enumeration will also include resources from the corresponding language-specific resource files (.mui files) that
/// contain localizable language resources. It is also possible for hModule to specify an .mui file, in which case only that file is searched for resources.
/// </summary>
/// <param name="hModule">
/// A handle to a module to be searched. Starting with Windows Vista, if this is an LN file, then appropriate .mui files (if any exist) are included in
/// the search.
/// <para>If this parameter is NULL, that is equivalent to passing in a handle to the module used to create the current process.</para>
/// </param>
/// <param name="lpszType">
/// The type of the resource for which the name is being enumerated. Alternately, rather than a pointer, this parameter can be MAKEINTRESOURCE(ID), where
/// ID is an integer value representing a predefined resource type.
/// </param>
/// <param name="lpEnumFunc">A pointer to the callback function to be called for each enumerated resource name or ID.</param>
/// <param name="lParam">An application-defined value passed to the callback function. This parameter can be used in error checking.</param>
/// <returns>
/// The return value is TRUE if the function succeeds or FALSE if the function does not find a resource of the type specified, or if the function fails
/// for another reason. To get extended error information, call GetLastError.
/// </returns>
[DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
[PInvokeData("FileAPI.h", MSDNShortId = "aa365467")]
private static extern bool EnumResourceNames(SafeLibraryHandle hModule, IntPtr lpszType, EnumResNameProcManaged lpEnumFunc, ResList lParam);
private class ResList { public List<SafeResourceId> L { get; } = new List<SafeResourceId>(); }
}
}

View File

@ -0,0 +1,120 @@
using System;
using System.Runtime.InteropServices;
namespace Vanara.PInvoke
{
public static partial class Kernel32
{
/// <summary>Retrieves a handle that can be used by the <c>UpdateResource</c> function to add, delete, or replace resources in a binary module.</summary>
/// <param name="pFileName">
/// <para>Type: <c>LPCTSTR</c></para>
/// <para>
/// The binary file in which to update resources. An application must be able to obtain write-access to this file; the file referenced by pFileName
/// cannot be currently executing. If pFileName does not specify a full path, the system searches for the file in the current directory.
/// </para>
/// </param>
/// <param name="bDeleteExistingResources">
/// <para>Type: <c>BOOL</c></para>
/// <para>
/// Indicates whether to delete the pFileName parameter's existing resources. If this parameter is <c>TRUE</c>, existing resources are deleted and the
/// updated file includes only resources added with the <c>UpdateResource</c> function. If this parameter is <c>FALSE</c>, the updated file includes
/// existing resources unless they are explicitly deleted or replaced by using <c>UpdateResource</c>.
/// </para>
/// </param>
/// <returns>
/// <para>Type: <c>HANDLE</c></para>
/// <para>
/// If the function succeeds, the return value is a handle that can be used by the <c>UpdateResource</c> and <c>EndUpdateResource</c> functions. The
/// return value is <c>NULL</c> if the specified file is not a PE, the file does not exist, or the file cannot be opened for writing. To get extended
/// error information, call <c>GetLastError</c>.
/// </para>
/// </returns>
// HANDLE WINAPI BeginUpdateResource( _In_ LPCTSTR pFileName, _In_ BOOL bDeleteExistingResources);
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms648030(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)]
[PInvokeData("Winbase.h", MSDNShortId = "ms648030")]
public static extern IntPtr BeginUpdateResource([In] string pFileName, [MarshalAs(UnmanagedType.Bool)] bool bDeleteExistingResources);
/// <summary>Commits or discards changes made prior to a call to <c>UpdateResource</c>.</summary>
/// <param name="hUpdate">
/// <para>Type: <c>HANDLE</c></para>
/// <para>A module handle returned by the <c>BeginUpdateResource</c> function, and used by <c>UpdateResource</c>, referencing the file to be updated.</para>
/// </param>
/// <param name="fDiscard">
/// <para>Type: <c>BOOL</c></para>
/// <para>
/// Indicates whether to write the resource updates to the file. If this parameter is <c>TRUE</c>, no changes are made. If it is <c>FALSE</c>, the
/// changes are made: the resource updates will take effect.
/// </para>
/// </param>
/// <returns>
/// <para>Type: <c>BOOL</c></para>
/// <para>
/// Returns <c>TRUE</c> if the function succeeds; <c>FALSE</c> otherwise. If the function succeeds and fDiscard is <c>TRUE</c>, then no resource updates
/// are made to the file; otherwise all successful resource updates are made to the file. To get extended error information, call <c>GetLastError</c>.
/// </para>
/// </returns>
// BOOL WINAPI EndUpdateResource( _In_ HANDLE hUpdate, _In_ BOOL fDiscard);
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms648032(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)]
[PInvokeData("Winbase.h", MSDNShortId = "ms648032")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool EndUpdateResource([In] IntPtr hUpdate, [MarshalAs(UnmanagedType.Bool)] bool fDiscard);
/// <summary>
/// Adds, deletes, or replaces a resource in a portable executable (PE) file. There are some restrictions on resource updates in files that contain
/// Resource Configuration (RC Config) data: language-neutral (LN) files and language-specific resource (.mui) files.
/// </summary>
/// <param name="hUpdate">
/// <para>Type: <c>HANDLE</c></para>
/// <para>A module handle returned by the <c>BeginUpdateResource</c> function, referencing the file to be updated.</para>
/// </param>
/// <param name="lpType">
/// <para>Type: <c>LPCTSTR</c></para>
/// <para>
/// The resource type to be updated. Alternatively, rather than a pointer, this parameter can be <c>MAKEINTRESOURCE</c>(ID), where ID is an integer value
/// representing a predefined resource type. If the first character of the string is a pound sign (#), then the remaining characters represent a decimal
/// number that specifies the integer identifier of the resource type. For example, the string "#258" represents the identifier 258.
/// </para>
/// <para>For a list of predefined resource types, see Resource Types.</para>
/// </param>
/// <param name="lpName">
/// <para>Type: <c>LPCTSTR</c></para>
/// <para>
/// The name of the resource to be updated. Alternatively, rather than a pointer, this parameter can be <c>MAKEINTRESOURCE</c>(ID), where ID is a
/// resource ID. When creating a new resource do not use a string that begins with a '#' character for this parameter.
/// </para>
/// </param>
/// <param name="wLanguage">
/// <para>Type: <c>WORD</c></para>
/// <para>
/// The language identifier of the resource to be updated. For a list of the primary language identifiers and sublanguage identifiers that make up a
/// language identifier, see the <c>MAKELANGID</c> macro.
/// </para>
/// </param>
/// <param name="lpData">
/// <para>Type: <c>LPVOID</c></para>
/// <para>
/// The resource data to be inserted into the file indicated by hUpdate. If the resource is one of the predefined types, the data must be valid and
/// properly aligned. Note that this is the raw binary data to be stored in the file indicated by hUpdate, not the data provided by <c>LoadIcon</c>,
/// <c>LoadString</c>, or other resource-specific load functions. All data containing strings or text must be in Unicode format. lpData must not point to
/// ANSI data.
/// </para>
/// <para>If lpData is <c>NULL</c> and cbData is 0, the specified resource is deleted from the file indicated by hUpdate.</para>
/// </param>
/// <param name="cbData">
/// <para>Type: <c>DWORD</c></para>
/// <para>The size, in bytes, of the resource data at lpData.</para>
/// </param>
/// <returns>
/// <para>Type: <c>BOOL</c></para>
/// <para>Returns <c>TRUE</c> if successful or <c>FALSE</c> otherwise. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// BOOL WINAPI UpdateResource( _In_ HANDLE hUpdate, _In_ LPCTSTR lpType, _In_ LPCTSTR lpName, _In_ WORD wLanguage, _In_opt_ LPVOID lpData, _In_ DWORD cbData);
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms648049(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)]
[PInvokeData("Winbase.h", MSDNShortId = "ms648049")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool UpdateResource([In] IntPtr hUpdate, [In] string lpType, [In] string lpName, ushort wLanguage, [In] IntPtr lpData, uint cbData);
}
}

View File

@ -0,0 +1,125 @@
using System.Runtime.InteropServices;
using FILETIME = System.Runtime.InteropServices.ComTypes.FILETIME;
namespace Vanara.PInvoke
{
public static partial class Kernel32
{
/// <summary>Converts MS-DOS date and time values to a file time.</summary>
/// <param name="wFatDate">
/// <para>The MS-DOS date. The date is a packed value with the following format.</para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Bits</term>
/// <term>Description</term>
/// </listheader>
/// <item>
/// <term>0-4</term>
/// <term>Day of the month (131)</term>
/// </item>
/// <item>
/// <term>5-8</term>
/// <term>Month (1 = January, 2 = February, and so on)</term>
/// </item>
/// <item>
/// <term>9-15</term>
/// <term>Year offset from 1980 (add 1980 to get actual year)</term>
/// </item>
/// </list>
/// </para>
/// </param>
/// <param name="wFatTime">
/// <para>The MS-DOS time. The time is a packed value with the following format.</para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Bits</term>
/// <term>Description</term>
/// </listheader>
/// <item>
/// <term>0-4</term>
/// <term>Second divided by 2</term>
/// </item>
/// <item>
/// <term>5-10</term>
/// <term>Minute (059)</term>
/// </item>
/// <item>
/// <term>11-15</term>
/// <term>Hour (023 on a 24-hour clock)</term>
/// </item>
/// </list>
/// </para>
/// </param>
/// <param name="lpFileTime">A pointer to a <c>FILETIME</c> structure that receives the converted file time.</param>
/// <returns>
/// <para>If the function succeeds, the return value is nonzero.</para>
/// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// BOOL WINAPI DosDateTimeToFileTime( _In_ WORD wFatDate, _In_ WORD wFatTime, _Out_ LPFILETIME lpFileTime); https://msdn.microsoft.com/en-us/library/windows/desktop/ms724247(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("Winbase.h", MSDNShortId = "ms724247")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool DosDateTimeToFileTime(ushort wFatDate, ushort wFatTime, out FILETIME lpFileTime);
/// <summary>Converts a file time to MS-DOS date and time values.</summary>
/// <param name="lpFileTime">A pointer to a <c>FILETIME</c> structure containing the file time to convert to MS-DOS date and time format.</param>
/// <param name="lpFatDate">
/// <para>A pointer to a variable to receive the MS-DOS date. The date is a packed value with the following format.</para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Bits</term>
/// <term>Description</term>
/// </listheader>
/// <item>
/// <term>04</term>
/// <term>Day of the month (131)</term>
/// </item>
/// <item>
/// <term>58</term>
/// <term>Month (1 = January, 2 = February, etc.)</term>
/// </item>
/// <item>
/// <term>9-15</term>
/// <term>Year offset from 1980 (add 1980 to get actual year)</term>
/// </item>
/// </list>
/// </para>
/// </param>
/// <param name="lpFatTime">
/// <para>A pointer to a variable to receive the MS-DOS time. The time is a packed value with the following format.</para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Bits</term>
/// <term>Description</term>
/// </listheader>
/// <item>
/// <term>04</term>
/// <term>Second divided by 2</term>
/// </item>
/// <item>
/// <term>510</term>
/// <term>Minute (059)</term>
/// </item>
/// <item>
/// <term>1115</term>
/// <term>Hour (023 on a 24-hour clock)</term>
/// </item>
/// </list>
/// </para>
/// </param>
/// <returns>
/// <para>If the function succeeds, the return value is nonzero.</para>
/// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// BOOL WINAPI FileTimeToDosDateTime( _In_ const FILETIME *lpFileTime, _Out_ LPWORD lpFatDate, _Out_ LPWORD lpFatTime); https://msdn.microsoft.com/en-us/library/windows/desktop/ms724274(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("Winbase.h", MSDNShortId = "ms724274")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool FileTimeToDosDateTime([In] ref FILETIME lpFileTime, out ushort lpFatDate, out ushort lpFatTime);
}
}

View File

@ -1,413 +1,24 @@
using System;
using System.ComponentModel;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
using Vanara.Extensions;
using Vanara.InteropServices;
using FILETIME = System.Runtime.InteropServices.ComTypes.FILETIME;
namespace Vanara.PInvoke
{
public static partial class Kernel32
{
/// <summary>Flags passed to the <see cref="Kernel32.FormatMessage(Vanara.PInvoke.Kernel32.FormatMessageFlags,Vanara.PInvoke.Kernel32.SafeLibraryHandle,uint,uint,ref System.IntPtr,uint,string[])"/> method.</summary>
[PInvokeData("winbase.h")]
[Flags]
public enum FormatMessageFlags
{
/// <summary>
/// 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.
/// <para>
/// 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.
/// </para>
/// <para>
/// 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.
/// </para>
/// <para>
/// 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.
/// </para>
/// <para>
/// 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.
/// </para>
/// <para>
/// 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.
/// </para>
/// </summary>
FORMAT_MESSAGE_ALLOCATE_BUFFER = 0x100,
/// <summary>
/// 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.
/// </summary>
FORMAT_MESSAGE_ARGUMENT_ARRAY = 0x2000,
/// <summary>
/// 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 <see cref="FORMAT_MESSAGE_FROM_STRING"/>.
/// <para>If the module has no message table resource, the function fails with ERROR_RESOURCE_TYPE_NOT_FOUND.</para>
/// </summary>
FORMAT_MESSAGE_FROM_HMODULE = 0x800,
/// <summary>
/// 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 <see cref="FORMAT_MESSAGE_FROM_HMODULE"/> or <see cref="FORMAT_MESSAGE_FROM_SYSTEM"/>.
/// </summary>
FORMAT_MESSAGE_FROM_STRING = 0x400,
/// <summary>
/// The function should search the system message-table resource(s) for the requested message. If this flag is specified with
/// <see cref="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 <see cref="FORMAT_MESSAGE_FROM_STRING"/>.
/// <para>
/// 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.
/// </para>
/// </summary>
FORMAT_MESSAGE_FROM_SYSTEM = 0x1000,
/// <summary>
/// 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.
/// </summary>
FORMAT_MESSAGE_IGNORE_INSERTS = 0x200,
/// <summary>
/// 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.
/// <para>
/// 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.
/// </para>
/// </summary>
FORMAT_MESSAGE_MAX_WIDTH_MASK = 0xff
}
/// <summary>The memory allocation attributes.</summary>
[PInvokeData("MinWinBase.h")]
[Flags]
public enum LocalMemoryFlags
{
/// <summary>Allocates fixed memory. The return value is a pointer to the memory object.</summary>
LMEM_FIXED = 0x0000,
/// <summary>
/// Allocates movable memory. Memory blocks are never moved in physical memory, but they can be moved within the default heap. The return value is a
/// handle to the memory object. To translate the handle to a pointer, use the LocalLock function. This value cannot be combined with LMEM_FIXED.
/// </summary>
LMEM_MOVEABLE = 0x0002,
/// <summary>Obsolete.</summary>
[Obsolete]
LMEM_NOCOMPACT = 0x0010,
/// <summary>Obsolete.</summary>
[Obsolete]
LMEM_NODISCARD = 0x0020,
/// <summary>Initializes memory contents to zero.</summary>
LMEM_ZEROINIT = 0x0040,
/// <summary>
/// If the LMEM_MODIFY flag is specified in LocalReAlloc, this parameter modifies the attributes of the memory object, and the uBytes parameter is ignored.
/// </summary>
LMEM_MODIFY = 0x0080,
/// <summary>Obsolete.</summary>
[Obsolete]
LMEM_DISCARDABLE = 0x0F00,
/// <summary>Valid flags.</summary>
LMEM_VALID_FLAGS = 0x0F72,
/// <summary>Indicates that the local handle is not valid</summary>
LMEM_INVALID_HANDLE = 0x8000,
/// <summary>Combines LMEM_MOVEABLE and LMEM_ZEROINIT.</summary>
LHND = (LMEM_MOVEABLE | LMEM_ZEROINIT),
/// <summary>Combines LMEM_FIXED and LMEM_ZEROINIT.</summary>
LPTR = (LMEM_FIXED | LMEM_ZEROINIT),
/// <summary>Same as LMEM_MOVEABLE.</summary>
NONZEROLHND = (LMEM_MOVEABLE),
/// <summary>Same as LMEM_FIXED.</summary>
NONZEROLPTR = (LMEM_FIXED)
}
/// <summary>Closes an open object handle.</summary>
/// <param name="hObject">A valid handle to an open object.</param>
/// <returns>
/// 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.
/// </returns>
[PInvokeData("WinBase.h", MSDNShortId = "ms724211")]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success), DllImport(Lib.Kernel32, ExactSpelling = true, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool CloseHandle(IntPtr hObject);
/// <summary>Converts a file time to system time format. System time is based on Coordinated Universal Time (UTC).</summary>
/// <param name="lpFileTime">
/// A pointer to a FILETIME structure containing the file time to be converted to system (UTC) date and time format. This value must be less than
/// 0x8000000000000000. Otherwise, the function fails.
/// </param>
/// <param name="lpSystemTime">A pointer to a SYSTEMTIME structure to receive the converted file time.</param>
/// <returns>
/// 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.
/// </returns>
[PInvokeData("FileAPI.h", MSDNShortId = "ms724280")]
[DllImport(Lib.Kernel32, ExactSpelling = true, SetLastError = true), SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool FileTimeToSystemTime(ref FILETIME lpFileTime, ref SYSTEMTIME lpSystemTime);
/// <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.
/// </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="lpBuffer">
/// A pointer to a buffer that receives the null-terminated string that specifies the formatted message. If dwFlags includes
/// <see cref="FormatMessageFlags.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.
/// </param>
/// <param name="nSize">
/// If the <see cref="FormatMessageFlags.FORMAT_MESSAGE_ALLOCATE_BUFFER"/> flag is not set, this parameter specifies the size of the output buffer, in
/// TCHARs. If <see cref="FormatMessageFlags.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.
/// </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>
/// <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 GetLastError.
/// </returns>
[DllImport(Lib.Kernel32, CharSet = CharSet.Auto, SetLastError = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms679351")]
public static extern int FormatMessage(FormatMessageFlags dwFlags, SafeLibraryHandle lpSource, uint dwMessageId, uint dwLanguageId, ref IntPtr lpBuffer,
uint nSize, string[] 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.
/// </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="lpBuffer">
/// A pointer to a buffer that receives the null-terminated string that specifies the formatted message. If dwFlags includes
/// <see cref="FormatMessageFlags.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.
/// </param>
/// <param name="nSize">
/// If the <see cref="FormatMessageFlags.FORMAT_MESSAGE_ALLOCATE_BUFFER"/> flag is not set, this parameter specifies the size of the output buffer, in
/// TCHARs. If <see cref="FormatMessageFlags.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.
/// </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>
/// <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 GetLastError.
/// </returns>
[DllImport(Lib.Kernel32, CharSet = CharSet.Auto, SetLastError = true)]
[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);
/// <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.
/// </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="lpBuffer">
/// A pointer to a buffer that receives the null-terminated string that specifies the formatted message. If dwFlags includes
/// <see cref="FormatMessageFlags.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.
/// </param>
/// <param name="nSize">
/// If the <see cref="FormatMessageFlags.FORMAT_MESSAGE_ALLOCATE_BUFFER"/> flag is not set, this parameter specifies the size of the output buffer, in
/// TCHARs. If <see cref="FormatMessageFlags.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.
/// </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>
/// <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 GetLastError.
/// </returns>
[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);
/// <summary>
/// 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.
/// </summary>
/// <param name="id">The message identifier for the requested message.</param>
/// <param name="args">
/// 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.
/// </param>
/// <param name="hLib">A handle to the module that contains the message table to search.</param>
/// <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="langId">
/// 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.
/// </param>
/// <returns>
/// If the function succeeds, the return value is the string that specifies the formatted message. To get extended error information, call GetLastError.
/// </returns>
[PInvokeData("WinBase.h", MSDNShortId = "ms679351")]
public static string FormatMessage(uint id, string[] args = null, SafeLibraryHandle hLib = null, 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 != null) 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 ?? SafeLibraryHandle.Null, id, langId, ref ptr, 0, args);
if (ret == 0) Win32Error.ThrowLastError();
return new SafeLocalHandle(ptr, 0).ToString(-1);
}
/// <summary>
/// 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.
/// </summary>
/// <param name="formatString">Pointer to a string that consists of unformatted message text. It will be scanned for inserts and formatted accordingly.</param>
/// <param name="args">
/// 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.
/// </param>
/// <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>
/// <returns>
/// If the function succeeds, the return value is the string that specifies the formatted message. To get extended error information, call GetLastError.
/// </returns>
[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);
}
/*/// <summary>
/// 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.
/// </summary>
/// <param name="formatString">Pointer to a string that consists of unformatted message text. It will be scanned for inserts and formatted accordingly.</param>
/// <param name="args">
/// 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.
/// </param>
/// <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>
/// <returns>
/// If the function succeeds, the return value is the string that specifies the formatted message. To get extended error information, call GetLastError.
/// </returns>
/// message text, processing any embedded insert sequences if requested. </summary> <param name="formatString">Pointer to a string that consists of
/// unformatted message text. It will be scanned for inserts and formatted accordingly.</param> <param name="args"> 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. </param> <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> <returns> If the function succeeds, the return value is the string that specifies the formatted
/// message. To get extended error information, call GetLastError. </returns>
[PInvokeData("WinBase.h", MSDNShortId = "ms679351")]
private static string FormatMessage(string formatString, object[] args, FormatMessageFlags flags = 0)
{
@ -435,404 +46,47 @@ namespace Vanara.PInvoke
return new SafeLocalHandle(ptr, 0).ToString(-1);
}*/
/// <summary>
/// Frees the loaded dynamic-link library (DLL) module and, if necessary, decrements its reference count. When the reference count reaches zero, the
/// module is unloaded from the address space of the calling process and the handle is no longer valid.
/// </summary>
/// <param name="hModule">
/// A handle to the loaded library module. The LoadLibrary, LoadLibraryEx, GetModuleHandle, or GetModuleHandleEx function returns this handle.
/// <summary>Determines the length of the specified string (not including the terminating null character).</summary>
/// <param name="lpString">
/// <para>Type: <c>LPCTSTR</c></para>
/// <para>The null-terminated string to be checked.</para>
/// </param>
/// <returns>
/// If the function succeeds, the return value is a nonzero value.
/// <para>If the function fails, the return value is zero. To get extended error information, call GetLastError.</para>
/// <para>Type: <c>int</c></para>
/// <para>The function returns the length of the string, in characters. If lpString is <c>NULL</c>, the function returns 0.</para>
/// </returns>
[DllImport(Lib.Kernel32, ExactSpelling = true, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
[PInvokeData("WinBase.h", MSDNShortId = "ms683152")]
public static extern bool FreeLibrary(IntPtr hModule);
/// <summary>Retrieves a pseudo handle for the current process.</summary>
/// <returns>The return value is a pseudo handle to the current process.</returns>
/// <remarks>
/// A pseudo handle is a special constant, currently (HANDLE)-1, that is interpreted as the current process handle. For compatibility with future
/// operating systems, it is best to call GetCurrentProcess instead of hard-coding this constant value. The calling process can use a pseudo handle to
/// specify its own process whenever a process handle is required. Pseudo handles are not inherited by child processes.
/// <para>This handle has the PROCESS_ALL_ACCESS access right to the process object.</para>
/// <para>
/// Windows Server 2003 and Windows XP: This handle has the maximum access allowed by the security descriptor of the process to the primary token of the process.
/// </para>
/// <para>
/// A process can create a "real" handle to itself that is valid in the context of other processes, or that can be inherited by other processes, by
/// specifying the pseudo handle as the source handle in a call to the DuplicateHandle function. A process can also use the OpenProcess function to open
/// a real handle to itself.
/// </para>
/// <para>
/// The pseudo handle need not be closed when it is no longer needed. Calling the <see cref="CloseHandle"/> function with a pseudo handle has no
/// effect.If the pseudo handle is duplicated by DuplicateHandle, the duplicate handle must be closed.
/// </para>
/// </remarks>
[DllImport(Lib.Kernel32, ExactSpelling = true, SetLastError = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms683179")]
public static extern IntPtr GetCurrentProcess();
/// <summary>Retrieves a pseudo handle for the calling thread.</summary>
/// <returns>The return value is a pseudo handle for the current thread.</returns>
/// <remarks>
/// A pseudo handle is a special constant that is interpreted as the current thread handle. The calling thread can use this handle to specify itself
/// whenever a thread handle is required. Pseudo handles are not inherited by child processes.
/// <para>This handle has the THREAD_ALL_ACCESS access right to the thread object. For more information, see Thread Security and Access Rights.</para>
/// <para>
/// Windows Server 2003 and Windows XP: This handle has the maximum access allowed by the security descriptor of the thread to the primary token of the process.
/// </para>
/// <para>
/// The function cannot be used by one thread to create a handle that can be used by other threads to refer to the first thread. The handle is always
/// interpreted as referring to the thread that is using it. A thread can create a "real" handle to itself that can be used by other threads, or
/// inherited by other processes, by specifying the pseudo handle as the source handle in a call to the DuplicateHandle function.
/// </para>
/// <para>
/// The pseudo handle need not be closed when it is no longer needed. Calling the CloseHandle function with this handle has no effect. If the pseudo
/// handle is duplicated by DuplicateHandle, the duplicate handle must be closed.
/// </para>
/// <para>
/// Do not create a thread while impersonating a security context. The call will succeed, however the newly created thread will have reduced access
/// rights to itself when calling GetCurrentThread. The access rights granted this thread will be derived from the access rights the impersonated user
/// has to the process. Some access rights including THREAD_SET_THREAD_TOKEN and THREAD_GET_CONTEXT may not be present, leading to unexpected failures.
/// </para>
/// </remarks>
[DllImport(Lib.Kernel32, ExactSpelling = true, SetLastError = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms683182")]
public static extern IntPtr GetCurrentThread();
/// <summary>Retrieves the thread identifier of the calling thread.</summary>
/// <returns>The return value is the thread identifier of the calling thread.</returns>
[DllImport(Lib.Kernel32, ExactSpelling = true, SetLastError = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms683183")]
public static extern uint GetCurrentThreadId();
/// <summary>
/// Retrieves the fully qualified path for the file that contains the specified module. The module must have been loaded by the current process.
/// <para>To locate the file for a module that was loaded by another process, use the GetModuleFileNameEx function.</para>
/// </summary>
/// <param name="hModule">
/// A handle to the loaded module whose path is being requested. If this parameter is NULL, GetModuleFileName retrieves the path of the executable file
/// of the current process.
/// <para>
/// The GetModuleFileName function does not retrieve the path for modules that were loaded using the LOAD_LIBRARY_AS_DATAFILE flag. For more information,
/// see LoadLibraryEx.
/// </para>
/// </param>
/// <param name="lpFilename">
/// A pointer to a buffer that receives the fully qualified path of the module. If the length of the path is less than the size that the nSize parameter
/// specifies, the function succeeds and the path is returned as a null-terminated string.
/// <para>
/// If the length of the path exceeds the size that the nSize parameter specifies, the function succeeds and the string is truncated to nSize characters
/// including the terminating null character.
/// </para>
/// <para><c>Windows XP:</c> The string is truncated to nSize characters and is not null-terminated.</para>
/// <para>
/// The string returned will use the same format that was specified when the module was loaded. Therefore, the path can be a long or short file name, and
/// can use the prefix "\\?\". For more information, see Naming a File.
/// </para>
/// </param>
/// <param name="nSize">The size of the lpFilename buffer, in TCHARs.</param>
/// <returns>
/// If the function succeeds, the return value is the length of the string that is copied to the buffer, in characters, not including the terminating
/// null character. If the buffer is too small to hold the module name, the string is truncated to nSize characters including the terminating null
/// character, the function returns nSize, and the function sets the last error to ERROR_INSUFFICIENT_BUFFER.
/// <para>
/// <c>Windows XP:</c> If the buffer is too small to hold the module name, the function returns nSize. The last error code remains ERROR_SUCCESS. If
/// nSize is zero, the return value is zero and the last error code is ERROR_SUCCESS.
/// </para>
/// <para>If the function fails, the return value is 0 (zero). To get extended error information, call GetLastError.</para>
/// </returns>
[SecurityCritical, SuppressUnmanagedCodeSecurity, DllImport(Lib.Kernel32, CharSet = CharSet.Auto, SetLastError = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms683197")]
public static extern int GetModuleFileName(SafeLibraryHandle hModule, [Out] StringBuilder lpFilename, int nSize);
/// <summary>
/// Retrieves the fully qualified path for the file that contains the specified module. The module must have been loaded by the current process.
/// <para>To locate the file for a module that was loaded by another process, use the GetModuleFileNameEx function.</para>
/// </summary>
/// <param name="hModule">
/// A handle to the loaded module whose path is being requested. If this parameter is NULL, GetModuleFileName retrieves the path of the executable file
/// of the current process.
/// <para>
/// The GetModuleFileName function does not retrieve the path for modules that were loaded using the LOAD_LIBRARY_AS_DATAFILE flag. For more information,
/// see LoadLibraryEx.
/// </para>
/// </param>
/// <returns>
/// The string returned will use the same format that was specified when the module was loaded. Therefore, the path can be a long or short file name, and
/// can use the prefix "\\?\". For more information, see Naming a File.
/// </returns>
[SecurityCritical]
[PInvokeData("WinBase.h", MSDNShortId = "ms683197")]
public static string GetModuleFileName(SafeLibraryHandle hModule)
{
var buffer = new StringBuilder(MAX_PATH);
Label_000B:
var num1 = GetModuleFileName(hModule, buffer, buffer.Capacity);
if (num1 == 0)
throw new Win32Exception();
if (num1 == buffer.Capacity && Marshal.GetLastWin32Error() == Win32Error.ERROR_INSUFFICIENT_BUFFER)
{
buffer.EnsureCapacity(buffer.Capacity * 2);
goto Label_000B;
}
return buffer.ToString();
}
/// <summary>The GetProcAddress function retrieves the address of an exported function or variable from the specified dynamic-link library (DLL).</summary>
/// <param name="hModule">
/// Handle to the DLL module that contains the function or variable. The LoadLibrary or GetModuleHandle function returns this handle.
/// </param>
/// <param name="lpProcName">
/// Pointer to a null-terminated string containing the function or variable name, or the function's ordinal value. If this parameter is an ordinal value,
/// it must be in the low-order word; the high-order word must be zero.
/// </param>
/// <returns>
/// If the function succeeds, the return value is the address of the exported function or variable. <br></br><br>If the function fails, the return value
/// is NULL. To get extended error information, call Marshal.GetLastWin32Error.</br>
/// </returns>
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms683212")]
public static extern IntPtr GetProcAddress(SafeLibraryHandle hModule, [MarshalAs(UnmanagedType.LPStr)] string lpProcName);
/// <summary>
/// The GlobalLock function locks a global memory object and returns a pointer to the first byte of the object's memory block. GlobalLock function
/// increments the lock count by one. Needed for the clipboard functions when getting the data from IDataObject
/// </summary>
/// <param name="hMem"></param>
/// <returns></returns>
[DllImport(Lib.Kernel32, ExactSpelling = true, SetLastError = true)]
[PInvokeData("WinBase.h", MSDNShortId = "aa366584")]
public static extern IntPtr GlobalLock(IntPtr hMem);
/// <summary>The GlobalUnlock function decrements the lock count associated with a memory object.</summary>
/// <param name="hMem"></param>
/// <returns></returns>
[DllImport(Lib.Kernel32, ExactSpelling = true, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
[PInvokeData("WinBase.h", MSDNShortId = "aa366595")]
public static extern bool GlobalUnlock(IntPtr hMem);
/// <summary>
/// Allocates the specified number of bytes from the heap. <note>The local functions have greater overhead and provide fewer features than other memory
/// management functions. New applications should use the heap functions unless documentation states that a local function should be used. For more
/// information, see Global and Local Functions.</note>
/// </summary>
/// <param name="uFlags">
/// The memory allocation attributes. The default is the LMEM_FIXED value. This parameter can be one or more of the following values, except for the
/// incompatible combinations that are specifically noted.
/// <list type="table">
/// <listheader>
/// <term>Value</term>
/// <term>Meaning</term>
/// </listheader>
/// <item>
/// <term>
/// <c>LHND</c>
/// <para>0x0042</para>
/// </term>
/// <term>Combines LMEM_MOVEABLE and LMEM_ZEROINIT.</term>
/// </item>
/// <item>
/// <term>
/// <c>LMEM_FIXED</c>
/// <para>0x0000</para>
/// </term>
/// <term>Allocates fixed memory. The return value is a pointer to the memory object.</term>
/// </item>
/// <item>
/// <term>
/// <c>LMEM_MOVEABLE</c>
/// <para>0x0002</para>
/// </term>
/// <term>
/// Allocates movable memory. Memory blocks are never moved in physical memory, but they can be moved within the default heap.
/// <para>The return value is a handle to the memory object. To translate the handle to a pointer, use the LocalLock function.</para>
/// <para>This value cannot be combined with LMEM_FIXED.</para>
/// </term>
/// </item>
/// <item>
/// <term>
/// <c>LMEM_ZEROINIT</c>
/// <para>0x0040</para>
/// </term>
/// <term>Initializes memory contents to zero.</term>
/// </item>
/// <item>
/// <term>
/// <c>LPTR</c>
/// <para>0x0040</para>
/// </term>
/// <term>Combines LMEM_FIXED and LMEM_ZEROINIT.</term>
/// </item>
/// <item>
/// <term><c>NONZEROLHND</c></term>
/// <term>Same as LMEM_MOVEABLE.</term>
/// </item>
/// <item>
/// <term><c>NONZEROLPTR</c></term>
/// <term>Same as LMEM_FIXED.</term>
/// </item>
/// </list>
/// <para>The following values are obsolete, but are provided for compatibility with 16-bit Windows. They are ignored.</para>
/// <list type="bullet">
/// <item>
/// <term>LMEM_DISCARDABLE</term>
/// </item>
/// <item>
/// <term>LMEM_NOCOMPACT</term>
/// </item>
/// <item>
/// <term>LMEM_NODISCARD</term>
/// </item>
/// </list>
/// </param>
/// <param name="uBytes">
/// The number of bytes to allocate. If this parameter is zero and the uFlags parameter specifies LMEM_MOVEABLE, the function returns a handle to a
/// memory object that is marked as discarded.
/// </param>
/// <returns>
/// If the function succeeds, the return value is a handle to the newly allocated memory object. If the function fails, the return value is NULL. To get
/// extended error information, call GetLastError.
/// </returns>
/// <remarks>
/// Windows memory management does not provide a separate local heap and global heap. Therefore, the LocalAlloc and GlobalAlloc functions are essentially
/// the same.
/// <para>
/// The movable-memory flags LHND, LMEM_MOVABLE, and NONZEROLHND add unnecessary overhead and require locking to be used safely. They should be avoided
/// unless documentation specifically states that they should be used.
/// </para>
/// <para>
/// New applications should use the heap functions unless the documentation specifically states that a local function should be used. For example, some
/// Windows functions allocate memory that must be freed with LocalFree.
/// </para>
/// <para>
/// If the heap does not contain sufficient free space to satisfy the request, LocalAlloc returns NULL. Because NULL is used to indicate an error,
/// virtual address zero is never allocated. It is, therefore, easy to detect the use of a NULL pointer.
/// </para>
/// <para>
/// If the LocalAlloc function succeeds, it allocates at least the amount requested. If the amount allocated is greater than the amount requested, the
/// process can use the entire amount. To determine the actual number of bytes allocated, use the LocalSize function.
/// </para>
/// <para>To free the memory, use the LocalFree function. It is not safe to free memory allocated with LocalAlloc using GlobalFree.</para>
/// </remarks>
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "aa366723")]
public static extern IntPtr LocalAlloc(LocalMemoryFlags uFlags, UIntPtr uBytes);
/// <summary>
/// Frees the specified local memory object and invalidates its handle. <note>The local functions have greater overhead and provide fewer features than
/// other memory management functions. New applications should use the heap functions unless documentation states that a local function should be used.
/// For more information, see Global and Local Functions.</note>
/// </summary>
/// <param name="hMem">
/// A handle to the local memory object. This handle is returned by either the LocalAlloc or LocalReAlloc function. It is not safe to free memory
/// allocated with GlobalAlloc.
/// </param>
/// <returns>
/// If the function succeeds, the return value is NULL. If the function fails, the return value is equal to a handle to the local memory object. To get
/// extended error information, call GetLastError.
/// </returns>
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "aa366730")]
public static extern IntPtr LocalFree(IntPtr hMem);
/// <summary>
/// Changes the size or the attributes of a specified local memory object. The size can increase or decrease. <note>The local functions have greater
/// overhead and provide fewer features than other memory management functions. New applications should use the heap functions unless documentation
/// states that a local function should be used. For more information, see Global and Local Functions.</note>
/// </summary>
/// <param name="hMem">A handle to the local memory object to be reallocated. This handle is returned by either the LocalAlloc or LocalReAlloc function.</param>
/// <param name="uBytes">The new size of the memory block, in bytes. If uFlags specifies LMEM_MODIFY, this parameter is ignored.</param>
/// <param name="uFlags">
/// The reallocation options. If LMEM_MODIFY is specified, the function modifies the attributes of the memory object only (the uBytes parameter is
/// ignored.) Otherwise, the function reallocates the memory object.
/// <para>You can optionally combine LMEM_MODIFY with the following value.</para>
/// <list type="table">
/// <listheader>
/// <term>Value</term>
/// <term>Meaning</term>
/// </listheader>
/// <item>
/// <term>
/// <c>LMEM_MOVEABLE</c>
/// <para>0x0002</para>
/// </term>
/// <term>
/// Allocates fixed or movable memory.
/// <para>
/// If the memory is a locked LMEM_MOVEABLE memory block or a LMEM_FIXED memory block and this flag is not specified, the memory can only be reallocated
/// in place.
/// </para>
/// </term>
/// </item>
/// </list>
/// <para>
/// If the memory is a locked LMEM_MOVEABLE memory block or a LMEM_FIXED memory block and this flag is not specified, the memory can only be reallocated
/// in place.
/// </para>
/// <para>If this parameter does not specify LMEM_MODIFY, you can use the following value.</para>
/// <list type="table">
/// <listheader>
/// <term>Value</term>
/// <term>Meaning</term>
/// </listheader>
/// <item>
/// <term>
/// <c>LMEM_ZEROINIT</c>
/// <para>0x0040</para>
/// </term>
/// <term>Causes the additional memory contents to be initialized to zero if the memory object is growing in size.</term>
/// </item>
/// </list>
/// </param>
/// <returns>
/// If the function succeeds, the return value is a handle to the reallocated memory object. If the function fails, the return value is NULL. To get
/// extended error information, call GetLastError.
/// </returns>
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "aa366742")]
public static extern IntPtr LocalReAlloc(IntPtr hMem, UIntPtr uBytes, LocalMemoryFlags uFlags);
/// <summary>
/// Retrieves the current size of the specified local memory object, in bytes. <note>The local functions have greater overhead and provide fewer features
/// than other memory management functions. New applications should use the heap functions unless documentation states that a local function should be
/// used. For more information, see Global and Local Functions.</note>
/// </summary>
/// <param name="hMem">A handle to the local memory object. This handle is returned by the LocalAlloc, LocalReAlloc, or LocalHandle function.</param>
/// <returns>
/// If the function succeeds, the return value is the size of the specified local memory object, in bytes. If the specified handle is not valid or if the
/// object has been discarded, the return value is zero. To get extended error information, call GetLastError.
/// </returns>
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "aa366745")]
public static extern uint LocalSize(IntPtr hMem);
/// <summary>Sets the last-error code for the calling thread.</summary>
/// <param name="dwErrCode">The last-error code for the thread.</param>
[DllImport(Lib.Kernel32, ExactSpelling = true, SetLastError = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms680627")]
public static extern void SetLastError(uint dwErrCode);
/// <summary>Converts a system time to file time format. System time is based on Coordinated Universal Time (UTC).</summary>
/// <param name="lpSystemTime">
/// A pointer to a SYSTEMTIME structure that contains the system time to be converted from UTC to file time format. The wDayOfWeek member of the
/// SYSTEMTIME structure is ignored.
/// </param>
/// <param name="lpFileTime">A pointer to a FILETIME structure to receive the converted system time.</param>
/// <returns>
/// 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.
/// </returns>
[DllImport(Lib.Kernel32, ExactSpelling = true, SetLastError = true), SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
[PInvokeData("Winbase.h", MSDNShortId = "ms724948")]
public static extern bool SystemTimeToFileTime(ref SYSTEMTIME lpSystemTime, ref FILETIME lpFileTime);
[DllImport(Lib.Kernel32, CharSet = CharSet.Auto, BestFitMapping = false, ThrowOnUnmappableChar = true)]
// int WINAPI lstrlen( _In_ LPCTSTR lpString);
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms647492(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, CharSet = CharSet.Auto, BestFitMapping = false, ThrowOnUnmappableChar = true)]
[PInvokeData("Winbase.h", MSDNShortId = "ms647492")]
private static extern int lstrlen([In, MarshalAs(UnmanagedType.LPTStr)] string s);
public static extern int lstrlen(string s);
/// <summary>
/// Multiplies two 32-bit values and then divides the 64-bit result by a third 32-bit value. The final result is rounded to the nearest integer.
/// </summary>
/// <param name="nNumber">The multiplicand.</param>
/// <param name="nNumerator">The multiplier.</param>
/// <param name="nDenominator">The number by which the result of the multiplication operation is to be divided.</param>
/// <returns>
/// <para>
/// If the function succeeds, the return value is the result of the multiplication and division, rounded to the nearest integer. If the result is a
/// positive half integer (ends in .5), it is rounded up. If the result is a negative half integer, it is rounded down.
/// </para>
/// <para>If either an overflow occurred or nDenominator was 0, the return value is -1.</para>
/// </returns>
// int MulDiv( _In_ int nNumber, _In_ int nNumerator, _In_ int nDenominator); https://msdn.microsoft.com/en-us/library/windows/desktop/aa383718(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)]
[PInvokeData("Winbase.h", MSDNShortId = "aa383718")]
public static extern int MulDiv(int nNumber, int nNumerator, int nDenominator);
/// <summary>SafeHandle instance using <see cref="CloseHandle"/> upon disposal.</summary>
public class SafeObjectHandle : GenericSafeHandle
{
/// <summary>Initializes a new instance of the <see cref="SafeObjectHandle"/> class.</summary>
public SafeObjectHandle() : this(IntPtr.Zero) { }
/// <summary>Initializes a new instance of the <see cref="SafeObjectHandle"/> class.</summary>
/// <param name="handle">The handle.</param>
public SafeObjectHandle(IntPtr handle) : base(handle, CloseHandle) { }
}
}
}
}

2515
PInvoke/Kernel32/WinCon.cs Normal file

File diff suppressed because it is too large Load Diff

View File

@ -1,129 +1,86 @@
using System;
using System;
using System.Runtime.InteropServices;
// ReSharper disable InconsistentNaming
namespace Vanara.PInvoke
{
public static partial class Kernel32
{
/// <summary>The flags that control the enforcement of the minimum and maximum working set sizes.</summary>
[PInvokeData("winnt.h")]
[Flags]
public enum QUOTA_LIMITS_HARDWS
{
/// <summary>The working set will not fall below the minimum working set limit.</summary>
QUOTA_LIMITS_HARDWS_MIN_ENABLE = 0x00000001,
/// <summary>The working set may fall below the minimum working set limit if memory demands are high.</summary>
QUOTA_LIMITS_HARDWS_MIN_DISABLE = 0x00000002,
/// <summary>The working set will not exceed the maximum working set limit.</summary>
QUOTA_LIMITS_HARDWS_MAX_ENABLE = 0x00000004,
/// <summary>The working set may exceed the maximum working set limit if there is abundant memory.</summary>
QUOTA_LIMITS_HARDWS_MAX_DISABLE = 0x00000008,
/// <summary>The quota limits use default limits</summary>
QUOTA_LIMITS_USE_DEFAULT_LIMITS = 0x00000010,
}
[PInvokeData("winnt.h")]
[Flags]
public enum SECTION_MAP : uint
{
SECTION_QUERY = 0x0001,
SECTION_MAP_WRITE = 0x0002,
SECTION_MAP_READ = 0x0004,
SECTION_MAP_EXECUTE = 0x0008,
SECTION_EXTEND_SIZE = 0x0010,
SECTION_MAP_EXECUTE_EXPLICIT = 0x0020,
SECTION_ALL_ACCESS = ACCESS_MASK.STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_WRITE | SECTION_MAP_READ | SECTION_MAP_EXECUTE | SECTION_EXTEND_SIZE,
}
/// <summary>
/// Flags that may be passed to the <see cref="GetVolumeInformation(string, out string, out uint, out uint, out FileSystemFlags, out string)"/> function.
/// A mask that indicates the member of the OSVERSIONINFOEX structure whose comparison operator is being set. This value corresponds to one of the bits
/// specified in the dwTypeMask parameter for the VerifyVersionInfo function.
/// </summary>
[Flags]
[PInvokeData("winnt.h")]
public enum FileSystemFlags
public enum VERSION_MASK : uint
{
/// <summary>The specified volume supports case-sensitive file names.</summary>
FILE_CASE_SENSITIVE_SEARCH = 0x00000001,
/// <summary>dwMinorVersion</summary>
VER_MINORVERSION = 0x0000001,
/// <summary>dwMajorVersion</summary>
VER_MAJORVERSION = 0x0000002,
/// <summary>dwBuildNumber</summary>
VER_BUILDNUMBER = 0x0000004,
/// <summary>dwPlatformId</summary>
VER_PLATFORMID = 0x0000008,
/// <summary>wServicePackMinor</summary>
VER_SERVICEPACKMINOR = 0x0000010,
/// <summary>wServicePackMajor</summary>
VER_SERVICEPACKMAJOR = 0x0000020,
/// <summary>wSuiteMask</summary>
VER_SUITENAME = 0x0000040,
/// <summary>wProductType</summary>
VER_PRODUCT_TYPE = 0x0000080,
}
/// <summary>The specified volume supports preserved case of file names when it places a name on disk.</summary>
FILE_CASE_PRESERVED_NAMES = 0x00000002,
/// <summary>The specified volume supports Unicode in file names as they appear on disk.</summary>
FILE_UNICODE_ON_DISK = 0x00000004,
/// <summary>
/// The specified volume preserves and enforces access control lists (ACL). For example, the NTFS file system preserves and enforces ACLs, and the
/// FAT file system does not.
/// </summary>
FILE_PERSISTENT_ACLS = 0x00000008,
/// <summary>The specified volume supports file-based compression.</summary>
FILE_FILE_COMPRESSION = 0x00000010,
/// <summary>The specified volume supports disk quotas.</summary>
FILE_VOLUME_QUOTAS = 0x00000020,
/// <summary>The specified volume supports sparse files.</summary>
FILE_SUPPORTS_SPARSE_FILES = 0x00000040,
/// <summary>The specified volume supports reparse points.</summary>
FILE_SUPPORTS_REPARSE_POINTS = 0x00000080,
/// <summary>The specified volume supports remote storage.</summary>
FILE_SUPPORTS_REMOTE_STORAGE = 0x00000100,
/// <summary>The specified volume is a compressed volume, for example, a DoubleSpace volume.</summary>
FILE_VOLUME_IS_COMPRESSED = 0x00008000,
/// <summary>The specified volume supports object identifiers.</summary>
FILE_SUPPORTS_OBJECT_IDS = 0x00010000,
/// <summary>
/// The specified volume supports the Encrypted File System (EFS). For more information, see <a
/// href="https://msdn.microsoft.com/en-us/library/windows/desktop/aa364223(v=vs.85).aspx">File Encryption</a>.
/// </summary>
FILE_SUPPORTS_ENCRYPTION = 0x00020000,
/// <summary>The specified volume supports named streams.</summary>
FILE_NAMED_STREAMS = 0x00040000,
/// <summary>The specified volume is read-only.</summary>
FILE_READ_ONLY_VOLUME = 0x00080000,
/// <summary>The specified volume supports a single sequential write.</summary>
FILE_SEQUENTIAL_WRITE_ONCE = 0x00100000,
/// <summary>
/// The specified volume supports transactions. For more information, see <a
/// href="https://msdn.microsoft.com/en-us/library/windows/desktop/aa365993(v=vs.85).aspx">About KTM</a>.
/// </summary>
FILE_SUPPORTS_TRANSACTIONS = 0x00200000,
/// <summary>
/// The specified volume supports hard links. For more information, see <a
/// href="https://msdn.microsoft.com/en-us/library/windows/desktop/aa365006(v=vs.85).aspx">Hard Links and Junctions.</a>
/// <para>
/// <c>Windows Server 2008, Windows Vista, Windows Server 2003 and Windows XP:</c> This value is not supported until Windows Server 2008 R2 and
/// Windows 7.
/// </para>
/// </summary>
FILE_SUPPORTS_HARD_LINKS = 0x00400000,
/// <summary>
/// The specified volume supports extended attributes. An extended attribute is a piece of application-specific metadata that an application can
/// associate with a file and is not part of the file's data.
/// <para>
/// <c>Windows Server 2008, Windows Vista, Windows Server 2003 and Windows XP:</c> This value is not supported until Windows Server 2008 R2 and
/// Windows 7.
/// </para>
/// </summary>
FILE_SUPPORTS_EXTENDED_ATTRIBUTES = 0x00800000,
/// <summary>
/// The file system supports open by FileID. For more information, see FILE_ID_BOTH_DIR_INFO.
/// <para>
/// <c>Windows Server 2008, Windows Vista, Windows Server 2003 and Windows XP:</c> This value is not supported until Windows Server 2008 R2 and
/// Windows 7.
/// </para>
/// </summary>
FILE_SUPPORTS_OPEN_BY_FILE_ID = 0x01000000,
/// <summary>
/// The specified volume supports update sequence number (USN) journals. For more information, see <a
/// href="https://msdn.microsoft.com/en-us/library/windows/desktop/aa363803(v=vs.85).aspx">Change Journal Records</a> .
/// <para>
/// <c>Windows Server 2008, Windows Vista, Windows Server 2003 and Windows XP:</c> This value is not supported until Windows Server 2008 R2 and
/// Windows 7.
/// </para>
/// </summary>
FILE_SUPPORTS_USN_JOURNAL = 0x02000000,
/// <summary>The specified volume supports integrity streams.</summary>
FILE_SUPPORTS_INTEGRITY_STREAMS = 0x04000000,
/// <summary>The specified volume supports block refcounting.</summary>
FILE_SUPPORTS_BLOCK_REFCOUNTING = 0x08000000,
/// <summary>The specified volume supports sparse VDL.</summary>
FILE_SUPPORTS_SPARSE_VDL = 0x10000000,
/// <summary>
/// The specified volume is a direct access (DAX) volume.
/// <para><c>Note</c> This flag was introduced in Windows 10, version 1607.</para>
/// </summary>
FILE_DAX_VOLUME = 0x20000000,
/// <summary>The specified volume supports ghosting.</summary>
FILE_SUPPORTS_GHOSTING = 0x40000000
/// <summary>
/// The operator to be used for the comparison. The VerifyVersionInfo function uses this operator to compare a specified attribute value to the
/// corresponding value for the currently running system.
/// </summary>
public enum VERSION_CONDITION : byte
{
/// <summary>The current value must be equal to the specified value.</summary>
VER_EQUAL = 1,
/// <summary>The current value must be greater than the specified value.</summary>
VER_GREATER,
/// <summary>The current value must be greater than or equal to the specified value.</summary>
VER_GREATER_EQUAL,
/// <summary>The current value must be less than the specified value.</summary>
VER_LESS,
/// <summary>The current value must be less than or equal to the specified value.</summary>
VER_LESS_EQUAL,
/// <summary>All product suites specified in the wSuiteMask member must be present in the current system.</summary>
VER_AND,
/// <summary>At least one of the specified product suites must be present in the current system.</summary>
VER_OR,
}
}
}

4634
PInvoke/Kernel32/WinNls.cs Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,244 @@
using System;
using System.Runtime.InteropServices;
using System.Text;
namespace Vanara.PInvoke
{
public static partial class Kernel32
{
/// <summary>Describes possible machine architectures. Used in <c>GetSystemWow64Directory2</c> and <c>IsWow64GuestMachineSupported</c>.</summary>
// https://msdn.microsoft.com/en-us/library/windows/desktop/mt804345(v=vs.85).aspx
[PInvokeData("Winnt.h", MSDNShortId = "mt804345")]
public enum IMAGE_FILE_MACHINE : ushort
{
/// <summary>Unknown</summary>
IMAGE_FILE_MACHINE_UNKNOWN = 0,
/// <summary>
/// Interacts with the host and not a WOW64 guest. <note>This constant is available starting with Windows 10, version 1607 and Windows Server 2016.</note>
/// </summary>
IMAGE_FILE_MACHINE_TARGET_HOST = 0x0001,
/// <summary>Intel 386</summary>
IMAGE_FILE_MACHINE_I386 = 0x014c,
/// <summary>MIPS little-endian, 0x160 big-endian</summary>
IMAGE_FILE_MACHINE_R3000 = 0x0162,
/// <summary>MIPS little-endian</summary>
IMAGE_FILE_MACHINE_R4000 = 0x0166,
/// <summary>MIPS little-endian</summary>
IMAGE_FILE_MACHINE_R10000 = 0x0168,
/// <summary>MIPS little-endian WCE v2</summary>
IMAGE_FILE_MACHINE_WCEMIPSV2 = 0x0169,
/// <summary>Alpha_AXP</summary>
IMAGE_FILE_MACHINE_ALPHA = 0x0184,
/// <summary>SH3 little-endian</summary>
IMAGE_FILE_MACHINE_SH3 = 0x01a2,
/// <summary>SH3DSP</summary>
IMAGE_FILE_MACHINE_SH3DSP = 0x01a3,
/// <summary>SH3E little-endian</summary>
IMAGE_FILE_MACHINE_SH3E = 0x01a4,
/// <summary>SH4 little-endian</summary>
IMAGE_FILE_MACHINE_SH4 = 0x01a6,
/// <summary>SH5</summary>
IMAGE_FILE_MACHINE_SH5 = 0x01a8,
/// <summary>ARM Little-Endian</summary>
IMAGE_FILE_MACHINE_ARM = 0x01c0,
/// <summary>ARM Thumb/Thumb-2 Little-Endian</summary>
IMAGE_FILE_MACHINE_THUMB = 0x01c2,
/// <summary>ARM Thumb-2 Little-Endian <note>This constant is available starting with Windows 7 and Windows Server 2008 R2.</note></summary>
IMAGE_FILE_MACHINE_ARMNT = 0x01c4,
/// <summary>TAM33BD</summary>
IMAGE_FILE_MACHINE_AM33 = 0x01d3,
/// <summary>IBM PowerPC Little-Endian</summary>
IMAGE_FILE_MACHINE_POWERPC = 0x01F0,
/// <summary>POWERPCFP</summary>
IMAGE_FILE_MACHINE_POWERPCFP = 0x01f1,
/// <summary>Intel 64</summary>
IMAGE_FILE_MACHINE_IA64 = 0x0200,
/// <summary>MIPS</summary>
IMAGE_FILE_MACHINE_MIPS16 = 0x0266,
/// <summary>ALPHA64</summary>
IMAGE_FILE_MACHINE_ALPHA64 = 0x0284,
/// <summary>MIPS</summary>
IMAGE_FILE_MACHINE_MIPSFPU = 0x0366,
/// <summary>MIPS</summary>
IMAGE_FILE_MACHINE_MIPSFPU16 = 0x0466,
/// <summary>AXP64</summary>
IMAGE_FILE_MACHINE_AXP64 = 0x0284,
/// <summary>Infineon</summary>
IMAGE_FILE_MACHINE_TRICORE = 0x0520,
/// <summary>CEF</summary>
IMAGE_FILE_MACHINE_CEF = 0x0CEF,
/// <summary>EFI Byte Code</summary>
IMAGE_FILE_MACHINE_EBC = 0x0EBC,
/// <summary>AMD64 (K8)</summary>
IMAGE_FILE_MACHINE_AMD64 = 0x8664,
/// <summary>M32R little-endian</summary>
IMAGE_FILE_MACHINE_M32R = 0x9041,
/// <summary>ARM64 Little-Endian <note>This constant is available starting with Windows 8.1 and Windows Server 2012 R2.</note></summary>
IMAGE_FILE_MACHINE_ARM64 = 0xAA64,
/// <summary>CEE</summary>
IMAGE_FILE_MACHINE_CEE = 0xC0EE,
}
/// <summary>Retrieves the path of the system directory used by WOW64. This directory is not present on 32-bit Windows.</summary>
/// <param name="lpBuffer">A pointer to the buffer to receive the path. This path does not end with a backslash.</param>
/// <param name="uSize">The maximum size of the buffer, in <c>TCHARs</c>.</param>
/// <returns>
/// <para>
/// If the function succeeds, the return value is the length, in <c>TCHARs</c>, of the string copied to the buffer, not including the terminating null
/// character. If the length is greater than the size of the buffer, the return value is the size of the buffer required to hold the path.
/// </para>
/// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para>
/// <para>On 32-bit Windows, the function always fails, and the extended error is set to ERROR_CALL_NOT_IMPLEMENTED.</para>
/// </returns>
// UINT WINAPI GetSystemWow64Directory( _Out_ LPTSTR lpBuffer, _In_ UINT uSize); https://msdn.microsoft.com/en-us/library/windows/desktop/ms724405(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)]
[PInvokeData("Winbase.h", MSDNShortId = "ms724405")]
public static extern uint GetSystemWow64Directory([Out] StringBuilder lpBuffer, uint uSize);
/// <summary>
/// Retrieves the path of the system directory used by WOW64, using the specified image file machine type. This directory is not present on 32-bit Windows.
/// </summary>
/// <param name="lpBuffer">A pointer to the buffer to receive the path. This path does not end with a backslash.</param>
/// <param name="uSize">The maximum size of the buffer, in TCHARs.</param>
/// <param name="ImageFileMachineType">An IMAGE_FILE_MACHINE_* value that specifies the machine to test.</param>
/// <returns>
/// <para>
/// If the function succeeds, the return value is the length, in <c>TCHARs</c>, of the string copied to the buffer, not including the terminating null
/// character. If the length is greater than the size of the buffer, the return value is the size of the buffer required to hold the path.
/// </para>
/// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// UINT WINAPI GetSystemWow64Directory( _Out_ LPTSTR lpBuffer, _In_ UINT uSize, _In_ WORD ImageFileMachineType); https://msdn.microsoft.com/en-us/library/windows/desktop/mt804319(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)]
[PInvokeData("Wow64apiset.h", MSDNShortId = "mt804319")]
public static extern uint GetSystemWow64Directory2([Out] StringBuilder lpBuffer, uint uSize, IMAGE_FILE_MACHINE ImageFileMachineType);
/// <summary>
/// <para>
/// [Some information relates to pre-released product which may be substantially modified before it's commercially released. Microsoft makes no
/// warranties, express or implied, with respect to the information provided here.]
/// </para>
/// <para>Determines which architectures are supported (under WOW64) on the given machine architecture.</para>
/// </summary>
/// <param name="WowGuestMachine">An <c>IMAGE_FILE_MACHINE_*</c> value that specifies the machine to test.</param>
/// <param name="MachineIsSupported">
/// On success, returns a pointer to a boolean: <c>true</c> if the machine supports WOW64, or <c>false</c> if it does not.
/// </param>
/// <returns>On success, returns <c>S_OK</c>; otherwise, returns an error. To get extended error information, call <c>GetLastError</c>.</returns>
// HRESULT WINAPI IsWow64GuestMachineSupported( _In_ USHORT WowGuestMachine, _Out_ BOOLEAN *MachineIsSupported); https://msdn.microsoft.com/en-us/library/windows/desktop/mt804321(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("Wow64apiset.h", MSDNShortId = "mt804321")]
public static extern HRESULT IsWow64GuestMachineSupported(IMAGE_FILE_MACHINE WowGuestMachine, [MarshalAs(UnmanagedType.U1)] out bool MachineIsSupported);
/// <summary>Determines whether the specified process is running under WOW64.</summary>
/// <param name="hProcess">
/// <para>
/// A handle to the process. The handle must have the PROCESS_QUERY_INFORMATION or PROCESS_QUERY_LIMITED_INFORMATION access right. For more information,
/// see Process Security and Access Rights.
/// </para>
/// <para><c>Windows Server 2003 and Windows XP:</c> The handle must have the PROCESS_QUERY_INFORMATION access right.</para>
/// </param>
/// <param name="Wow64Process">
/// A pointer to a value that is set to TRUE if the process is running under WOW64. If the process is running under 32-bit Windows, the value is set to
/// FALSE. If the process is a 64-bit application running under 64-bit Windows, the value is also set to FALSE.
/// </param>
/// <returns>
/// <para>If the function succeeds, the return value is a nonzero value.</para>
/// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// BOOL WINAPI IsWow64Process( _In_ HANDLE hProcess, _Out_ PBOOL Wow64Process); https://msdn.microsoft.com/en-us/library/windows/desktop/ms684139(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "ms684139")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool IsWow64Process([In] IntPtr hProcess, [MarshalAs(UnmanagedType.Bool)] out bool Wow64Process);
/// <summary>Determines whether the specified process is running under WOW64; also returns additional machine process and architecture information.</summary>
/// <param name="hProcess">
/// A handle to the process. The handle must have the PROCESS_QUERY_INFORMATION or PROCESS_QUERY_LIMITED_INFORMATION access right. For more information,
/// see Process Security and Access Rights.
/// </param>
/// <param name="pProcessMachine">
/// On success, returns a pointer to an IMAGE_FILE_MACHINE_* value. The value will be IMAGE_FILE_MACHINE_UNKNOWN if the target process is not a WOW64
/// process; otherwise, it will identify the type of WoW process.
/// </param>
/// <param name="pNativeMachine">
/// On success, returns a pointer to a possible IMAGE_FILE_MACHINE_* value identifying the native architecture of host system.
/// </param>
/// <returns>
/// <para>If the function succeeds, the return value is a nonzero value.</para>
/// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// BOOL WINAPI IsWow64Process( _In_ HANDLE hProcess, _Out_ USHORT *pProcessMachine, _Out_opt_ USHORT *pNativeMachine); https://msdn.microsoft.com/en-us/library/windows/desktop/mt804318(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("Wow64apiset.h", MSDNShortId = "mt804318")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool IsWow64Process2([In] IntPtr hProcess, out IMAGE_FILE_MACHINE pProcessMachine, out IMAGE_FILE_MACHINE pNativeMachine);
/// <summary>Disables file system redirection for the calling thread. File system redirection is enabled by default.</summary>
/// <param name="OldValue">
/// The WOW64 file system redirection value. The system uses this parameter to store information necessary to revert (re-enable) file system redirection.
/// </param>
/// <returns>
/// <para>If the function succeeds, the return value is a nonzero value.</para>
/// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// BOOL WINAPI Wow64DisableWow64FsRedirection( _Out_ PVOID *OldValue); https://msdn.microsoft.com/en-us/library/windows/desktop/aa365743(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "aa365743")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool Wow64DisableWow64FsRedirection(out IntPtr OldValue);
/// <summary>
/// <para>Restores file system redirection for the calling thread.</para>
/// <para>This function should not be called without a previous call to the <c>Wow64DisableWow64FsRedirection</c> function.</para>
/// <para>Any data allocation on behalf of the <c>Wow64DisableWow64FsRedirection</c> function is cleaned up by this function.</para>
/// </summary>
/// <param name="OldValue">The WOW64 file system redirection value. This value is obtained from the <c>Wow64DisableWow64FsRedirection</c> function.</param>
/// <returns>
/// <para>If the function succeeds, the return value is a nonzero value.</para>
/// <para>If the function fails, the return value is <c>FALSE</c> (zero). To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// BOOL WINAPI Wow64RevertWow64FsRedirection( _In_ PVOID OldValue); https://msdn.microsoft.com/en-us/library/windows/desktop/aa365745(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "aa365745")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool Wow64RevertWow64FsRedirection(IntPtr OldValue);
/// <summary>Undocumented.</summary>
/// <param name="Machine">Undocumented.</param>
/// <returns>Undocumented.</returns>
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
public static extern IMAGE_FILE_MACHINE Wow64SetThreadDefaultGuestMachine(IMAGE_FILE_MACHINE Machine);
}
}

View File

@ -0,0 +1,20 @@
using System.Runtime.InteropServices;
namespace Vanara.PInvoke
{
public static partial class Kernel32
{
/// <summary>
/// Retrieves the session identifier of the console session. The console session is the session that is currently attached to the physical console. Note
/// that it is not necessary that Remote Desktop Services be running for this function to succeed.
/// </summary>
/// <returns>
/// The session identifier of the session that is attached to the physical console. If there is no session attached to the physical console, (for
/// example, if the physical console session is in the process of being attached or detached), this function returns 0xFFFFFFFF.
/// </returns>
// DWORD WTSGetActiveConsoleSessionId(void); https://msdn.microsoft.com/en-us/library/aa383835(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)]
[PInvokeData("Winbase.h", MSDNShortId = "aa383835")]
public static extern uint WTSGetActiveConsoleSessionId();
}
}

View File

@ -419,6 +419,19 @@ namespace Vanara.PInvoke
[PInvokeData("winbase.h", MSDNShortId = "aa446671")]
public static extern bool GetTokenInformation(SafeTokenHandle hObject, TOKEN_INFORMATION_CLASS tokenInfoClass, SafeCoTaskMemHandle pTokenInfo, int tokenInfoLength, out int returnLength);
/// <summary>The <c>ImpersonateNamedPipeClient</c> function impersonates a named-pipe client application.</summary>
/// <param name="hNamedPipe">A handle to a named pipe.</param>
/// <returns>
/// <para>If the function succeeds, the return value is nonzero.</para>
/// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para>
/// </returns>
// BOOL WINAPI ImpersonateNamedPipeClient( _In_ HANDLE hNamedPipe);
// https://msdn.microsoft.com/en-us/library/windows/desktop/aa378618(v=vs.85).aspx
[DllImport(Lib.AdvApi32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("Winbase.h", MSDNShortId = "aa378618")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool ImpersonateNamedPipeClient(IntPtr hNamedPipe);
/// <summary>
/// The LogonUser function attempts to log a user on to the local computer. The local computer is the computer from which LogonUser was called. You
/// cannot use LogonUser to log on to a remote computer. You specify the user with a user name and domain and authenticate the user with a plain-text