Не удается добавить ссылку на 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….)

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 Files\Microsoft Visual Studio\2022\Community\dotnet\runtime\shared\Microsoft.WindowsDesktop.App\6.0.14\System.Windows.Forms.dll

I’m using C# to command something in Excel but when I type

using System.Windows.Forms

it’s not recognized by Visual Studio
When I added the reference, I have this error message

A reference to ‘System_Windows_Forms’ could not be added.
The ActiveX type library ‘…’ was exported from a .NET assembly and cannot be added as a reference.
Add a reference to the .NET assembly instead

Do you have any solutions?

  • c#
  • winforms

asked May 2, 2011 at 14:26

nam's user avatar

namnam

3,5529 gold badges46 silver badges68 bronze badges

1

  • You should not be typing this by hand usually, if your project is a winforms project then the correct references are added by default in Visual Studio.

    May 2, 2011 at 16:00

2 Answers

Did you try to add it from the COM-tab? Find the System.Windows.Forms.dll in the .NET-tab instead! (Sorting the dll-s by name makes it so much easier to find the right one.)

answered May 3, 2011 at 0:49

simaglei's user avatar

simagleisimaglei

1,1281 gold badge14 silver badges14 bronze badges

0

Reference Manager>Assemblies>Framework
enter image description here

Peter Csala's user avatar

Peter Csala

18.3k16 gold badges35 silver badges77 bronze badges

answered Dec 8, 2021 at 18:24

MrShprotter's user avatar

2

  • Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

    Dec 8, 2021 at 19:01

  • Where is the «Reference Manager»?

    Jul 18 at 13:38

║XLR8║

1212 / 909 / 270

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

Сообщений: 4,361

Записей в блоге: 5

1

20.02.2010, 11:39. Показов 36725. Ответов 23


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

У меня Microsoft Visual C# 2008 Express Edition, создал пустой проект и теперь немогу подключить пространство имен System.Windiws.Forms , можете подсказать как это сделать? (просьба не предлагать создать Windows Forms Appication)



0



1319 / 992 / 127

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

Сообщений: 1,299

20.02.2010, 11:50

2

надо добавить ссылку на этот модуль у самого проекта. обозреватель решений — проект — ссылки — добавить — .NET — System.Windiws.Forms



2



CEO

Эксперт С++

2258 / 1248 / 57

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

Сообщений: 3,588

20.02.2010, 11:51

3

в файле Program.cs: using System.Windows.Forms
правой кнопкой на элементе «Ссылки» в Окне експлорера проекта -> Добавить -> Закладка .NET -> ищем System.Windows.Forms -> Добавляем



1



kirill29

2095 / 1260 / 171

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

Сообщений: 2,842

20.02.2010, 11:56

4

Solution Explorer, правой кнопкой мыши на References, выбираем Add References, далее на вкладке NET
находим System.Windows.Forms.
Далее подключаем пространоство имен using System.Windows.Forms;

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
using System;
using System.Windows.Forms;
 
namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            MessageBox.Show("Тест");
        }
    }
}



0



outoftime

║XLR8║

1212 / 909 / 270

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

Сообщений: 4,361

Записей в блоге: 5

20.02.2010, 12:05

 [ТС]

5

Спасибо всем. А не подскажите как убрать «черный екран смерти» что-бы видно было только формы при запуске, а то я по книге не совсем догнал..

Добавлено через 2 минуты
kirill29, а как сделать следующе на си шарп:

C++
1
2
3
stack <int> S;
S.push(1); S.push(2); S.push(3);
cout << S.pop() << S.pop() << S.pop() << endl;



0



kirill29

2095 / 1260 / 171

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

Сообщений: 2,842

20.02.2010, 12:26

6

outoftime, как-то так:

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
using System;
using System.Collections;
 
namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            Stack stack = new Stack();
            stack.Push(1);
            stack.Push(2);
            stack.Push(3);
            Console.Write(stack.Pop().ToString() + stack.Pop().ToString() + stack.Pop().ToString());
            Console.ReadKey();
        }
    }
}



0



Alligieri

CEO

Эксперт С++

2258 / 1248 / 57

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

Сообщений: 3,588

20.02.2010, 12:29

7

kirill29, забыл

C#
1
Console.Write("\n");



0



Beralus

26 / 26 / 5

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

