Search code examples
c#messagebox.net-standard-2.0

Is it possible to display a simple notification MessageBox-like window in .NET standard 2.0 (windows only)


I am converting a .NET4 class library to .NET Standard 2.0 so that it can be called from a .NET4 application and a .NET6 application. These applications are for windows only.

The one conversion problem I am having is that the class library has a handful of calls to WinForms MessageBox.Show() to display short alert messages with an OK button to close the window.

As .NET Standard 2.0 does not support WinForms, what is the best way to replicate this functionality? (showing a simple popup window with a short message string and an OK button)

===============

edit: thanks for the answers. Pinvoke worked perfectly. This is the class I ended up with:

internal class SimpleMsgBox
{
    [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
    static extern int MessageBox(int hWnd, String text, String caption, uint type);

    internal static void Show(string message, string title)
    {
        MessageBox(0, message, title, 0);
    }
}

it can then be called like this:

SimpleMsgBox.Show("an error occurred", "alert");

Solution

  • You can use a P/Invoke statement to call the MessageBox function in User32.dll like so.

            [DllImport("User32.dll", SetLastError = true, CharSet = CharSet.Auto)] 
            public static extern int MessageBox(
                IntPtr hWnd,
                string lpText,
                string lpCaption,
                uint uType
                );
    

    To display the MessageBox, call the MessageBox function with the desired parameters. To specify the parent window, pass in either the handle of your own application's window or IntPtr.Zero to use the desktop's window. The lpText parameter is the message text, and the lpCaption parameter is the title of the message box window. Refer to the documentation for the uType parameter, as there are many options available for customizing the appearance and behavior of the MessageBox.

    int returnValue = NativeMethods.MessageBox(
                    IntPtr.Zero,
                    "Hello!",
                    "This is a caption",
                    0x0);