Dotnet core Console调用WIndows.Forms的MessageBox提示

最近想把ET打表工具的报错提示直接调用win系统弹窗,好让策划明显的知道表格哪里填错数据,弹窗需要调用System.Windows.Forms库。操作如下:

需要在 .csproj 文件中添加:

<UseWindowsForms>true</UseWindowsForms>

须将目标平台设置为 Windows

修改之后,还是报错:

如果使用 Windows 窗体或 WPF,或者引用使用 Windows 窗体或 WPF 的项目或包,则必须将目标平台设置为 Windows

需将 .csproj 文件中的

<TargetFramework>net8.0</TargetFramework>

修改为:

<TargetFramework>net8.0-windows</TargetFramework>

修改后的 .csproj 文件

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net8.0-windows</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
    <UseWindowsForms>true</UseWindowsForms>
  </PropertyGroup>

</Project>

打表抛异常/控制台显示报错的地方改成弹窗提示即可

EmitResult emitResult = compilation.Emit(memSteam);
if (!emitResult.Success)
{
    StringBuilder stringBuilder = new StringBuilder();
    foreach (Diagnostic t in emitResult.Diagnostics)
    {
        stringBuilder.AppendLine(t.GetMessage());
    }

    MessageBox.Show($"动态编译失败:\n{stringBuilder}");
    throw new Exception($"动态编译失败:\n{stringBuilder}");
}

memSteam.Seek(0, SeekOrigin.Begin);

再次执行

dotnet run

就能正常运行了,可以看到弹窗信息。

posted @ 2024-06-28 20:06  Flamesky  阅读(38)  评论(0编辑  收藏  举报