Ошибка cs0234 тип или имя пространства имен forms не существует в пространстве имен system windows

I have just started working on c#, and was fiddling with some code sample that I got from some forum.

This code is using a namespace using system.windows.forms for which I am getting an error:

Forms does not exist in the namespace system.windows.

Also I am getting some error related to undefined functions for senddown & sendup which I believe to be in the Forms name space.

I am using visual studio 10 (with .net frame work 4.0). Any idea how to fix this error?

Uwe Keim's user avatar

Uwe Keim

39.7k57 gold badges175 silver badges291 bronze badges

asked Jul 10, 2011 at 5:47

John Smith's user avatar

6

Expand the project in Solution Tree, Right-Click on References, Add Reference, Select System.Windows.Forms on Framework tab.

You need to add reference to some non-default assemblies sometimes.

From comments: for people looking for VS 2019+: Now adding project references is Right-Click on Dependencies in Solution Explorer.

For people looking for VS Code: How do I add assembly references in Visual Studio Code

answered Jul 10, 2011 at 5:50

VMAtm's user avatar

VMAtmVMAtm

28k17 gold badges79 silver badges125 bronze badges

10

In case someone runs into this error when trying to reference Windows Forms components in a .NET Core 3+ WPF app (which is actually not uncommon), the solution is to go into the .csproj file (double click it in VS2019) and add it to the property group node containing the target frameworks. Like this:

<PropertyGroup>
    <TargetFramework>netcoreapp3.0</TargetFramework>
    <UseWPF>true</UseWPF>
    <UseWindowsForms>true</UseWindowsForms>
</PropertyGroup>

Fudge's user avatar

answered Sep 27, 2019 at 7:12

jool's user avatar

jooljool

1,57112 silver badges15 bronze badges

5

If you are writing Windows Forms code in a .Net Core app, then it’s very probable that you run into this error:

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

If you are using the Sdk style project file (which is recommended) your *.csproj file should be similar to this:

<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>

Pay extra attention to these lines:

<Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">
<OutputType>WinExe</OutputType>
<UseWindowsForms>true</UseWindowsForms>
<PackageReference Include="Microsoft.Windows.Compatibility" Version="3.0.0" />

Note that if you are using WPF while referencing some WinForms libraries you should add <UseWPF>true</UseWPF> as well.

Hint: Since .NET 5.0, Microsoft recommends to refer to SDK Microsoft.Net.Sdk in lieu of Microsoft.Net.Sdk.WindowsDesktop.

Owlbuster's user avatar

answered Oct 29, 2019 at 12:11

Bizhan's user avatar

BizhanBizhan

16.2k9 gold badges63 silver badges101 bronze badges

Net >= 5

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

Quoting Announcing .NET 5.0:

Windows desktop APIs (including Windows Forms, WPF, and WinRT) will only be available when targeting net5.0-windows. You can specify an operating system version, like net5.0-windows7 or net5.0-windows10.0.17763.0 ( for Windows October 2018 Update). You need to target a Windows 10 version if you want to use WinRT APIs.

In your project:

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

  <PropertyGroup>
    <OutputType>WinExe</OutputType>
    <TargetFramework>net5.0-windows</TargetFramework>
    <UseWindowsForms>true</UseWindowsForms>
  </PropertyGroup>

</Project>

Also interesting:

  • net5.0 is the new Target Framework Moniker (TFM) for .NET 5.0.
  • net5.0 combines and replaces netcoreapp and netstandard TFMs.
  • net5.0 supports .NET Framework compatibility mode
  • net5.0-windows will be used to expose Windows-specific functionality, including Windows Forms, WPF and WinRT APIs.
  • .NET 6.0 will use the same approach, with net6.0, and will add net6.0-ios and net6.0-android.
  • The OS-specific TFMs can include OS version numbers, like net6.0-ios14.
  • Portable APIs, like ASP.NET Core will be usable with net5.0. The same will be true of Xamarin forms with net6.0.