Сообщений: 84

20.02.2010, 12:30

8

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

Спасибо всем. А не подскажите как убрать «черный екран смерти» что-бы видно было только формы при запуске, а то я по книге не совсем догнал..

Добавлено через 2 минуты
kirill29, а как сделать следующе на си шарп:

C++
1
2
3
stack <int> S;
S.push(1); S.push(2); S.push(3);
cout << S.pop() << S.pop() << S.pop() << endl;

1);
System.Windows.Forms.Application.Run(new Form1());

2)
System.Collections.Stack stack;
stack=new System.Collections.Stack()
//stack.Peek
//stack.Push
//stack.Pop
System.Console.Write(«10 konstruktorov»);



0



1319 / 992 / 127

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

Сообщений: 1,299

20.02.2010, 12:37

9

)))))) консоль и KSoD (черный экран смерти) — АбсолютнО разные вещи. чтобы убрать консоль надо в свойствах проекта (на первой вкладке — «приложение» («application»)) вместо «консольного приложения» — «приложение windows forms»



0



║XLR8║

1212 / 909 / 270

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

Сообщений: 4,361

Записей в блоге: 5

20.02.2010, 13:02

 [ТС]

10

Спасибо, с этим разобрался. Но у меня есть еще вопросы:
есть ли в си шарпе вектора как в си++, или хотябы заменители..

Добавлено через 5 минут
как узнать длину строки? Допустим есть строка String s = «dfsdfsdf»; как узнать ее длину? и как обратиться к и-ому символу этой строки?



0



4336 / 1505 / 101

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

Сообщений: 2,342

20.02.2010, 13:13

11

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

как узнать длину строки?

s.Length

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

и как обратиться к и-ому символу этой строки

s[и], доступен только для чтения

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

есть ли в си шарпе вектора как в си++, или хотябы заменители

List<>

Добавлено через 1 минуту

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

Stack stack = new Stack();

Stack<int> stack = new Stack<int>();



0



outoftime

║XLR8║

1212 / 909 / 270

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

Сообщений: 4,361

Записей в блоге: 5

20.02.2010, 13:38

 [ТС]

12

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

Stack<int> stack = new Stack<int>();

мне больше понравился стек произвольных пипов))

Добавлено через 1 минуту
List<> — а где он должен быть (пространство имен)

Добавлено через 6 минут
как переписать этот клас, что-бы он работал?

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
    class functions
    {
        int kmp(string t, string s)
        {
            string sn = t + "$" + s;
            int n = sn.Length,
                nt = t.Length;
            List<int> pi = new List(0);
            for (int i = 0; i < n; ++i)
            {
                int k = pi[i - 1];
                while (sn[k] != sn[i]) k = pi[k - 1];
                if (sn[k] == sn[i]) ++k;
                pi[i] = k;
                if (k == nt) return i - 2 * nt - 1;
            }    
            return -1;
        }
    }



0



HIMen

4336 / 1505 / 101

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

Сообщений: 2,342

20.02.2010, 13:40

13

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

мне больше понравился стек произвольных типов))

Создай тот и другой на 1000000 элементов и сравни производительность.

Добавлено через 39 секунд

C#
1
List<int> pi = new List<int>();



0



║XLR8║

1212 / 909 / 270

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

Сообщений: 4,361

Записей в блоге: 5

20.02.2010, 13:42

 [ТС]

14

Error 1 The type or namespace name ‘List’ could not be found (are you missing a using directive or an assembly reference?) C:\Documents and Settings\Администратор\Мои документы\Visual Studio 2008\Projects\Project1\Project1\CodeFile1.cs 14 13 Project1

Добавлено через 21 секунду
HIMen, где он должен быть? я его у себя не нашел..



0



4336 / 1505 / 101

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

Сообщений: 2,342

20.02.2010, 13:43

15

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

List<> — а где он должен быть (пространство имен)

System.Collections.Generic;



0



outoftime

║XLR8║

1212 / 909 / 270

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

Сообщений: 4,361

Записей в блоге: 5

20.02.2010, 14:05

 [ТС]

