如何在仅Windows的.NET Standard 2.0中实现类似MessageBox的弹窗
问题描述
将.NET4类库转换为.NET Standard 2.0,使其能被Windows平台的.NET4和.NET6应用调用。转换过程中遇到问题:类库多处使用WinForms的MessageBox.Show()显示带OK按钮的简短提示弹窗,但.NET Standard 2.0不支持WinForms,需要复现该弹窗功能。
解决方案
通过PInvoke直接调用Windows系统的user32.dll中的MessageBox函数即可实现,最终实现类如下:
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");
内容的提问来源于stack exchange,提问作者qwanta
相关产品推荐
相关产品推荐