answered Feb 8, 2021 at 8:52

dani herrera's user avatar

dani herreradani herrera

49k9 gold badges118 silver badges178 bronze badges

You may encounter this problem if you have multiple projects inside a solution and one of them is physically located inside solution folder.
I solved this by right click on this folder inside Solution tree -> then pressing «exclude from project»

exclude folder

answered Oct 6, 2020 at 11:26

Skeptik's user avatar

SkeptikSkeptik

491 silver badge4 bronze badges

For some one just need the struct and some function from Windowsform namespace, you just need to change the the project to old behave.

Make DisableWinExeOutputInference true then OutputType dont be override by visual studio :D.

Dont foget set add -windows to TargetFramework

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net5.0-windows</TargetFramework>
<DisableWinExeOutputInference>true</DisableWinExeOutputInference>
<UseWindowsForms>true</UseWindowsForms>
<StartupObject></StartupObject>
<ApplicationIcon />
</PropertyGroup>

here where i found them
https://learn.microsoft.com/en-us/dotnet/core/compatibility/sdk/5.0/sdk-and-target-framework-change

answered Feb 11 at 3:22

noir Kelo's user avatar

browxy.com 
Compilation failed: 1 error(s), 0 warnings
main.cs(7,24): error CS0234: The type or namespace name `Forms' does not exist in the namespace `System.Windows'. Are you missing `System.Windows.Forms' assembly reference?

browxy.com

answered Mar 25, 2021 at 17:03

CS QGB's user avatar

CS QGBCS QGB

2951 gold badge3 silver badges12 bronze badges

1

I have just started working on c#, and was fiddling with some code sample that I got from some forum.

This code is using a namespace using system.windows.forms for which I am getting an error:

Forms does not exist in the namespace system.windows.

Also I am getting some error related to undefined functions for senddown & sendup which I believe to be in the Forms name space.

I am using visual studio 10 (with .net frame work 4.0). Any idea how to fix this error?

Uwe Keim's user avatar

Uwe Keim

39.7k57 gold badges175 silver badges291 bronze badges

asked Jul 10, 2011 at 5:47

John Smith's user avatar

6

Expand the project in Solution Tree, Right-Click on References, Add Reference, Select System.Windows.Forms on Framework tab.

You need to add reference to some non-default assemblies sometimes.

From comments: for people looking for VS 2019+: Now adding project references is Right-Click on Dependencies in Solution Explorer.

For people looking for VS Code: How do I add assembly references in Visual Studio Code

answered Jul 10, 2011 at 5:50

VMAtm's user avatar

VMAtmVMAtm

28k17 gold badges79 silver badges125 bronze badges

10

In case someone runs into this error when trying to reference Windows Forms components in a .NET Core 3+ WPF app (which is actually not uncommon), the solution is to go into the .csproj file (double click it in VS2019) and add it to the property group node containing the target frameworks. Like this:

<PropertyGroup>
    <TargetFramework>netcoreapp3.0</TargetFramework>
    <UseWPF>true</UseWPF>
    <UseWindowsForms>true</UseWindowsForms>
</PropertyGroup>

Fudge's user avatar

answered Sep 27, 2019 at 7:12

jool's user avatar

jooljool

1,57112 silver badges15 bronze badges

5

If you are writing Windows Forms code in a .Net Core app, then it’s very probable that you run into this error:

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

If you are using the Sdk style project file (which is recommended) your *.csproj file should be similar to this:

<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>

Pay extra attention to these lines:

<Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">
<OutputType>WinExe</OutputType>
<UseWindowsForms>true</UseWindowsForms>
<PackageReference Include="Microsoft.Windows.Compatibility" Version="3.0.0" />

Note that if you are using WPF while referencing some WinForms libraries you should add <UseWPF>true</UseWPF> as well.

