Marshal.GetLastWin32Error Método

Definición

Devuelve el código de error devuelto por la última función no administrada a la que se llamó mediante la invocación de plataforma que tiene la marca SetLastError activada.

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

Devoluciones

Último código de error establecido por una llamada a la función SetLastError Win32.

Atributos

Ejemplos

En el ejemplo siguiente se llama al GetLastWin32Error método . En primer lugar, el ejemplo muestra cómo llamar al método sin ningún error presente y, a continuación, muestra cómo llamar al método con un error 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

Comentarios

En los sistemas Windows, GetLastWin32Error expone la función GetLastError de Win32 desde Kernel32.DLL. Este método existe porque no es confiable realizar una llamada de invocación de plataforma directa para GetLastError obtener esta información. Si desea acceder a este código de error, debe llamar a GetLastWin32Error en lugar de escribir su propia definición de invocación de plataforma para GetLastError y llamarla. Common Language Runtime puede realizar llamadas internas a las API que sobrescriben el GetLastError mantenimiento por parte del sistema operativo.

Puede usar este método para obtener códigos de error solo si aplica a System.Runtime.InteropServices.DllImportAttribute la firma del método y establece el DllImportAttribute.SetLastError campo trueen . El proceso para esto varía en función del lenguaje de origen usado: C# y C++ son false de forma predeterminada, pero la Declare instrucción de Visual Basic es true.

Hay una diferencia en el comportamiento del GetLastWin32Error método en .NET Core y .NET Framework cuando DllImportAttribute.SetLastError es true. En .NET Framework, el GetLastWin32Error método puede conservar la información de error de una llamada P/Invoke a la siguiente. En .NET Core, la información de error se borra antes de la llamada de P/Invoke y representa GetLastWin32Error solo la información de error de la última llamada al método.

En .NET 6 y versiones posteriores, este método es funcionalmente equivalente a GetLastPInvokeError, que se denomina para reflejar mejor la intención de la API y su naturaleza multiplataforma. GetLastPInvokeError se debe preferir sobre GetLastWin32Error.

Se aplica a

Consulte también