Marshal.GetLastWin32Error Método

Definição

Retorna o código de erro retornado pela última função não gerenciada chamada com a invocação da plataforma que tem o sinalizador SetLastError definido.

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

Retornos

O último código de erro definido por uma chamada para a função SetLastError do Win32.

Atributos

Exemplos

O exemplo a seguir chama o GetLastWin32Error método . O exemplo demonstra primeiro chamar o método sem nenhum erro presente e, em seguida, demonstra a chamada do método com um erro presente.

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

Comentários

Em sistemas Windows, GetLastWin32Error expõe a função GetLastError do Win32 de Kernel32.DLL. Esse método existe porque não é confiável fazer uma chamada de invocação de plataforma direta para GetLastError obter essas informações. Se você quiser acessar esse código de erro, deverá chamar GetLastWin32Error em vez de escrever sua própria definição de invocação de plataforma para GetLastError e chamá-la. O Common Language Runtime pode fazer chamadas internas para APIs que substituem o GetLastError mantido pelo sistema operacional.

Você só poderá usar esse método para obter códigos de erro se aplicar o System.Runtime.InteropServices.DllImportAttribute à assinatura do método e definir o DllImportAttribute.SetLastError campo como true. O processo para isso varia dependendo da linguagem de origem usada: C# e C++ são false por padrão, mas a instrução Declare no Visual Basic é true.

Há uma diferença no comportamento do GetLastWin32Error método no .NET Core e .NET Framework quando DllImportAttribute.SetLastError é true. Em .NET Framework, o GetLastWin32Error método pode reter informações de erro de uma chamada P/Invoke para a próxima. No .NET Core, as informações de erro são limpas antes da chamada P/Invoke e o representa apenas informações GetLastWin32Error de erro da última chamada de método.

No .NET 6 e versões posteriores, esse método é funcionalmente equivalente a GetLastPInvokeError, que é nomeado para refletir melhor a intenção da API e sua natureza multiplataforma. GetLastPInvokeError deve ser preferencial em vez de GetLastWin32Error.

Aplica-se a

Confira também