我刚刚开始研究 c#,并且正在摆弄从某个论坛获得的一些代码示例。
这段代码使用了一个命名空间
using system.windows.forms
,我收到了一个错误:
命名空间 system.windows 中不存在 Forms。
我还收到一些与
senddown
和 sendup
的未定义函数相关的错误,我相信它们位于 Forms
命名空间中。
我正在使用 Visual Studio 10(带有 .net Framework 4.0)。知道如何修复这个错误吗?
在解决方案树中展开项目,右键单击
References
、Add Reference
,选择System.Windows.Forms
选项卡上的Framework
。
有时需要添加对一些非默认程序集的引用。
来自评论:对于寻找 VS 2019+ 的人:现在添加项目引用是在 Dependencies
中的
Solution Explorer
上右键单击。
对于寻找 VS Code 的人:如何在 Visual Studio Code 中添加程序集引用
如果有人在尝试引用 .NET Core 3+ WPF 应用程序中的 Windows Forms 组件时遇到此错误(实际上并不罕见),解决方案是进入
.csproj
文件(在中双击它) VS2019)并将其添加到包含目标框架的属性组节点。像这样:
<PropertyGroup>
<TargetFramework>netcoreapp3.0</TargetFramework>
<UseWPF>true</UseWPF>
<UseWindowsForms>true</UseWindowsForms>
</PropertyGroup>
如果您在 .Net Core 应用程序中编写 Windows Forms 代码,那么您很可能会遇到此错误:
错误 CS0234 命名空间“System.Windows”中不存在类型或命名空间名称“Forms”(是否缺少程序集引用?)
如果您使用 Sdk 样式项目文件(推荐),您的 *.csproj 文件应与此类似:
<Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
<OutputType>WinExe</OutputType>
<UseWindowsForms>true</UseWindowsForms>
<RootNamespace>MyAppNamespace</RootNamespace>
<AssemblyName>MyAppName</AssemblyName>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Windows.Compatibility" Version="3.0.0" />
</ItemGroup>
</Project>
特别注意这些行:
<Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">
<OutputType>WinExe</OutputType>
<UseWindowsForms>true</UseWindowsForms>
<PackageReference Include="Microsoft.Windows.Compatibility" Version="3.0.0" />
请注意,如果您在引用某些 WinForms 库时使用 WPF,则还应该添加
<UseWPF>true</UseWPF>
。
提示:自 .NET 5.0 起,Microsoft 建议参考 SDK
Microsoft.Net.Sdk
代替 Microsoft.Net.Sdk.WindowsDesktop
。
<TargetFramework>
net5.0-windows
</TargetFramework>
引用宣布.NET 5.0:
Windows 桌面 API(包括 Windows Forms、WPF 和 WinRT)将仅在面向 net5.0-windows 时可用。您可以指定操作系统版本,例如 net5.0-windows7 或 net5.0-windows10.0.17763.0(适用于 Windows October 2018 Update)。如果您想使用 WinRT API,您需要定位 Windows 10 版本。
在您的项目中:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net5.0-windows</TargetFramework>
<UseWindowsForms>true</UseWindowsForms>
</PropertyGroup>
</Project>
也很有趣:
对于某些人只需要 Windowsform 命名空间中的结构和一些函数,您只需将项目更改为旧的行为即可。
将DisableWinExeOutputInference设置为true,然后OutputType不会被Visual Studio覆盖:D。
不要忘记将 add -windows 设置为 TargetFramework
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net5.0-windows</TargetFramework>
<DisableWinExeOutputInference>true</DisableWinExeOutputInference>
<UseWindowsForms>true</UseWindowsForms>
<StartupObject></StartupObject>
<ApplicationIcon />
</PropertyGroup>
在这里我找到了它们 https://learn.microsoft.com/en-us/dotnet/core/compatibility/sdk/5.0/sdk-and-target-framework-change
转到项目属性->应用程序->常规。 选择“为此项目启用 Windows 窗体”复选框。
最干净的解决方案是添加这个 nuget 包 链接到 nuget 包页面