System windows forms ошибка

For Those using Visual Studio 2022 with .Net Core 6.0

Sorry to revive this thread, but I created an account just to do so, as none of the solutions I found searching google for days worked for me alone, and seemed to only bring up only outdated tutorials.

Not Working =(

What DID work for me

  1. Double click your project (opening the csproj editor window)

Add the following lines (replacing the existing TargetFramework line):

<TargetFramework>net6.0-windows</TargetFramework>
<UseWindowsForms>true</UseWindowsForms>

My window, for referrence, looks like:

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

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net6.0-windows</TargetFramework>
      <UseWindowsForms>true</UseWindowsForms>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

</Project>
  1. Note Both lines! I read several solutions / videos that stopped simply after adding the «UseWindowsForms» tag, which did not solve the problem for me, even after unloading and reloading/closing and opening etc.

I stumbled on this solution after applying the «UseWindowsForms» tag, and then in desperation changing my NET framework in properties to 5.0, which caused it to work, and then noted when changing back to 6.0 it still worked.

If you forget the Framework tag in the future, you can reproduce the effect just by flipping your properties back and forth…

  1. Right click the project, and go to properties.

  2. Change the Target framework from .NET 6.0…to….NET 5.0

  3. Exit back to your code. Which after a few moments will show the System.Windows.Forms connecting properly.

  4. Open back up properties.

  5. Change the Target framework from .Net 5.0, back to .Net 6.0

Congratulations

You have (or at least I have) a .Net 6.0 project that is properly allowing me to use System.Windows.Forms (Including the Clipboard, which I suspect many here are looking for…).

I did due diligence on this, testing it multiple times across multiple projects, and it (at least for my setup) consistently works!

BTW. For those wondering. the [STAThread] Attribute tag seen in the pictures is needed to allow the Clipboard class to function. (this is also why I am not using top level statements in the example, but if you don’t need that Class, the example works with top level statements (I needed it to show my Clipboard test….)

COM->System.Windows.Forms

это не COM

.net Core, Visual Studio 2019, создаю проект в консоли(так ведь можно)

можно, но только когда вы знаете что делать дальше. а сейчас очевидно что не знаете:
— в .net Core формы поддерживатся с версии самой корки 3.*
— .net Core 3.* поддерживается начиная с Visual Studio 2019 (и то начиная со свежих билдов, осенних)
— визуального редактора форм на данный момент не существует
— есть руководство https://docs.microsoft.com/ru-ru/dotnet/core/porti… (что подключать там тоже написано)

совет — если вы только начинаете изучать программирование, не готовы осваивать XAML и нуждаете в визуальном редакторе форм, практикуйтесь сначала в .Net Framework, и используйте шаблон проекта WinForms

Вам нужно добавить ссылку на зависимость в свойствах проекта в обозревателе решений. Конечно, если проект не выполняется на .NET Core, в таком случае вам нужно подключить соответсвующее расширение с помощбю менеджера пакетов Nuget для проекта

microsoft visual studio 2022
Проект Библиотека классов .NET 7
пкм по проекту (или зависимости) выбираем: Добавить => Ссылка на проект => Кликаем обзор =>
Отрывается окно => Переходим по структуре файлов вверх до папки «2022» =>
В поле поиска вставляем «System.Windows.Forms» => В результате ищем нужное (Примерно 3 снизу) =>
Выбираем => Тыкаем Добавить.
В свойствах проекта добавляем поддержку Windows Worms (если WPF).
Готово!
C:Program FilesMicrosoft Visual Studio2022CommunitydotnetruntimesharedMicrosoft.WindowsDesktop.App6.0.14System.Windows.Forms.dll

I’ve been using Powershell and want to start using C#. My plan is to start by converting some powershell code to C#. The first thing I am trying is a file dialog box. Simple I thought.

Powershell(which works):

$fd = New-Object system.windows.forms.openfiledialog

I tried various things in C# but it seems to come down to :

using System.Windows.Forms;  //»Forms» underlines red in Visual Studio 2017

Compiler message :

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

Do I have version issues and how might I fix?

Here is «About» for Visual Studio

Microsoft Visual Studio Community 2017 
Version 15.9.4
VisualStudio.15.Release/15.9.4+28307.222
Microsoft .NET Framework
Version 4.8.03752

Installed Version: Community

Application Insights Tools for Visual Studio Package   8.14.11009.1
Application Insights Tools for Visual Studio

ASP.NET and Web Tools 2017   15.9.04012.0
ASP.NET and Web Tools 2017

ASP.NET Core Razor Language Services   15.8.31590
Provides languages services for ASP.NET Core Razor.

ASP.NET Web Frameworks and Tools 2017   5.2.60913.0
For additional information, visit https://www.asp.net/

Azure App Service Tools v3.0.0   15.9.03024.0
Azure App Service Tools v3.0.0

Azure Functions and Web Jobs Tools   15.9.02046.0
Azure Functions and Web Jobs Tools

C# Tools   2.10.0-beta2-63501-03+b9fb1610c87cccc8ceb74a770dba261a58e39c4a
C# components used in the IDE. Depending on your project type and settings, a different version of the compiler may be used.

Common Azure Tools   1.10
Provides common services for use by Azure Mobile Services and Microsoft Azure Tools.

JavaScript Language Service   2.0
JavaScript Language Service

Microsoft Azure Tools   2.9
Microsoft Azure Tools for Microsoft Visual Studio 2017 — v2.9.10730.2

Microsoft Continuous Delivery Tools for Visual Studio   0.4
Simplifying the configuration of Azure DevOps pipelines from within the Visual Studio IDE.

Microsoft JVM Debugger   1.0
Provides support for connecting the Visual Studio debugger to JDWP compatible Java Virtual Machines

Microsoft Library Manager   1.0
Install client-side libraries easily to any web project

Microsoft MI-Based Debugger   1.0
Provides support for connecting Visual Studio to MI compatible debuggers

Microsoft Visual Studio Tools for Containers   1.1
Develop, run, validate your ASP.NET Core applications in the target environment. F5 your application directly into a container with debugging, or CTRL + F5 to edit & refresh your app without having to rebuild the container.

NuGet Package Manager   4.6.0
NuGet Package Manager in Visual Studio. For more information about NuGet, visit http://docs.nuget.org/.

ProjectServicesPackage Extension   1.0
ProjectServicesPackage Visual Studio Extension Detailed Info

ResourcePackage Extension   1.0
ResourcePackage Visual Studio Extension Detailed Info

ResourcePackage Extension   1.0
ResourcePackage Visual Studio Extension Detailed Info

SQL Server Data Tools   15.1.61810.11040
Microsoft SQL Server Data Tools

TypeScript Tools   15.9.20918.2001
TypeScript Tools for Microsoft Visual Studio

Visual Basic Tools   2.10.0-beta2-63501-03+b9fb1610c87cccc8ceb74a770dba261a58e39c4a
Visual Basic components used in the IDE. Depending on your project type and settings, a different version of the compiler may be used.

Visual F# Tools 10.2 for F# 4.5   15.8.0.0.  Commit Hash: 6e26c5bacc8c4201e962f5bdde0a177f82f88691.
Microsoft Visual F# Tools 10.2 for F# 4.5

Visual Studio Code Debug Adapter Host Package   1.0
Interop layer for hosting Visual Studio Code debug adapters in Visual Studio

Visual Studio Tools for Containers   1.0
Visual Studio Tools for Containers

Thanks

2 / 1 / 1

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

Сообщений: 49

1

11.08.2019, 20:33. Показов 7982. Ответов 4


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

Я обнаружил что у меня отсутствует пространство имен System.Windows.Forms. Просьба подсказать, что делать.



0



Pvt

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

11.08.2019, 20:49

2

C#
1
using System.Windows.Forms;

не помогает? в обозревателе решений ссылки проверить



0



2 / 1 / 1

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

Сообщений: 49

11.08.2019, 21:06

 [ТС]

3

Проверил, там такой ссылки действительно нет.

Добавлено через 12 минут
Что делать?



0



Pvt

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

11.08.2019, 22:07

4

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

Решение

ПКМ Ссылки/Добавить ссылку/.NET/System.Windows.Forms



1



Happyness

0 / 0 / 0

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

Сообщений: 4

19.07.2021, 15:45

5

Проблема бывает, когда пишем свою dll.
1. Кликаем правой кнопкой мыши в обозревателе решений на
имени нашего решения (строка с иконкой c#).
Жмём Добавить -> Ссылка. Ставим птичку на System.Windows.Forms
2. Если мы используем MessageBox, то в блоке using пишем:
using MessageBox = System.Windows.Forms.MessageBox;
(другие визуальные элементы — по аналогии)
Пример кода dll-ки:

C#
1
2
3
4
5
6
7
8
9
10
11
12
using MessageBox = System.Windows.Forms.MessageBox;
 
namespace Lib
{
    public class Class1
    {
        public static void Method()
        {
            MessageBox.Show("123");
        }
    }
}



0




компилятор ругается на System.Windows.Forms;

От: Аноним

 
Дата:  11.07.05 07:18
Оценка:

Коллеги, подскажите, плиз!

Изучаю .NET. Попробовал в программке на С# выдать элементарный MessageBox.
Написал так:

using System.Windows.Forms;

......
......

MessageBox.Show("Привет!");

или вот так:

System.Windows.Forms.MessageBox.Show("Привет!");

При компиляции получаю сообщение:
The type or namespace name ‘Windows’ does not exist in the class or namespace ‘System’ (are you missing an assembly reference?)

Что за лажа?


Re: компилятор ругается на System.Windows.Forms;

От:

Jenyay

http://jenyay.net
Дата:  11.07.05 07:23
Оценка:

Здравствуйте, <Аноним>, Вы писали:

А>При компиляции получаю сообщение:

А>The type or namespace name ‘Windows’ does not exist in the class or namespace ‘System’ (are you missing an assembly reference?)

А System.Windows.Forms.dll подключил?

… << RSDN@Home 1.1.4 beta 7 rev. 0>>


Re[2]: компилятор ругается на System.Windows.Forms;

От: Аноним

 
Дата:  11.07.05 07:28
Оценка:

Здравствуйте, Jenyay, Вы писали:

J>Здравствуйте, <Аноним>, Вы писали:


А>>При компиляции получаю сообщение:

А>>The type or namespace name ‘Windows’ does not exist in the class or namespace ‘System’ (are you missing an assembly reference?)

J>А System.Windows.Forms.dll подключил?

Нет. А что — надо для каждого using’а явно подключать dll


Re[2]: компилятор ругается на System.Windows.Forms;

От: Аноним

 
Дата:  11.07.05 07:31
Оценка:

Здравствуйте, Jenyay, Вы писали:

J>Здравствуйте, <Аноним>, Вы писали:


А>>При компиляции получаю сообщение:

А>>The type or namespace name ‘Windows’ does not exist in the class or namespace ‘System’ (are you missing an assembly reference?)

J>А System.Windows.Forms.dll подключил?

А на кой тогда ключевое слово using, если компилятору надо объяснять, где брать стандартные библиотеки?!


Re[2]: компилятор ругается на System.Windows.Forms;

От: Аноним

 
Дата:  11.07.05 07:40
Оценка:

Здравствуйте, Jenyay, Вы писали:

J>Здравствуйте, <Аноним>, Вы писали:


А>>При компиляции получаю сообщение:

А>>The type or namespace name ‘Windows’ does not exist in the class or namespace ‘System’ (are you missing an assembly reference?)

J>А System.Windows.Forms.dll подключил?

Аууу!?

Объясните дураку, когда компилятор хавает using без подключения dll, а когда нет?!

В java всегда достаточно написать #import (аналог С#-го usinga)…


Re[3]: компилятор ругается на System.Windows.Forms;

От:

_FRED_

Черногория

@ViIvanov
Дата:  11.07.05 07:43
Оценка:

Здравствуйте, <Аноним>, Вы писали:

А>>>При компиляции получаю сообщение:

А>>>The type or namespace name ‘Windows’ does not exist in the class or namespace ‘System’ (are you missing an assembly reference?)

J>>А System.Windows.Forms.dll подключил?

А>Нет. А что — надо для каждого using’а явно подключать dll

Не для каждого «каждого using’а», а для каждого класса надо найти в МСДН (или другой документации) его описание и посмотреть секцию «Requirements» (в самом низу страницы, например здесь) — из неё можно узнать пространство имён, которое надо указать перед использованием класса («Namespace») и сборку, которую надо подключить к проекту («Assembly») если она ещё не подключена.

В одной сборке могут быть классы из нескольких пространств имён (System.Uri и System.Net.Sockets.TcpClient в System.dll), так же как и классы из разных сборок могут быть в одном пространстве имён (System.Uri в System.dll и System.Int32 в mscorlib.dll).

<< RSDN@Home 1.1.4 beta 7 rev. 500 >> =11:43= [Windows XP — 5.1.2600.0]
under «*none*»

Help will always be given at Hogwarts to those who ask for it.


Re[3]: компилятор ругается на System.Windows.Forms;

От:

Oyster

Украина

https://github.com/devoyster
Дата:  11.07.05 07:44
Оценка:

Здравствуйте, <Аноним>, Вы писали:

А>Объясните дураку, когда компилятор хавает using без подключения dll, а когда нет?!


А>В java всегда достаточно написать #import (аналог С#-го usinga)…

В .NET всегда надо явно добавлять в references используемые сборки. Класс MessageBox находится в сборке System.Windows.Forms, поэтому эту сборку надо явно добавить в references.

http://rsdn.org/File/27948/bf.gif


Re: компилятор ругается на System.Windows.Forms;

От:

nzeemin

Россия

http://nzeemin.livejournal.com/
Дата:  11.07.05 07:45
Оценка:

Здравствуйте, <Аноним>, Вы писали:

А>При компиляции получаю сообщение:

А>The type or namespace name ‘Windows’ does not exist in the class or namespace ‘System’ (are you missing an assembly reference?)

Вероятно, вы не добавили эту библиотеку в References проекта. using лишь указывает, что в данном файле используются объявления из этой библиотеки…

Создавайте проект через File|New|Project, Windows Application — все необходимые библиотеки будут сразу подключены в References.


Re[4]: компилятор ругается на System.Windows.Forms;

От: Аноним

 
Дата:  11.07.05 07:55
Оценка:

Здравствуйте, Oyster, Вы писали:

O>Здравствуйте, <Аноним>, Вы писали:


А>>Объясните дураку, когда компилятор хавает using без подключения dll, а когда нет?!


А>>В java всегда достаточно написать #import (аналог С#-го usinga)…


O>В .NET всегда надо явно добавлять в references используемые сборки. Класс MessageBox находится в сборке System.Windows.Forms, поэтому эту сборку надо явно добавить в references.

ВСЕГДА???
Я уже не первый день пробую писать всякие тестовые приложеньица на С# (например, использовал System.Collections — и ничего, кроме using’а компилятору не «объяснял») — и только первый раз наткнулся на необходимость явно делать Reference…


Re[4]: компилятор ругается на System.Windows.Forms;

От: Аноним

 
Дата:  11.07.05 08:03
Оценка:

Здравствуйте, Oyster, Вы писали:

O>Здравствуйте, <Аноним>, Вы писали:


А>>Объясните дураку, когда компилятор хавает using без подключения dll, а когда нет?!


А>>В java всегда достаточно написать #import (аналог С#-го usinga)…


O>В .NET всегда надо явно добавлять в references используемые сборки. Класс MessageBox находится в сборке System.Windows.Forms, поэтому эту сборку надо явно добавить в references.

«Самые стандартные» классы компилятор хавает по умолчанию?


Re[5]: компилятор ругается на System.Windows.Forms;

От:

Oyster

Украина

https://github.com/devoyster
Дата:  11.07.05 08:09
Оценка:

Здравствуйте, <Аноним>, Вы писали:

O>>В .NET всегда надо явно добавлять в references используемые сборки. Класс MessageBox находится в сборке System.Windows.Forms, поэтому эту сборку надо явно добавить в references.


А>»Самые стандартные» классы компилятор хавает по умолчанию?

Нет, просто некоторые сборки включаются в проект по умолчанию. Например, всегда подключается сборка mscorlib (даже если её нет в references), по умолчанию в VS.NET 2003 в references добавляются System, System.Data, System.Xml.

http://rsdn.org/File/27948/bf.gif


Re[4]: компилятор ругается на System.Windows.Forms;

От: Аноним

 
Дата:  11.07.05 08:10
Оценка:

_FR>Не для каждого «каждого using’а», а для каждого класса надо найти в МСДН (или другой документации) его описание и посмотреть секцию «Requirements» (в самом низу страницы, например здесь) — из неё можно узнать пространство имён, которое надо указать перед использованием класса («Namespace») и сборку, которую надо подключить к проекту («Assembly») если она ещё не подключена.

_FR>В одной сборке могут быть классы из нескольких пространств имён (System.Uri и System.Net.Sockets.TcpClient в System.dll), так же как и классы из разных сборок могут быть в одном пространстве имён (System.Uri в System.dll и System.Int32 в mscorlib.dll).

СЕНК! Чисто конкретный ответ — по-програмерски!!! Ато начитают деепричастными оборотами сыпать…


Re[6]: компилятор ругается на System.Windows.Forms;

От: Аноним

 
Дата:  11.07.05 08:12
Оценка:

Здравствуйте, Oyster, Вы писали:

O>Здравствуйте, <Аноним>, Вы писали:


O>>>В .NET всегда надо явно добавлять в references используемые сборки. Класс MessageBox находится в сборке System.Windows.Forms, поэтому эту сборку надо явно добавить в references.


А>>»Самые стандартные» классы компилятор хавает по умолчанию?


O>Нет, просто некоторые сборки включаются в проект по умолчанию. Например, всегда подключается сборка mscorlib (даже если её нет в references), по умолчанию в VS.NET 2003 в references добавляются System, System.Data, System.Xml.

СЕНКАЮ! Въехал.


Re[3]: компилятор ругается на System.Windows.Forms;

От:

SiAVoL

Россия

 
Дата:  11.07.05 08:36
Оценка:

Здравствуйте, <Аноним>, Вы писали:

А>А на кой тогда ключевое слово using, если компилятору надо объяснять, где брать стандартные библиотеки?!

using System.Windows.Forms;

Так вот, этой строкой никаких дополнительных сборок не подключается. Вообще говоря, физически пространств имен в .NET не существует
Строка просто указывает в каких пространствах имен следует искать класс, который в коде указан коротким именем (System.Windows.Forms.MessageBox — полное имя класса, а MessageBox — короткое). Т.о. это избавляет нас от необходимости писать везде System.Windows.Forms.MessageBox.Show(«Привет!»)
, вместо короткого варианта MessageBox.Show(«Привет!»)
Т.е. using это просто синтаксический сахар, позволяющий меньше стучать по клавиатуре и получать более удобочитаемый код, не более того.

… << RSDN@Home 1.1.4 beta 7 rev. 501>>


Re[3]: компилятор ругается на System.Windows.Forms;

От:

misha_sk

Россия

 
Дата:  11.07.05 09:13
Оценка:

А>Объясните дураку, когда компилятор хавает using без подключения dll, а когда нет?!

А>В java всегда достаточно написать #import (аналог С#-го usinga)…

В Java для поиска физического размещения классов используется переменная окружения CLASSPATH. Правда там идет смешенивание физического размшения и логического, в виду необходимости структурирования пакетов по каталогам файловой системы.

Подождите ...

Wait...

  • Переместить
  • Удалить
  • Выделить ветку

Пока на собственное сообщение не было ответов, его можно удалить.

Я пробовал сделать (мою первую) программу на С#:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("hello");
            Console.ReadLine();
        }
    }
}

