Как добавить using 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 Files\Microsoft Visual Studio\2022\Community\dotnet\runtime\shared\Microsoft.WindowsDesktop.App\6.0.14\System.Windows.Forms.dll

║XLR8║

1212 / 909 / 270

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

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

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

1

20.02.2010, 11:39. Показов 36716. Ответов 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



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….)

It looks like you are trying to use the Forms namespace from the System.Windows namespace in your visual-studio-2019 project, but you are getting an error message saying that it does not exist in the namespace.

One possibility is that you are missing a reference to the System.Windows.Forms assembly in your project. To add this reference, you can try the following steps:

  1. Right-click on your project in the Solution Explorer window and select “Add Reference” from the context menu.
  2. In the “Reference Manager” window that appears, select the “Assemblies” tab.

  3. Search for “System.Windows.Forms” in the search box or browse through the list of available assemblies until you find it.

  4. Check the box next to “System.Windows.Forms” to select it, and then click the “Add” button at the bottom of the window.

  5. Once the reference has been added, try rebuilding your project and see if the error message disappears.

If the “References” tab still does not appear in the Solution Explorer window, you may need to customize your view settings. You can do this by clicking the “Options” button at the top of the Solution Explorer window and selecting “Show all files”.

Alternatively, you can try adding the reference manually by editing your project file (*.csproj) in a text editor. Look for the <Reference> element and add the following line inside it:

<HintPath>path\to\System.Windows.Forms.dll</HintPath>

Replace “path\to” with the actual file path where the System.Windows.Forms.dll assembly is located on your system.

Hopefully, one of these steps will help you resolve the issue and get “using System.Windows.Forms” to work in your project.

  • Как добавить unlocker в контекстное меню windows 10
  • Как добавить ubuntu в домен windows
  • Как добавить torrent в исключения брандмауэра windows 10
  • Как добавить throttlestop в автозагрузку на windows 10
  • Как добавить telnet windows 10