Hint: Since .NET 5.0, Microsoft recommends to refer to SDK Microsoft.Net.Sdk in lieu of Microsoft.Net.Sdk.WindowsDesktop.

Owlbuster's user avatar

answered Oct 29, 2019 at 12:11

Bizhan's user avatar

BizhanBizhan

16.2k9 gold badges63 silver badges101 bronze badges

Net >= 5

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

Quoting Announcing .NET 5.0:

Windows desktop APIs (including Windows Forms, WPF, and WinRT) will only be available when targeting net5.0-windows. You can specify an operating system version, like net5.0-windows7 or net5.0-windows10.0.17763.0 ( for Windows October 2018 Update). You need to target a Windows 10 version if you want to use WinRT APIs.

In your project:

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

  <PropertyGroup>
    <OutputType>WinExe</OutputType>
    <TargetFramework>net5.0-windows</TargetFramework>
    <UseWindowsForms>true</UseWindowsForms>
  </PropertyGroup>

</Project>

Also interesting:

  • net5.0 is the new Target Framework Moniker (TFM) for .NET 5.0.
  • net5.0 combines and replaces netcoreapp and netstandard TFMs.
  • net5.0 supports .NET Framework compatibility mode
  • net5.0-windows will be used to expose Windows-specific functionality, including Windows Forms, WPF and WinRT APIs.
  • .NET 6.0 will use the same approach, with net6.0, and will add net6.0-ios and net6.0-android.
  • The OS-specific TFMs can include OS version numbers, like net6.0-ios14.
  • Portable APIs, like ASP.NET Core will be usable with net5.0. The same will be true of Xamarin forms with net6.0.

answered Feb 8, 2021 at 8:52

dani herrera's user avatar

dani herreradani herrera

49k9 gold badges118 silver badges178 bronze badges

You may encounter this problem if you have multiple projects inside a solution and one of them is physically located inside solution folder.
I solved this by right click on this folder inside Solution tree -> then pressing «exclude from project»

exclude folder

answered Oct 6, 2020 at 11:26

Skeptik's user avatar

SkeptikSkeptik

491 silver badge4 bronze badges

For some one just need the struct and some function from Windowsform namespace, you just need to change the the project to old behave.

Make DisableWinExeOutputInference true then OutputType dont be override by visual studio :D.

Dont foget set add -windows to TargetFramework

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net5.0-windows</TargetFramework>
<DisableWinExeOutputInference>true</DisableWinExeOutputInference>
<UseWindowsForms>true</UseWindowsForms>
<StartupObject></StartupObject>
<ApplicationIcon />
</PropertyGroup>

here where i found them
https://learn.microsoft.com/en-us/dotnet/core/compatibility/sdk/5.0/sdk-and-target-framework-change

answered Feb 11 at 3:22

noir Kelo's user avatar

browxy.com 
Compilation failed: 1 error(s), 0 warnings
main.cs(7,24): error CS0234: The type or namespace name `Forms' does not exist in the namespace `System.Windows'. Are you missing `System.Windows.Forms' assembly reference?

browxy.com

answered Mar 25, 2021 at 17:03

CS QGB's user avatar

CS QGBCS QGB

2951 gold badge3 silver badges12 bronze badges

1

1 / 1 / 0

Регистрация: 20.04.2016

Сообщений: 53

1

01.09.2016, 19:01. Показов 22716. Ответов 4


Студворк — интернет-сервис помощи студентам

Доброго времени суток, у меня возникла проблема при добавлении System.Windows.Forms чтобы использовать в Wpf не который в функционал WF. И выдает он следующую ошибку: Тип или имя пространства имен «Forms» не существует в пространстве имен «System.Windows».



0



Ev_Hyper

Заблокирован

01.09.2016, 19:10

2

hoteng, ссылку на System.Windows.Forms и WindowsFormsIntegration добавили?

Цитата
Сообщение от hoteng
Посмотреть сообщение

использовать в Wpf не который в функционал WF