Это хорошо, но если я попытаюсь использовать System.Windows.Forms:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("hello");
            System.MessageBox("hello");
            Console.ReadLine();
        }
    }
}

Это ошибка, которую я получаю:

Error   1   The type or namespace name 'Windows' does not exist in the namespace     'System' (are you missing an assembly reference?)  C:UsersRamyDocumentsVisual Studio 2010ProjectsConsoleApplication1ConsoleApplication1Program.cs  5   14  ConsoleApplication1

Некоторые детали:
— Я использую Visual Studio 2012;
— Я установил .NET Development Kit;
— Это консольное приложение.

Может быть, потому что на консольном приложении нельзя использовать System.Windows.Forms?
Если да, то какая программа должна быть? Я также пробовал с формой, но я только показывал окно и никакого кода.

  • #1

I’m converting to Net5. I have 40 out of 41 projects converted OK

The remaining project will not let me reference System.WindowsForms.

There are two versions of System.WindowsForms, I’ve been using 2.4 routinely (I hope that’s what I should be doing).

I tried them both in the troublesome procedure.

What happens is: I select Project/Add COM Reference and then check System.WindowsForms.

Close the dialog and reopen it and see that the check is gone.

I did this because checking it did not have any effect on the error I was trying to fix.

I’m using System.Windows.Forms.StatusBarPanel. Could that be a problem in Net5?

