Share via


Exemplo de MsgBox

Esta amostra demonstra como passar tipos de cadeia de caracteres por valor como parâmetros In e quando usar os campos EntryPoint, CharSet e ExactSpelling.

A amostra de MsgBox usa a seguinte função não gerenciada, mostrada com a respectiva declaração de função original:

  • MessageBox exportada de User32.dll.

    int MessageBox(HWND hWnd, LPCTSTR lpText, LPCTSTR lpCaption,
       UINT uType);  
    

Nesta amostra, a classe NativeMethods contém um protótipo gerenciado para cada função não gerenciada chamado pela classe MsgBoxSample. Os métodos de protótipo gerenciado MsgBox, MsgBox2 e MsgBox3 têm declarações diferentes para a mesma função não gerenciada.

A declaração para MsgBox2 produz uma saída incorreta na caixa de mensagem porque o tipo de caractere, especificado como ANSI, é incompatível com o ponto de entrada MessageBoxW, que é o nome da função Unicode. A declaração MsgBox3 cria uma incompatibilidade entre os campos EntryPoint, CharSet e ExactSpelling. Quando chamado, MsgBox3 gera uma exceção. Para obter informações detalhadas sobre a nomeação de cadeia de caracteres e realização de marshaling de nome, consulte Especificando um conjunto de caracteres.

Declarando Protótipos

private ref class NativeMethods
{
public:
    // Declares managed prototypes for unmanaged functions.
    [DllImport("User32.dll", EntryPoint = "MessageBox",
        CharSet = CharSet::Auto)]
    static int MsgBox(int hWnd, String^ text, String^ caption,
        unsigned int type);

    // Causes incorrect output in the message window.
    [DllImport("User32.dll", EntryPoint = "MessageBoxW",
        CharSet = CharSet::Ansi)]
    static int MsgBox2(int hWnd, String^ text,
        String^ caption, unsigned int type);

    // Causes an exception to be thrown. EntryPoint, CharSet, and
    // ExactSpelling fields are mismatched.
    [DllImport("User32.dll", EntryPoint = "MessageBox",
        CharSet = CharSet::Ansi, ExactSpelling = true)]
    static int MsgBox3(int hWnd, String^ text,
        String^ caption, unsigned int type);
};
internal static class NativeMethods
{
    // Declares managed prototypes for unmanaged functions.
    [DllImport("User32.dll", EntryPoint = "MessageBox",
        CharSet = CharSet.Auto)]
    internal static extern int MsgBox(
        IntPtr hWnd, string lpText, string lpCaption, uint uType);

    // Causes incorrect output in the message window.
    [DllImport("User32.dll", EntryPoint = "MessageBoxW",
        CharSet = CharSet.Ansi)]
    internal static extern int MsgBox2(
        IntPtr hWnd, string lpText, string lpCaption, uint uType);

    // Causes an exception to be thrown. EntryPoint, CharSet, and
    // ExactSpelling fields are mismatched.
    [DllImport("User32.dll", EntryPoint = "MessageBox",
        CharSet = CharSet.Ansi, ExactSpelling = true)]
    internal static extern int MsgBox3(
        IntPtr hWnd, string lpText, string lpCaption, uint uType);
}
Friend Class NativeMethods
    ' Declares managed prototypes for unmanaged functions.
    Friend Declare Auto Function MsgBox Lib "User32.dll" Alias "MessageBox" (
        ByVal hWnd As IntPtr, ByVal lpText As String, ByVal lpCaption As String,
        ByVal uType As UInteger) As Integer

    ' Causes incorrect output in the message window.
    Friend Declare Ansi Function MsgBox2 Lib "User32.dll" Alias "MessageBoxW" (
        ByVal hWnd As IntPtr, ByVal lpText As String, ByVal lpCaption As String,
        ByVal uType As UInteger) As Integer

    ' Causes an exception to be thrown.
    ' ExactSpelling is True by default when Ansi or Unicode is used.
    Friend Declare Ansi Function MsgBox3 Lib "User32.dll" Alias "MessageBox" (
        ByVal hWnd As IntPtr, ByVal lpText As String, ByVal lpCaption As String,
        ByVal uType As UInteger) As Integer
End Class

Chamando Funções

public class MsgBoxSample
{
public:
    static void Main()
    {
        NativeMethods::MsgBox(0, "Correct text", "MsgBox Sample", 0);
        NativeMethods::MsgBox2(0, "Incorrect text", "MsgBox Sample", 0);

        try
        {
            NativeMethods::MsgBox3(0, "No such function", "MsgBox Sample", 0);
        }
        catch (EntryPointNotFoundException^)
        {
            Console::WriteLine("EntryPointNotFoundException thrown as expected!");
        }
    }
};
public class MsgBoxSample
{
    public static void Main()
    {
        NativeMethods.MsgBox(0, "Correct text", "MsgBox Sample", 0);
        NativeMethods.MsgBox2(0, "Incorrect text", "MsgBox Sample", 0);

        try
        {
            NativeMethods.MsgBox3(0, "No such function", "MsgBox Sample", 0);
        }
        catch (EntryPointNotFoundException)
        {
            Console.WriteLine($"{nameof(EntryPointNotFoundException)} thrown as expected!");
        }
    }
}
Public Class MsgBoxSample
    Public Shared Sub Main()
        NativeMethods.MsgBox(0, "Correct text", "MsgBox Sample", 0)
        NativeMethods.MsgBox2(0, "Incorrect text", "MsgBox Sample", 0)

        Try
            NativeMethods.MsgBox3(0, "No such function", "MsgBox Sample", 0)
        Catch e As EntryPointNotFoundException
            Console.WriteLine($"{NameOf(EntryPointNotFoundException)} thrown as expected!")
        End Try
    End Sub
End Class

Confira também