.Net 8 Console 程序中使用 Windows 弹窗

更新日期: 2024-06-07 阅读次数: 416 字数: 299 分类: Windows

例如,咱把 .Net Console 默认的 hello world 程序修改一下,增加一个弹窗。

using System.Windows.Forms;

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

DialogResult res = MessageBox.Show("Are you sure you want to Delete", "Confirmation", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
if (res == DialogResult.OK) {
    MessageBox.Show("You have clicked Ok Button");
    //Some task…
}
if (res == DialogResult.Cancel) {
    MessageBox.Show("You have clicked Cancel Button");
    //Some task…
}

不出所料,错误出现了。

'Forms' does not exist in the namespace 'System.Windows'

第一行引入 System.Windows.Forms,就报错了。

The type or namespace name 'Forms' does not exist in the namespace 'System.Windows' (are you missing an assembly reference?)

需要在 .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>

再次执行

dotnet run

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

结语

VS Code 搞 DotNet 开发还是不太行,按理说,这些错误 IDE 就能解决,这样手动修改确实麻烦。

不行就得上 Visual Studio 社区版了。

微信关注我哦 👍

大象工具微信公众号

我是来自山东烟台的一名开发者,有敢兴趣的话题,或者软件开发需求,欢迎加微信 zhongwei 聊聊, 查看更多联系方式

tags: dotnet