BTW. I also tried including:

 <ItemGroup>
        <Import Include="Microsoft.VisualBasic" />
        <Import Include="System" />
        <Import Include="System.Collections" />
        <Import Include="System.Collections.Generic" />
        <Import Include="System.Data" />
        <Import Include="System.Drawing" />
        <Import Include="System.Diagnostics" />
        <Import Include="System.Windows.Forms" />
        <Import Include="System.Linq" />
        <Import Include="System.Xml.Linq" />
        <Import Include="System.Threading.Tasks" />
    </ItemGroup>

In that case I also checked System.WindowsForms (I’m not sure it would show checked) but it was not checked.

Last edited: Jan 17, 2021

JohnH


  • JohnH

    JohnH

  • Jan 17, 2021

I’m using System.Windows.Forms.StatusBarPanel. Could that be a problem in Net5?

docs.microsoft.com

StatusBarPanel Class (System.Windows.Forms)

Represents a panel in a StatusBar control. This class is not available in .NET 5 and later versions. Use the StatusStrip control instead, which replaces and extends the StatusBar control.


docs.microsoft.com

This class is not available in .NET 5.0 and later versions. Use the StatusStrip control instead, which replaces and extends the StatusBar control.

MenuStrip/ToolStrip/StatusStrip were introduced as replacements for Menu/ToolBar/StatusBar in .Net 2.0.

