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

Комментарии

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

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

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

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

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

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