- Как добавить форму в проект (Windows Forms .NET) How to add a form to a project (Windows Forms .NET)
- Добавление новой формы Add a new form
- Добавление ссылки на проект в форму Add a project reference to a form
- Open new forms in C++ Windows Forms Application
- 1 Answer 1
- c# open a new form then close the current form?
- 15 Answers 15
- Учебник. Создание нового приложения WinForms (Windows Forms .NET) Tutorial: Create a new WinForms app (Windows Forms .NET)
- Предварительные требования Prerequisites
- Создание приложения WinForms Create a WinForms app
- Важные элементы среды Visual Studio Important parts of Visual Studio
- Добавление элементов управления на форму Add controls to the form
- Обработка событий Handle events
- Запустите приложение Run the app
Как добавить форму в проект (Windows Forms .NET) How to add a form to a project (Windows Forms .NET)
Добавьте формы в свой проект с помощью Visual Studio. Add forms to your project with Visual Studio. Если в приложении несколько форм, вы сможете выбрать начальную форму для приложения или одновременно отобразить несколько форм. When your app has multiple forms, you can choose which is the startup form for your app, and you can display multiple forms at the same time.
Документация для Руководства по рабочему столу по .NET 5 (и .NET Core) находится в разработке. The Desktop Guide documentation for .NET 5 (and .NET Core) is under construction.
Добавление новой формы Add a new form
Добавьте новую форму в Visual Studio. Add a new form with Visual Studio.
В Visual Studio найдите панель Обозреватель проектов. In Visual Studio, find the Project Explorer pane. Щелкните проект правой кнопкой мыши и выберите Добавить > Форма (Windows Forms) . Right-click on the project and choose Add > Form (Windows Forms).
В поле Имя введите имя формы, например MyNewForm. In the Name box, type a name for your form, such as MyNewForm. Visual Studio сформирует имя по умолчанию, которое является уникальным. Можно использовать это имя. Visual Studio will provide a default and unique name that you may use.
После добавления формы Visual Studio откроет конструктор форм для этой формы. Once the form has been added, Visual Studio opens the form designer for the form.
Добавление ссылки на проект в форму Add a project reference to a form
Если у вас есть исходные файлы для формы, можно добавить форму в проект, скопировав файлы в папку проекта. If you have the source files to a form, you can add the form to your project by copying the files into the same folder as your project. Ссылки на все файлы кода в папке проекта и в дочерних папках проекта будут автоматически добавлены в проект. The project automatically references any code files that are in the same folder or child folder of your project.
Форма включает два файла с одинаковыми именами и разными расширениями: form2.cs (form2 — пример имени файла) и form2.Designer.cs. Forms are made up of two files that share the same name: form2.cs (form2 being an example of a file name) and form2.Designer.cs. Иногда присутствует файл ресурсов с тем же именем — form2.resx. Sometimes a resource file exists, sharing the same name, form2.resx. В предыдущем примере form2 представляет собой базовое имя файла. In in the previous example, form2 represents the base file name. Необходимо скопировать все связанные файлы в папку проекта. You’ll want to copy all related files to your project folder.
Кроме того, можно использовать Visual Studio для импорта файла в проект. Alternatively, you can use Visual Studio to import a file into your project. При добавлении существующего файла в проект файл копируется в папку проекта. When you add an existing file to your project, the file is copied into the same folder as your project.
В Visual Studio найдите панель Обозреватель проектов. In Visual Studio, find the Project Explorer pane. Щелкните проект правой кнопкой мыши и выберите Добавить > Существующий элемент. Right-click on the project and choose Add > Existing Item.
Перейдите в папку, содержащую файлы формы. Navigate to the folder containing your form files.
Open new forms in C++ Windows Forms Application
I’m using visual studio 2012 to work with windows form in C++. I’ve gotten help from this link Can’t find Windows Forms Application for C++
I want to have multiple forms. I’ve designed Form2 and included Form2.h into Form1.h . But when I open form2, it appears and fades immediately. This is my code:
the two forms will hide, and if I close form1
the form2 will close too.
I want to open and close forms independent. What must I do?
Any help would be appreciated
1 Answer 1
It is rather striking how removing the project template in VS2012 instantly made everybody write the wrong code. You are using «stack semantics», it is an emulation of the RAII pattern in C++. Or in other words, your Form2 instance gets immediately destroyed when your button_Click() returns. Proper code looks like:
The exact same bug is present in the code that creates the Form1 instance, visible from you having to pass %form1 . It is a bit less obvious because your Main() method keeps executing for the lifetime of the app. Nevertheless, the destructor of the Form1 class will be called twice. Tends to cause havoc when you alter the default one. Same recipe, don’t use stack semantics:
Your app terminates instantly when you call this->Close() because you are closing the main window of your app. Which happens because you passed the Form1 instance to Application::Run(). That’s compatible with the way the vast majority of Windows apps behave, closing the «main window» ends the application.
But that’s not what you want so don’t pass the form instance to Run(). You need another exit condition for your app, usually you’ll want a «when there are no more windows left» condition. Alter your Main() method to look like this:
void OnFormClosed(System::Object ^sender, System::Windows::Forms::FormClosedEventArgs ^e) < Form^ form = safe_cast
c# open a new form then close the current form?
For example, Assume that I’m in form 1 then I want:
- Open form 2( from a button in form 1)
- Close form 1
- Focus on form 2
15 Answers 15
Steve’s solution does not work. When calling this.Close(), current form is disposed together with form2. Therefore you need to hide it and set form2.Closed event to call this.Close().
Many different ways have already been described by the other answers. However, many of them either involved ShowDialog() or that form1 stay open but hidden. The best and most intuitive way in my opinion is to simply close form1 and then create form2 from an outside location (i.e. not from within either of those forms). In the case where form1 was created in Main , form2 can simply be created using Application.Run just like form1 before. Here’s an example scenario:
I need the user to enter their credentials in order for me to authenticate them somehow. Afterwards, if authentication was successful, I want to show the main application to the user. In order to accomplish this, I’m using two forms: LogingForm and MainForm . The LoginForm has a flag that determines whether authentication was successful or not. This flag is then used to decide whether to create the MainForm instance or not. Neither of these forms need to know about the other and both forms can be opened and closed gracefully. Here’s the code for this:
Учебник. Создание нового приложения WinForms (Windows Forms .NET) Tutorial: Create a new WinForms app (Windows Forms .NET)
Из этого краткого руководства вы узнаете, как создать новое приложение Windows Forms (WinForms) с помощью Visual Studio. In this short tutorial, you’ll learn how to create a new Windows Forms (WinForms) app with Visual Studio. После создания первоначального приложения вы научитесь добавлять элементы управления и обрабатывать события. Once the initial app has been generated, you’ll learn how to add controls and how to handle events. По завершении работы с этим руководством у вас будет простое приложение, добавляющее имена в список. By the end of this tutorial, you’ll have a simple app that adds names to a list box.
Документация для Руководства по рабочему столу по .NET 5 (и .NET Core) находится в разработке. The Desktop Guide documentation for .NET 5 (and .NET Core) is under construction.
В этом руководстве описано следующее: In this tutorial, you learn how to:
- Создание нового приложения WinForms Create a new WinForms app
- Добавление элементов управления на форму Add controls to a form
- Обработка событий элемента управления для предоставления функциональных возможностей приложения Handle control events to provide app functionality
- Запустите приложение Run the app
Предварительные требования Prerequisites
- Visual Studio 2019 версии 16.8 или более поздней Visual Studio 2019 version 16.8 or later versions
- Выберите рабочую нагрузку «Рабочий стол Visual Studio» Select the Visual Studio Desktop workload
- Выберите Отдельные компоненты .NET 5 Select the .NET 5 individual component
Создание приложения WinForms Create a WinForms app
Первым шагом в создании нового приложения является запуск Visual Studio и создание приложения на основе шаблона. The first step to creating a new app is opening Visual Studio and generating the app from a template.
Запустите Visual Studio. Open Visual Studio.
Выберите Создать новый проект. Select Create a new project.
В поле Поиск шаблонов введите winforms и нажмите клавишу ВВОД . In the Search for templates box, type winforms, and then press Enter .
В раскрывающемся списке язык кода выберите C# или Visual Basic. In the code language dropdown, choose C# or Visual Basic.
В списке шаблонов выберите Приложение Windows Forms (.NET) и затем щелкните Далее. In the templates list, select Windows Forms App (.NET) and then click Next.
Не выбирайте шаблон Приложение Windows Forms (.NET Framework) . Don’t select the Windows Forms App (.NET Framework) template.
В окне Настроить новый проект задайте в качестве имени проекта значение Names и щелкните Создать. In the Configure your new project window, set the Project name to Names and click Create.
Вы также можете сохранить проект в другую папку, изменив параметр Расположение. You can also save your project to a different folder by adjusting the Location setting.
После создания приложения Visual Studio должен открыть панель конструктора для формы по умолчанию Form1. Once the app is generated, Visual Studio should open the designer pane for the default form, Form1. Если конструктор форм не отображается, дважды щелкните форму в области Обозреватель решений, чтобы открыть окно конструктора. If the form designer isn’t visible, double-click on the form in the Solution Explorer pane to open the designer window.
Важные элементы среды Visual Studio Important parts of Visual Studio
Поддержка WinForms в Visual Studio состоит из четырех важных компонентов, с которыми вы будете взаимодействовать при создании приложения. Support for WinForms in Visual Studio has four important components that you’ll interact with as you create an app:
обозреватель решений Solution Explorer
Все файлы проекта, код, формы и ресурсы отображаются в этой области. All if your project files, code, forms, resources, will appear in this pane.
Properties (Свойства) Properties
На этой панели отображаются параметры свойств, которые можно настроить в зависимости от выбранного элемента. This pane shows property settings you can configure based on the item selected. Например, если выбрать элемент в Обозревателе решений, отобразятся параметры свойств, связанные с файлом. For example, if you select an item from Solution Explorer, you’ll see property settings related to the file. Если выбрать объект в конструкторе, отобразятся параметры элемента управления или формы. If you select an object in the Designer, you’ll see settings for the control or form.
Конструктор форм Form Designer
Это конструктор для формы. This is the designer for the form. Он является интерактивным, и на него можно перетаскивать объекты из панели элементов. It’s interactive and you can drag-and-drop objects from the Toolbox. Выбирая и перемещая элементы в конструкторе, можно визуально создавать пользовательский интерфейс для приложения. By selecting and moving items in the designer, you can visually compose the user interface (UI) for your app.
Панель элементов Toolbox
Панель элементов содержит все элементы управления, которые можно добавить на форму. The toolbox contains all of the controls you can add to a form. Чтобы добавить элемент управления на текущую форму, дважды щелкните элемент управления или перетащите его. To add a control to the current form, double-click a control or drag-and-drop the control.
Добавление элементов управления на форму Add controls to the form
Открыв конструктор форм Form1, используйте панель Область элементов, чтобы добавить на форму следующие элементы управления: With the Form1 form designer open, use the Toolbox pane to add the following controls to the form:
- Метка Label
- Кнопка Button
- Listbox Listbox
- Текстовое поле Textbox
Вы можете расположить и изменить размер элементов управления в соответствии со следующими настройками. You can position and size the controls according to the following settings. Либо визуально перенесите их, чтобы они соответствовали следующему снимку экрана, либо щелкните каждый элемент управления и настройте параметры в области Свойства. Either visually move them to match the screenshot that follows, or click on each control and configure the settings in the Properties pane. Можно также щелкнуть область заголовка формы, чтобы выбрать форму. You can also click on the form title area to select the form:
Объект Object | Параметр Setting | Значение Value |
---|---|---|
Form Form | Текст Text | Names |
Размер Size | 268, 180 | |
Label Label | Расположение Location | 12, 9 |
Текст Text | Names | |
Listbox Listbox | Имя Name | lstNames |
Расположение Location | 12, 27 | |
Размер Size | 120, 94 | |
текстовое поле; Textbox | Имя Name | txtName |
Расположение Location | 138, 26 | |
Размер Size | 100, 23 | |
Button Button | Имя Name | btnAdd |
Расположение Location | 138, 55 | |
Размер Size | 100, 23 | |
Текст Text | Add Name |
Вы должны получить в конструкторе форму, которая выглядит следующим образом. You should have a form in the designer that looks similar to the following:
Обработка событий Handle events
Теперь, когда в форме есть все элементы управления, необходимо обрабатывать события элементов управления, чтобы реагировать на вводимые пользователем данные. Now that the form has all of its controls laid out, you need to handle the events of the controls to respond to user input. Открыв конструктор форм, выполните следующие действия. With the form designer still open, perform the following steps:
Выберите в форме элемент управления «Кнопка». Select the button control on the form.
В области Свойства щелкните значок события , чтобы вывести список событий кнопки.
Найдите событие Click и дважды щелкните его, чтобы создать обработчик событий. Find the Click event and double-click it to generate an event handler.
Это действие добавляет следующий код в форму: This action adds the following code to the the form:
Код, помещаемый в этот обработчик, будет добавлять имя, заданное элементом управления TextBox txtName , в элемент управления ListBox lstNames . The code we’ll put in this handler will add the name specified by the txtName textbox control to the lstNames listbox control. Однако мы хотим, чтобы имя удовлетворяло двум условиям: указанное имя не должно быть пустым, и его еще не должно быть в списке. However, we want there to be two conditions to adding the name: the name provided must not be blank, and the name must not already exist.
В следующем примере кода показано добавление имени в элемент управления lstNames . The following code demonstrates adding a name to the lstNames control:
Запустите приложение Run the app
Теперь, когда у нас есть код события, можно запустить приложение, нажав клавишу F5 или выбрав пункт меню Отладка > Начать отладку. Now that the event has been coded, you can run the app by pressing the F5 key or by selecting Debug > Start Debugging from the menu. Отобразится форма, и вы можете ввести имя в текстовое поле, а затем добавить его, нажав кнопку. The form displays and you can enter a name in the textbox and then add it by clicking the button.