JohnH

JohnH

VB.NET Forum Moderator


  • #2

I’m using System.Windows.Forms.StatusBarPanel. Could that be a problem in Net5?

docs.microsoft.com

StatusBarPanel Class (System.Windows.Forms)

Represents a panel in a StatusBar control. This class is not available in .NET 5 and later versions. Use the StatusStrip control instead, which replaces and extends the StatusBar control.


docs.microsoft.com

This class is not available in .NET 5.0 and later versions. Use the StatusStrip control instead, which replaces and extends the StatusBar control.

MenuStrip/ToolStrip/StatusStrip were introduced as replacements for Menu/ToolBar/StatusBar in .Net 2.0.

JohnH

JohnH

VB.NET Forum Moderator


  • #3

The remaining project will not let me reference System.WindowsForms.

There are two versions of System.WindowsForms, I’ve been using 2.4 routinely (I hope that’s what I should be doing).

I tried them both in the troublesome procedure.

What happens is: I select Project/Add COM Reference and then check System.WindowsForms.

No, you shouldn’t. When <UseWindowsForms> is added to SDK project file the Microsoft.WindowsDesktop.App.WindowsForms framework dependency is added, this includes .Net 5 version of System.Windows.Forms.dll. Expand Dependencies in Solution Explorer and you’ll see it.

