c# - 是否可以在 .NET 标准 2.0 中显示一个简单的类似于 MessageBox 的通知窗口(仅限 Windows)

标签 c# messagebox .net-standard-2.0

我正在将 .NET4 类库转换为 .NET Standard 2.0,以便可以从 .NET4 应用程序和 .NET6 应用程序调用它。这些应用程序仅适用于 Windows。

我遇到的一个转换问题是类库对 WinForms MessageBox.Show() 进行了几次调用,以显示简短的警报消息,并使用“确定”按钮关闭窗口。

由于 .NET Standard 2.0 不支持 WinForms,复制此功能的最佳方法是什么? (显示一个简单的弹出窗口,其中包含短信字符串和“确定”按钮)

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

编辑:感谢您的回答。 Pinvoke 运行完美。这是我最终得到的类(class):

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);
    }
}

然后可以这样调用:

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

最佳答案

您可以使用 P/Invoke 语句来调用 MessageBox function像这样在 User32.dll 中。

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

要显示 MessageBox,请使用所需参数调用 MessageBox 函数。要指定父窗口,请传入您自己的应用程序窗口的句柄或 IntPtr.Zero 以使用桌面窗口。 lpText参数是消息文本,lpCaption参数是消息框窗口的标题。请参阅 uType 参数的文档,因为有许多选项可用于自定义 MessageBox 的外观和行为。

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

关于c# - 是否可以在 .NET 标准 2.0 中显示一个简单的类似于 MessageBox 的通知窗口(仅限 Windows),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75921957/

相关文章:

c# - Xamarin.forms 如何在列表中显示彼此相邻的项目

c# - 使用 Exchange Web 服务发送 "Auto-Accepted"约会

c# - MessageBox 自动继续,无需按下按钮

c# - 如何创建自定义消息框?

c++ - MessageBox 和 ShellExecute 成功,但如果在应用程序退出之前立即调用则不会显示任何内容

C# 生成的 SOAP 客户端自定义转换器

.NET 标准和运行时要求

c# - 将 curl 命令转换为 restsharp

c# - 连接两个列表中的字符串以创建第三个列表

c# - 将 JSON 数组发布到 mvc Controller