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
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
Вам нужно добавить ссылку на зависимость в свойствах проекта в обозревателе решений. Конечно, если проект не выполняется на .NET Core, в таком случае вам нужно подключить соответсвующее расширение с помощбю менеджера пакетов Nuget для проекта
When developing C# applications that involve GUI components, you may encounter the error message «System.Windows.Forms not found.» This issue usually occurs when the required assembly reference for Windows Forms is missing or improperly configured in your project. Here are some steps to troubleshoot and resolve this common problem:
1. Check Project References
Ensure that your C# project includes a reference to the ‘System.Windows.Forms’ assembly. To add the reference, right-click on the ‘References’ node in your project, select ‘Add Reference,’ and then search for ‘System.Windows.Forms’ in the list of available assemblies.
using System.Windows.Forms;
2. Verify Target Framework
Make sure that your project’s target framework supports Windows Forms. Check the project properties and ensure that the target framework is compatible with Windows Forms.
3. Reinstall .NET Framework
If the ‘System.Windows.Forms’ assembly is still not found, try reinstalling the .NET Framework on your system. This may help in resolving any underlying issues related to missing assemblies.
4. Clean and Rebuild
Sometimes, the error can be due to a build issue. Try cleaning your project and then rebuilding it to see if the problem persists.
5. Update Visual Studio
Ensure that you are using an up-to-date version of Visual Studio with all the necessary components installed. Updating Visual Studio may resolve compatibility issues causing the ‘System.Windows.Forms’ not found error.
By following these troubleshooting steps, you should be able to resolve the ‘System.Windows.Forms’ not found issue in your C# application and continue developing your Windows Forms-based projects seamlessly.
Чем асинхронная логика (схемотехника) лучше тактируемой, как я думаю, что помимо энергоэффективности — ещё и безопасность.
Hrethgir 14.05.2025
Помимо огромного плюса в энергоэффективности, асинхронная логика — тотальный контроль над каждым совершённым тактом, а значит — безусловная безопасность, где безконтрольно не совершится ни одного. . .
Многопоточные приложения на C++
bytestream 14.05.2025
C++ всегда был языком, тесно работающим с железом, и потому особеннно эффективным для многопоточного программирования. Стандарт C++11 произвёл революцию, добавив в язык нативную поддержку потоков,. . .
Stack, Queue и Hashtable в C#
UnmanagedCoder 14.05.2025
Каждый опытный разработчик наверняка сталкивался с ситуацией, когда невинный на первый взгляд List<T> превращался в узкое горлышко всего приложения. Причина проста: универсальность – это прекрасно,. . .
Как использовать OAuth2 со Spring Security в Java
Javaican 14.05.2025
Протокол OAuth2 часто путают с механизмами аутентификации, хотя по сути это протокол авторизации. Представьте, что вместо передачи ключей от всего дома вашему другу, который пришёл полить цветы, вы. . .
Анализ текста на Python с NLTK и Spacy
AI_Generated 14.05.2025
NLTK, старожил в мире обработки естественного языка на Python, содержит богатейшую коллекцию алгоритмов и готовых моделей. Эта библиотека отлично подходит для образовательных целей и. . .
Реализация DI в PHP
Jason-Webb 13.05.2025
Когда я начинал писать свой первый крупный PHP-проект, моя архитектура напоминала запутаный клубок спагетти. Классы создавали другие классы внутри себя, зависимости жостко прописывались в коде, а о. . .
Обработка изображений в реальном времени на C# с OpenCV
stackOverflow 13.05.2025
Объединение библиотеки компьютерного зрения OpenCV с современным языком программирования C# создаёт симбиоз, который открывает доступ к впечатляющему набору возможностей. Ключевое преимущество этого. . .
POCO, ACE, Loki и другие продвинутые C++ библиотеки
NullReferenced 13.05.2025
В C++ разработки существует такое обилие библиотек, что порой кажется, будто ты заблудился в дремучем лесу. И среди этого многообразия POCO (Portable Components) – как маяк для тех, кто ищет. . .
Паттерны проектирования GoF на C#
UnmanagedCoder 13.05.2025
Вы наверняка сталкивались с ситуациями, когда код разрастается до неприличных размеров, а его поддержка становится настоящим испытанием. Именно в такие моменты на помощь приходят паттерны Gang of. . .
Создаем CLI приложение на Python с Prompt Toolkit
py-thonny 13.05.2025
Современные командные интерфейсы давно перестали быть черно-белыми текстовыми программами, которые многие помнят по старым операционным системам. CLI сегодня – это мощные, интуитивные и даже. . .
Introduction
As a beginner in C#, creating a project with WPF can be an exciting experience. However, you may encounter issues that can hinder your progress. One such issue is when your project can’t find the System.Windows.Forms
namespace even after adding the necessary references. In this article, we will explore the possible causes of this issue and provide solutions to help you resolve it.
Understanding the Issue
When you try to use classes from the System.Windows.Forms
namespace in your WPF project, you may encounter a compilation error. This error occurs because the System.Windows.Forms
namespace is not available by default in WPF projects. To use classes from this namespace, you need to add a reference to the System.Windows.Forms
assembly.
Adding References
To add a reference to the System.Windows.Forms
assembly, follow these steps:
- Open your project in Visual Studio: Open your C# project in Visual Studio.
- Right-click on your project: Right-click on your project in the Solution Explorer and select Add > Reference.
- Browse for the assembly: In the Reference Manager, browse for the
System.Windows.Forms
assembly. - Select the assembly: Select the
System.Windows.Forms
assembly and click OK.
Why Can’t I Find System.Windows.Forms?
Even after adding the reference, you may still encounter issues finding the System.Windows.Forms
namespace. There are several reasons for this:
- Incorrect namespace: Make sure you are using the correct namespace. The
System.Windows.Forms
namespace is used for Windows Forms applications, not WPF applications. - Missing using directive: Ensure that you have included the
using
directive for theSystem.Windows.Forms
namespace at the top of your code file. - Conflicting references: If you have multiple references to the
System.Windows.Forms
assembly, it may cause conflicts. Try removing unnecessary references.
Using FolderBrowserDialog
The FolderBrowserDialog
class is a part of the System.Windows.Forms
namespace. To use this class in your WPF project, you need to add a reference to the System.Windows.Forms
assembly, as described earlier. Here’s an example of how to use the FolderBrowserDialog
class:
using System.Windows.Forms;
// Create a new instance of the FolderBrowserDialog FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();
// Show the dialog and get the selected folder if (folderBrowserDialog.ShowDialog() == DialogResult.OK) { string selectedFolder = folderBrowserDialog.SelectedPath; // Use the selected folder }
Using DialogResult
The DialogResult
class is also part of the System.Windows.Forms
namespace. To use this class in your WPF project, you need to add a reference to the System.Windows.Forms
assembly, as described earlier. Here’s an example of how to use the DialogResult
class:
using System.Windows.Forms;
// Create a new instance of the DialogResult DialogResult dialogResult = new DialogResult();
// Show the dialog and get the result if (dialogResult ==.OK) { // Use the result }
Conclusion
In conclusion, the System.Windows.Forms
namespace is not available by default in WPF projects. To use classes from this namespace, you need to add a reference to the System.Windows.Forms
assembly. By following the steps outlined in this article, you should be able to resolve the issue of your project not finding the System.Windows.Forms
namespace even with references.
Troubleshooting Tips
- Check the namespace: Ensure that you are using the correct namespace.
- Check the using directive: Ensure that you have included the
using
directive for theSystem.Windows.Forms
namespace. - Check for conflicting references: If you have multiple references to the
System.Windows.Forms
assembly, it may cause conflicts. - Check the project type: Ensure that your project is set to use the correct project type (e.g., WPF).
Additional Resources
- Microsoft Documentation: System.Windows.Forms Namespace
- Stack Overflow: C# project can’t find System.Windows.Forms even with references
Related Articles
- WPF vs Windows Forms: WPF vs Windows Forms: Which One to Choose?
- C# Project Setup: Setting Up a C# Project in Visual Studio
C# Project Can’t Find System.Windows.Forms Even with References: Q&A
====================================================================
Q: What is the System.Windows.Forms namespace?
A: The System.Windows.Forms
namespace is a part of the .NET Framework that provides a set of classes for building Windows Forms applications. It includes classes for creating forms, controls, and other UI elements.
Q: Why can’t I find System.Windows.Forms in my WPF project?
A: The System.Windows.Forms
namespace is not available by default in WPF projects. To use classes from this namespace, you need to add a reference to the System.Windows.Forms
assembly.
Q: How do I add a reference to System.Windows.Forms?
A: To add a reference to the System.Windows.Forms
assembly, follow these steps:
- Open your project in Visual Studio.
- Right-click on your project in the Solution Explorer and select Add > Reference.
- Browse for the
System.Windows.Forms
assembly. - Select the
System.Windows.Forms
assembly and click OK.
Q: Why do I need to add a reference to System.Windows.Forms?
A: You need to add a reference to the System.Windows.Forms
assembly because WPF projects do not include the System.Windows.Forms
namespace by default. By adding a reference to the assembly, you can use classes from the System.Windows.Forms
namespace in your WPF project.
Q: Can I use System.Windows.Forms in a WPF project?
A: Yes, you can use classes from the System.Windows.Forms
namespace in a WPF project. However, you need to add a reference to the System.Windows.Forms
assembly and use the classes in a way that is compatible with WPF.
Q: What are some common classes in System.Windows.Forms?
A: Some common classes in the System.Windows.Forms
namespace include:
Form
: Represents a Windows Forms application.Control
: Represents a control in a Windows Forms application.Button
: Represents a button control in a Windows Forms application.TextBox
: Represents a text box control in a Windows Forms application.FolderBrowserDialog
: Represents a dialog box for browsing folders.DialogResult
: Represents the result of a dialog box.
Q: How do I use FolderBrowserDialog in a WPF project?
A: To use the FolderBrowserDialog
class in a WPF project, you need to add a reference to the System.Windows.Forms
assembly and use the class in a way that is compatible with WPF. Here’s an example of how to use the FolderBrowserDialog
class:
using System.Windows.Forms;
// Create a new instance of the FolderBrowserDialog FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();
// Show the dialog and get the selected folder if (folderBrowserDialog.ShowDialog() == DialogResult.OK) { string selectedFolder = folderBrowserDialog.SelectedPath; // Use the selected folder }
Q: How do I use DialogResult in a WPF project?
A: To use the DialogResult
class in a WPF project, you to add a reference to the System.Windows.Forms
assembly and use the class in a way that is compatible with WPF. Here’s an example of how to use the DialogResult
class:
using System.Windows.Forms;
// Create a new instance of the DialogResult DialogResult dialogResult = new DialogResult();
// Show the dialog and get the result if (dialogResult == DialogResult.OK) { // Use the result }
Q: What are some common issues when using System.Windows.Forms in a WPF project?
A: Some common issues when using the System.Windows.Forms
namespace in a WPF project include:
- Conflicting references: If you have multiple references to the
System.Windows.Forms
assembly, it may cause conflicts. - Incorrect namespace: Make sure you are using the correct namespace.
- Missing using directive: Ensure that you have included the
using
directive for theSystem.Windows.Forms
namespace. - Incompatible classes: Some classes in the
System.Windows.Forms
namespace may not be compatible with WPF.
Q: How do I troubleshoot issues when using System.Windows.Forms in a WPF project?
A: To troubleshoot issues when using the System.Windows.Forms
namespace in a WPF project, follow these steps:
- Check the namespace: Ensure that you are using the correct namespace.
- Check the using directive: Ensure that you have included the
using
directive for theSystem.Windows.Forms
namespace. - Check for conflicting references: If you have multiple references to the
System.Windows.Forms
assembly, it may cause conflicts. - Check the project type: Ensure that your project is set to use the correct project type (e.g., WPF).
Q: Where can I find more information about System.Windows.Forms?
A: You can find more information about the System.Windows.Forms
namespace in the following resources:
- Microsoft Documentation: System.Windows.Forms Namespace
- Stack Overflow: C# project can’t find System.Windows.Forms even with references
- CodeProject: WPF vs Windows Forms: Which One to Choose?
Я попробовал создать (свою первую) программу на C#:
Код: Выделить всё
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:\Users\Ramy\Documents\Visual Studio 2010\Projects\ConsoleApplication1\ConsoleApplication1\Program.cs 5 14 ConsoleApplication1
Некоторые подробности:
— Я использую Visual Studio 2012;
— Я установил .NET Development Kit;
— Он это консольное приложение.
Может быть, это потому, что в консольном приложении нельзя использовать System.Windows.Forms?
Если да, то какая программа должна быть? Я также пробовал использовать форму, но у меня отображалось только окно, а не код.
Подробнее здесь: https://stackoverflow.com/questions/964 … dows-forms