如何在.net core控制台应用程序上显示消息框?

Mer*_*RAN 5 messagebox console-application .net-core

我正在开发 .net core 控制台应用程序。我想在想要退出应用程序时提醒用户。像下面这样;

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

但我无法将 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?)    
Run Code Online (Sandbox Code Playgroud)

是否可以在.net core控制台应用程序上显示消息框?

Dan*_*lii 4

为了使用 Windows 窗体,您需要修改.csproj

\n
    \n
  • 设置UseWindowsFormstrue
  • \n
  • 附加-windowsTargetFramework(例如net6.0-windows
  • \n
\n

ConsoleApp.csproj

\n
<Project Sdk="Microsoft.NET.Sdk">\n  <PropertyGroup>\n    <OutputType>Exe</OutputType>\n    <TargetFramework>net6.0-windows</TargetFramework>\n    <UseWindowsForms>true</UseWindowsForms>\n  </PropertyGroup>\n</Project>\n
Run Code Online (Sandbox Code Playgroud)\n

Program.cs

\n
System.Console.WriteLine("Hello, Console!");\nSystem.Windows.Forms.MessageBox.Show("Hello, Popup!");\n
Run Code Online (Sandbox Code Playgroud)\n

结果:

\n

结果

\n

笔记:

\n
    \n
  • 我在 Windows x64 上的 .NET Core 3.1、.NET 5 和 .NET 6 上检查了此解决方案。
  • \n
  • 如果您不想显示控制台窗口,请设置OutputType.csprojWinExe不是Exe
  • \n
  • Windows 窗体仅适用于 Windows,此解决方案也是如此。
  • \n
  • 在 .NET Core 3.1 上,不需要将目标框架更改为 Windows,但仍然无法发布适用于 Linux 操作系统的可执行文件。
  • \n
  • 如果您需要在 Windows 上显示弹出窗口的跨平台解决方案,并且仅在 Linux \xe2\x80\x93 上使用控制台,您可以创建自定义构建配置并使用预处理器指令,如下例所示。
  • \n
\n

跨平台ConsoleApp.csproj

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

跨平台Program.cs

\n
System.Console.WriteLine("Hello, Console!");\n\n#if WindowsRuntime\nSystem.Windows.Forms.MessageBox.Show("Hello, Popup!");\n#endif\n
Run Code Online (Sandbox Code Playgroud)\n