JohnH

JohnH

VB.NET Forum Moderator


  • #4

The Import Includes in project file is for importing namespaces (at project level) for existing referenced assemblies by the way.

  • #5

It should just be «Import System.Windows.Forms» less the quotation marks and remebering the «.» period(s).

jmcilhinney


  • #6

It should just be «Import System.Windows.Forms» less the quotation marks and remebering the «.» period(s).

Nope. That’s just importing a namespace at the file level. It’s only tangentially related to referencing an assembly.

  • #7

Nope. That’s just importing a namespace at the file level. It’s only tangentially related to referencing an assembly.

Ah well he/she did state in their first post that:

There are two versions of System.WindowsForms, I’ve been using 2.4 routinely (I hope that’s what I should be doing).

and I just seen they missed a period, so ty for correcting me :p.

ProtekNickz xD

  • #8

Microsoft.Common.CurrentVersion.targets(2701,5): warning MSB3290: Failed to create the wrapper assembly for type library «{215d64d2-031c-33c7-96e3-61794cd1ee61}». Type library ‘System_Windows_Forms’ was exported from a CLR assembly and cannot be re-imported as a CLR assembly.

No, you shouldn’t. When <UseWindowsForms> is added to SDK project file the Microsoft.WindowsDesktop.App.WindowsForms framework dependency is added, this includes .Net 5 version of System.Windows.Forms.dll. Expand Dependencies in Solution Explorer and you’ll see it.