16

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
    class functions
    {
        public int kmp(string t, string s)
        {
            string sn = t + "$" + s;
            int n = sn.Length,
                nt = t.Length;
            /*int[] pi = new int[n];
            for (int i = 0; i < n; ++i) pi[i] = 0;*/
            List<int> pi = new List<int>(n);
            for (int i = 0; i < n; ++i) pi[i] = 0;
 
                for (int i = 1; i < n; ++i)
                {
                    int k = pi[i - 1];
                    while (sn[k] != sn[i] && k > 0) k = pi[k - 1];
                    if (sn[k] == sn[i]) ++k;
                    pi[i] = k;
                    if (k == nt) return i - 2 * nt;
                }    
 
            return -1;
        }
    }

не подскажите в чем проблема, когда у меня стоит масив все нормально, как только я меняю его на лист, сразу ошибка.



0



CEO

Эксперт С++

2258 / 1248 / 57

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

Сообщений: 3,588

20.02.2010, 14:14

17

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

for (int i = 0; i < n; ++i) pi[i] = 0;
for (int i = 1; i < n; ++i)
* * * * * * * * {
* * * * * * * * * * int k = pi[i — 1];
* * * * * * * * * * while (sn[k] != sn[i] && k > 0) k = pi[k — 1];
* * * * * * * * * * if (sn[k] == sn[i]) ++k;
* * * * * * * * * * pi[i] = k;
* * * * * * * * * * if (k == nt) return i — 2 * nt;
* * * * * * * * } * *
return -1;
* * * * }

После изначальной инициализации в List нет елементов, добавте их туда методом List.Add()



0



outoftime

║XLR8║

1212 / 909 / 270

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

Сообщений: 4,361

Записей в блоге: 5

20.02.2010, 14:53

 [ТС]

18

Alligieri, а можно как-то создать лист с Н элементами, значение которых К ?? Не прогоняя лист в цыкле

Добавлено через 18 минут

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
namespace Application
{
    using System;
    using System.Collections;
    using System.Collections.Generic; 
    using System.Windows.Forms;
 
    class functions
    {
        public string s, t;
 
        public void Read()
        {
            Console.Write("Введіть шукану стрічку: ");
            t = Console.ReadLine().ToString();
            Console.Write("Введіть текст: ");
            s = Console.ReadLine().ToString();
        }
 
        public int kmp(string t, string s)
        {
            string sn = t + "$" + s;
            int n = sn.Length,
                nt = t.Length;
            List<int> pi = new List<int>();
            for (int i = 0; i < n; ++i) pi.Add(0);
 
            for (int i = 1; i < n; ++i)
            {
                int k = pi[i - 1];
                while (sn[k] != sn[i] && k > 0) k = pi[k - 1];
                if (sn[k] == sn[i]) ++k;
                pi[i] = k;
                if (k == nt) return i - 2 * nt;
            }
 
            return -1;
        }
    }
 
    class mesege
    {
        public static void Main()
        {
            functions F = new functions();
            F.Read();
            int d = F.kmp(F.t, F.s);
            if (d == -1) MessageBox.Show("Стрічка " + F.t + " не зустрічається в срічці " + F.s);
            else MessageBox.Show("Стрічка " + F.t + " входить в стрічку " + F.s + " з " + d.ToString() + "-ої позиції" );
        }
    }
}

можете помочь написать ввод не в консоли а заполняя форму?



0



124 / 106 / 7

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

Сообщений: 263

20.02.2010, 16:08

19

……



0



CEO

Эксперт С++

2258 / 1248 / 57

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

Сообщений: 3,588

20.02.2010, 16:57

20

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

for (int i = 0; i < n; ++i) pi.Add(0);
for (int i = 1; i < n; ++i)
* * * * * * {
* * * * * * * * int k = pi[i — 1]; //как мне кажется k=0 всегда
* * * * * * * * while (sn[k] != sn[i] && k > 0) k = pi[k — 1]; //тут вообще никогда не выполнится
* * * * * * * * if (sn[k] == sn[i]) ++k;
* * * * * * * * pi[i] = k;
* * * * * * * * if (k == nt) return i — 2 * nt;
* * * * * * }
return -1;

Что вы пытаетесь cделать?



0



  • Не удается добавить bluetooth устройство windows 10
  • Не удается активировать windows на этом устройстве так как у вас не действительной цифровой лицензии
  • Не удается вычислить индекс производительности windows 7 для этой системы
  • Не удается активировать windows на этом устройстве 0x8007232b
  • Не убирается экран блокировки windows 10