如何在.NET Core控制台应用程序中显示消息框?

5

我正在开发 .net core 控制台应用程序。当用户要退出应用程序时,我想发出提示。如下所示:

 MessageBox.Show("Contiue or not", "Question", MessageBoxButtons.YesNo, MessageBoxIcon.None, MessageBoxDefaultButton.Button1) == DialogResult.No)
    Application.Exit();

但是我无法将System.Windows.Forms引用添加到我的项目中。我遇到了这个错误。
 Error  CS0234  The type or namespace name 'Forms' does not exist in the namespace 'System.Windows' (are you missing an assembly reference?)    

在.NET Core控制台应用程序中显示消息框是否可能?


也许这可以帮助:https://dev59.com/H3NA5IYBdhLWcg3wBpHs - Muammer
2
根据移植说明,将SDK更改为Microsoft.NET.Sdk.WindowsDesktop并添加<UseWindowsForms>true</UseWindowsForms>即可使其正常工作。(如果您想要控制台应用程序,则输出类型必须保留为“Exe”)。当然,从控制台应用程序中进行GUI调用本质上仍然是一个坏主意,即使忽略了不必要的平台不兼容性(这仅适用于Windows)。 - Jeroen Mostert
2个回答

4
为了使用Windows Forms,您需要修改.csproj文件:
  • UseWindowsForms设置为true
  • TargetFramework后添加-windows(例如:net6.0-windows
ConsoleApp.csproj文件:
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net6.0-windows</TargetFramework>
    <UseWindowsForms>true</UseWindowsForms>
  </PropertyGroup>
</Project>

Program.cs:

System.Console.WriteLine("Hello, Console!");
System.Windows.Forms.MessageBox.Show("Hello, Popup!");

结果:

结果

注释:

  • 我在 Windows x64 上的 .NET Core 3.1、.NET 5 和 .NET 6 上验证了此解决方案。
  • 如果您不希望显示控制台窗口,请将.csproj中的OutputType设置为WinExe,而不是Exe
  • Windows Forms 只适用于 Windows,因此此解决方案也是如此。
  • 在 .NET Core 3.1 上,无需将目标框架更改为 Windows,但仍然无法发布 Linux 操作系统的可执行文件。
  • 如果需要跨平台解决方案,在 Windows 上显示弹出窗口并仅在 Linux 上使用控制台,则可以创建自定义构建配置,并像下面的示例那样使用预处理器指令。

跨平台 ConsoleApp.csproj:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net6.0</TargetFramework>
    <Configurations>Debug;Release;WindowsDebug;WindowsRelease</Configurations>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)' == 'WindowsDebug' Or '$(Configuration)' == 'WindowsRelease'">
    <DefineConstants>WindowsRuntime</DefineConstants>
    <TargetFramework>net6.0-windows</TargetFramework>
    <UseWindowsForms>true</UseWindowsForms>
  </PropertyGroup>
</Project>

跨平台 Program.cs

System.Console.WriteLine("Hello, Console!");

#if WindowsRuntime
System.Windows.Forms.MessageBox.Show("Hello, Popup!");
#endif

1
这个应用程序能在Linux上运行吗(不需要Windows对话框)? - Heinrich Ulbricht
@HeinrichUlbricht,不,当项目使用Windows Forms时,它只能针对Windows进行目标定位。但是,您可以创建自定义构建配置并使用预处理器指令。我在答案中添加了一个代码示例。 - Daniil Palii

1
一些控制台应用程序也需要将这行代码添加到项目中...
<DisableWinExeOutputInference>true</DisableWinExeOutputInference>

将此添加到Daniil帖子中的示例将给您以下结果...
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net6.0-windows</TargetFramework>
    <UseWindowsForms>true</UseWindowsForms>

    <!--Insert DisableWinExeOutputInference here -->
    <DisableWinExeOutputInference>true</DisableWinExeOutputInference>

  </PropertyGroup>
</Project>

如何理解,何时使用?参数的作用是什么? - Daniil Palii

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接