Thanks for the above. I’m getting use to looking at the Dependencies!

If I understand what you told me I have duplicates WindowsForms entries in the code below.

I think this {215d64d2-031c-33c7-96e3-61794cd1ee61} related to windowsforms (where is there a list of such Guids?)

And I think it is there because I added the reference to remove an error message.

If I now remove it I get many WindowsForms error messages again.

Like: MessageBox is not declared.

I’d appreciate any suggestions related to fixing the below.

BTW. It works as is but I want to take you reply seriously.

I’m still working on the other’s replies!

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

  <PropertyGroup>
    <RootNamespace>Cag.TextEditor</RootNamespace>
      <TargetFramework>net5.0-windows</TargetFramework>
      <UseWindowsForms>true</UseWindowsForms>
      <MyType>WindowsForms</MyType>
  </PropertyGroup>

  <ItemGroup>
    <COMReference Include="{215d64d2-031c-33c7-96e3-61794cd1ee61}">
      <WrapperTool>tlbimp</WrapperTool>
      <VersionMinor>4</VersionMinor>
      <VersionMajor>2</VersionMajor>
      <Guid>215d64d2-031c-33c7-96e3-61794cd1ee61</Guid>
    </COMReference>
    <COMReference Include="tom.dll">
      <WrapperTool>tlbimp</WrapperTool>
      <VersionMinor>0</VersionMinor>
      <VersionMajor>1</VersionMajor>
      <Guid>8cc497c9-a1df-11ce-8098-00aa0047be5d</Guid>
      <Lcid>0</Lcid>
      <Isolated>false</Isolated>
    </COMReference>
    <COMReference Include="{bee4bfec-6683-3e67-9167-3c0cbc68f40a}">
      <WrapperTool>tlbimp</WrapperTool>
      <VersionMinor>4</VersionMinor>
      <VersionMajor>2</VersionMajor>
      <Guid>bee4bfec-6683-3e67-9167-3c0cbc68f40a</Guid>
    </COMReference>
  </ItemGroup>

  <ItemGroup>
    <ProjectReference Include="..BitmapEditorBitmapEditor.vbproj" />
    <ProjectReference Include="..ColorUtilitiesColorUtilities.vbproj" />
    <ProjectReference Include="..FractionUpDownFractionUpDown.vbproj" />
    <ProjectReference Include="..LibraryCs2LibraryCs2.csproj" />
    <ProjectReference Include="..LibraryDisk1LibraryDisk1.vbproj" />
    <ProjectReference Include="..LibraryGraphic2LibraryGraphic2.vbproj" />
    <ProjectReference Include="..LibraryNative0LibraryNative0.vbproj" />
    <ProjectReference Include="..LibraryPrinter1LibraryPrinter1.vbproj" />
    <ProjectReference Include="..LibraryTextEditor2LibraryTextEditor2.vbproj" />
    <ProjectReference Include="..LibraryVb0LibraryVb0.vbproj" />
    <ProjectReference Include="..LibraryVb1LibraryVb1.vbproj" />
    <ProjectReference Include="..LibraryVb3LibraryVb3.vbproj" />
    <ProjectReference Include="..UpDownsUpDowns.vbproj" />
  </ItemGroup>