Вы уверены, что вам это нужно?



0



hoteng

1 / 1 / 0

Регистрация: 20.04.2016

Сообщений: 53

01.09.2016, 19:23

 [ТС]

3

C#
1
Windows.Forms.Integration

как я могу использовать данное пространство имен если, System.Windows.Form не находит имя Form.



1



Ev_Hyper

Заблокирован

01.09.2016, 20:16

4

Лучший ответ Сообщение было отмечено hoteng как решение

Решение

hoteng,

1. В обозревателе решений щелкните правой кнопкой мыши узел проекта и выберите команду Добавить ссылку.
2. В диалоговом окне Добавление ссылки выберите вкладку, соответствующую типу компонента, ссылка на который создается.
3. Выберите компоненты, на которые надо ссылаться, и нажмите кнопку OK.

скопировал вот отсюда:
https://msdn.microsoft.com/ru-… .120).aspx



5



1 / 1 / 0

Регистрация: 20.04.2016

Сообщений: 53

01.09.2016, 20:45

 [ТС]

5

Благодарю



0



Пока я использую System.Windows.Forms в своем проекте

Эта ошибка появляется

Имя типа или пространства имен «Forms» не существует в пространстве имен «System.Windows» (вам не хватает ссылки на сборку?)

См. этот вопрос

Я добавил следующий код в свой .csproj. Но это не устраняет ошибку.

<Reference Include="System.Windows.Forms" Version="2.0.0.0"/>

Обратитесь к этому вопросу, я Я использую код визуальной студии, и это похоже не очень помогает в моей ситуации. Есть ли способ добавить ссылку для решения проблемы? Спасибо, что уделили время моему вопросу!!

person
JJ___
  
schedule
29.01.2018
  
source
источник


Ответы (1)

Вы не забыли добавить ссылку таким образом:

введите здесь описание изображения

Потому что, если вы этого не сделали, вполне возможно, что именно поэтому вам нужно щелкнуть правой кнопкой мыши по ссылкам, которые выделены синим цветом на изображении. а затем выберите «Добавить ссылку».

Я сделал это, и я могу создать и отобразить форму из консольного приложения.

РЕДАКТИРОВАТЬ:

Как добавить ссылки на сборки в Visual Studio Code?

Пожалуйста, обратитесь к этой ссылке для этого решения визуального студийного кода. Я извиняюсь. Однако другое решение отлично подходит для визуальной студии :) Так что я оставляю его :)

На самом деле мне кажется, что System.Windows.Forms не поддерживается для VS Code, поскольку для подмножества Windows.Forms требуются некоторые специфические функции Windows.

Для полной поддержки рекомендуется установить сообщество Visual Studio.

Прошу прощения за путаницу. Я должен был сначала проверить, поддерживается ли библиотека. Я этого не сделал.

https://code.visualstudio.com/docs/languages/csharp

Ссылка внизу содержит небольшой раздел часто задаваемых вопросов, в котором рассказывается об установке сообщества Visual Studio для полной поддержки функций.

person
Morten Bork
  
schedule
29.01.2018

Если вы пишете код Windows Forms в приложении .Net Core, очень вероятно, что вы столкнетесь с этой ошибкой:

Ошибка CS0234 Тип или имя пространства имен Forms не существует в пространстве имен System.Windows (отсутствует ссылка на сборку?)

Если вы используете файл проекта в стиле 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" />

Обратите внимание: если вы используете WPF, ссылаясь на некоторые библиотеки WinForms, вам следует добавить <UseWPF>true</UseWPF> также.

Другие наши интересноые статьи:

  • Ошибка easy anti cheat please run windows update
  • Ошибка critical structure corruption windows 10 как исправить
  • Ошибка c0000034 при операции обновления windows 10
  • Ошибка dxgmms2 sys на синем экране windows 10
  • Ошибка inaccessible boot device при загрузке windows 10

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии