我正在将 .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/