</Project>

JohnH

JohnH

VB.NET Forum Moderator


  • #9

You’re missing the namespace imports at project level. (the Import Include)

In case you didn’t know, you add references to assemblies (dll libraries) which in this case is part of single huge dependency package so that they can be loaded when your app loads, and import namespaces in order to use classes within those libraries. One dll can have many classes/types organized into namespaces. Some namespaces are imported at project project level because they are used all over the place, for example the System.Windows.Forms namespace, others that you use more occationally in a single code file you import with the Imports statement at top of the code file.

  • #10

You’re missing the namespace imports at project level. (the Import Include)

1)Are you refering to
<OutputType>WinExe</OutputType>

What I should have included but didn’t is the fact that in the file that works under Dependencies / Frameworks there is
MicrosoftWindowsDesktop.App.WindoesForms and, in the project file I have 215d64d2-031c-33c7-96e3-61794cd1ee61

I think I shouldn’t need nor want two references to WindowsForms.

2)If I now remove {215d64d2-031c-33c7-96e3-61794cd1ee61} I get many WindowsForms error messages again.

Like: MessageBox is not declared.

I may have misinterpreted your earlier message but I thought MicrosoftWindowsDesktop.App.WindoesForms was what I needed.

JohnH

JohnH

VB.NET Forum Moderator


  • #11

No I said

Import Include

. As explained to be able to use a library it must be referenced that is that <UseWindowsForms> does, it add a bunch of libraries. Then you must import the namespaces, if not every type used in code must be qualified with the namespace, for example you can’t write MessageBox, it must be System.Windows.Forms.MessageBox. Obviously a form with lots of Forms types in generated code will not compile.
This is also explained in point 3 of VB extras in the migration guide that I posted before: Migrate a Windows Forms app to .NET 5 — Windows Forms .NET

Понравилась статья? Поделить с друзьями:
  • System sleep wake ошибка mac os
  • System sk carrier ошибка рефрижератора
  • System service exception ошибка вин 10
  • System server exception ошибка windows 10
  • System resuming samsung как исправить ошибку