Marshal.GetLastWin32Error Метод

Определение

Возвращает код ошибки, возвращенной последней неуправляемой функцией, вызванной при помощи вызова неуправляемого кода с установленным флагом SetLastError.

public:
 static int GetLastWin32Error();
[System.Security.SecurityCritical]
public static int GetLastWin32Error ();
public static int GetLastWin32Error ();
[<System.Security.SecurityCritical>]
static member GetLastWin32Error : unit -> int
static member GetLastWin32Error : unit -> int
Public Shared Function GetLastWin32Error () As Integer

Возвращаемое значение

Последний код ошибки, заданный вызовом функции SetLastError платформы Win32.

Атрибуты

Примеры

В следующем примере вызывается GetLastWin32Error метод . В примере сначала демонстрируется вызов метода без ошибки, а затем демонстрируется вызов метода с ошибкой.

using System;
using System.Runtime.InteropServices;

internal class Win32
{
    // Use DllImportAttribute to inport the Win32 MessageBox
    // function.  Set the SetLastError flag to true to allow
    // the function to set the Win32 error.
    [DllImportAttribute("user32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
    public static extern int MessageBox(IntPtr hwnd, String text, String caption, uint type);
}

class Program
{

    static void Run()
    {
        // Call the MessageBox with normal parameters.

        Console.WriteLine("Calling Win32 MessageBox without error...");

        Win32.MessageBox(new IntPtr(0), "Press OK...", "Press OK Dialog", 0);

        // Get the last error and display it.
        int error = Marshal.GetLastWin32Error();

        Console.WriteLine("The last Win32 Error was: " + error);

        // Call the MessageBox with an invalid window handle to
        // produce a Win32 error.

        Console.WriteLine("Calling Win32 MessageBox with error...");

        Win32.MessageBox(new IntPtr(123132), "Press OK...", "Press OK Dialog", 0);

        // Get the last error and display it.

        error = Marshal.GetLastWin32Error();

        Console.WriteLine("The last Win32 Error was: " + error);
    }

    static void Main(string[] args)
    {
        Run();
    }
}
// This code example displays the following to the console:
//
// Calling Win32 MessageBox without error...
// The last Win32 Error was: 0
// Calling Win32 MessageBox with error...
// The last Win32 Error was: 1400
Imports System.Runtime.InteropServices

Module Win32
    ' Use DllImportAttribute to inport the Win32 MessageBox
    ' function.  Set the SetLastError flag to true to allow
    ' the function to set the Win32 error.
    <DllImportAttribute("user32.dll", SetLastError:=True, CharSet:=CharSet.Unicode)> _
    Function MessageBox(ByVal hwnd As IntPtr, ByVal text As String, ByVal caption As String, ByVal type As UInt32) As Integer
    End Function

End Module

Module Program


    Sub Run()


        ' Call the MessageBox with normal parameters.

        Console.WriteLine("Calling Win32 MessageBox without error...")

        Win32.MessageBox(New IntPtr(0), "Press OK...", "Press OK Dialog", 0)

        ' Get the last error and display it.
        Dim errorVal As Integer

        errorVal = Marshal.GetLastWin32Error()

        Console.WriteLine("The last Win32 Error was: " + errorVal)

        ' Call the MessageBox with an invalid window handle to
        ' produce a Win32 error.

        Console.WriteLine("Calling Win32 MessageBox with error...")

        Win32.MessageBox(New IntPtr(123132), "Press OK...", "Press OK Dialog", 0)

        ' Get the last error and display it.

        errorVal = Marshal.GetLastWin32Error()

        Console.WriteLine("The last Win32 Error was: " + errorVal)

    End Sub

    Sub Main(ByVal args() As String)

        Run()

    End Sub

End Module

' This code example displays the following to the console: 
'
' Calling Win32 MessageBox without error...
' The last Win32 Error was: 0
' Calling Win32 MessageBox with error...
' The last Win32 Error was: 1400

Комментарии

В системах GetLastWin32Error Windows предоставляет функцию Win32 GetLastError из Kernel32.DLL. Этот метод существует, так как он не является надежным выполнять прямой вызов платформы для GetLastError получения этих сведений. Если вы хотите получить доступ к этому коду ошибки, необходимо вызвать GetLastWin32Error вместо написания собственного определения вызова платформы для GetLastError и его вызова. Среда CLR может выполнять внутренние вызовы API, которые перезаписывают поддерживаемые GetLastError операционной системой.

Этот метод можно использовать для получения кодов ошибок, только если применить System.Runtime.InteropServices.DllImportAttribute к сигнатуре метода и задать для поля значение DllImportAttribute.SetLastErrortrue. Процесс зависит от используемого исходного языка: по умолчанию используются false C# и C++, но Declare в Visual Basic используется trueоператор .

Существует разница в поведении GetLastWin32Error метода в .NET Core и платформа .NET Framework, если DllImportAttribute.SetLastError имеет значение true. На платформа .NET Framework GetLastWin32Error метод может сохранять сведения об ошибке от одного вызова P/Invoke к следующему. В .NET Core сведения об ошибке очищаются перед вызовом P/Invoke, а GetLastWin32Error представляет только сведения об ошибке из последнего вызова метода.

В .NET 6 и более поздних версиях этот метод функционально эквивалентен GetLastPInvokeError, который называется , чтобы лучше отражать назначение API и его кроссплатформенный характер. GetLastPInvokeError следует предпочтительнее , чем GetLastWin32Error.

Применяется к

См. также раздел