Windows forms app net framework visual studio

Как добавить форму в проект (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.

Create a Windows Forms app in Visual Studio with Visual Basic

In this short introduction to the Visual Studio integrated development environment (IDE), you’ll create a simple Visual Basic application that has a Windows-based user interface (UI).

If you haven’t already installed Visual Studio, go to the Visual Studio downloads page to install it for free.

If you haven’t already installed Visual Studio, go to the Visual Studio downloads page to install it for free.

Some of the screenshots in this tutorial use the dark theme. If you aren’t using the dark theme but would like to, see the Personalize the Visual Studio IDE and Editor page to learn how.

Читайте также:  Lenovo или windows phone

Create a project

First, you’ll create a Visual Basic application project. The project type comes with all the template files you’ll need, before you’ve even added anything.

Open Visual Studio 2017.

From the top menu bar, choose File > New > Project.

In the New Project dialog box in the left pane, expand Visual Basic, and then choose Windows Desktop. In the middle pane, choose Windows Forms App (.NET Framework). Then name the file HelloWorld .

If you don’t see the Windows Forms App (.NET Framework) project template, cancel out of the New Project dialog box and from the top menu bar, choose Tools > Get Tools and Features. The Visual Studio Installer launches. Choose the .NET desktop development workload, then choose Modify.

Open Visual Studio 2019.

On the start window, choose Create a new project.

On the Create a new project window, choose the Windows Forms App (.NET Framework) template for Visual Basic.

(If you prefer, you can refine your search to quickly get to the template you want. For example, enter or type Windows Forms App in the search box. Next, choose Visual Basic from the Language list, and then choose Windows from the Platform list.)

If you do not see the Windows Forms App (.NET Framework) template, you can install it from the Create a new project window. In the Not finding what you’re looking for? message, choose the Install more tools and features link.

Next, in the Visual Studio Installer, choose the Choose the .NET desktop development workload.

After that, choose the Modify button in the Visual Studio Installer. You might be prompted to save your work; if so, do so. Next, choose Continue to install the workload. Then, return to step 2 in this «Create a project» procedure.

In the Configure your new project window, type or enter HelloWorld in the Project name box. Then, choose Create.

Visual Studio opens your new project.

Create the application

After you select your Visual Basic project template and name your file, Visual Studio opens a form for you. A form is a Windows user interface. We’ll create a «Hello World» application by adding controls to the form, and then we’ll run the app.

Add a button to the form

Click Toolbox to open the Toolbox fly-out window.

(If you don’t see the Toolbox fly-out option, you can open it from the menu bar. To do so, View > Toolbox. Or, press Ctrl+Alt+X.)

Click the Pin icon to dock the Toolbox window.

Click the Button control and then drag it onto the form.

In the Appearance section (or the Fonts section) of the Properties window, type Click this , and then press Enter.

(If you don’t see the Properties window, you can open it from the menu bar. To do so, click View > Properties Window. Or, press F4.)

In the Design section of the Properties window, change the name from Button1 to btnClickThis , and then press Enter.

If you’ve alphabetized the list in the Properties window, Button1 appears in the (DataBindings) section, instead.

Add a label to the form

Now that we’ve added a button control to create an action, let’s add a label control to send text to.

Select the Label control from the Toolbox window, and then drag it onto the form and drop it beneath the Click this button.

In either the Design section or the (DataBindings) section of the Properties window, change the name of Label1 to lblHelloWorld , and then press Enter.

Add code to the form

In the Form1.vb [Design] window, double-click the Click this button to open the Form1.vb window.

(Alternatively, you can expand Form1.vb in Solution Explorer, and then click Form1.)

In the Form1.vb window, between the Private Sub and End Sub lines, type or enter lblHelloWorld.Text = «Hello World!» as shown in the following screenshot:

Run the application

Click the Start button to run the application.

Several things will happen. In the Visual Studio IDE, the Diagnostics Tools window will open, and an Output window will open, too. But outside of the IDE, a Form1 dialog box appears. It will include your Click this button and text that says Label1.

Click the Click this button in the Form1 dialog box. Notice that the Label1 text changes to Hello World!.

Close the Form1 dialog box to stop running the app.

Next steps

To learn more, continue with the following tutorial:

Создание приложения Windows Forms на Visual Basic в Visual Studio Create a Windows Forms app in Visual Studio with Visual Basic

В рамках этого краткого знакомства с возможностями интегрированной среды разработки Visual Studio (IDE) вы создадите простое приложение на Visual Basic с пользовательским интерфейсом на основе Windows. In this short introduction to the Visual Studio integrated development environment (IDE), you’ll create a simple Visual Basic application that has a Windows-based user interface (UI).

Читайте также:  One password mac and windows

Установите Visual Studio бесплатно со страницы скачиваемых материалов Visual Studio, если еще не сделали этого. If you haven’t already installed Visual Studio, go to the Visual Studio downloads page to install it for free.

Установите Visual Studio бесплатно со страницы скачиваемых материалов Visual Studio, если еще не сделали этого. If you haven’t already installed Visual Studio, go to the Visual Studio downloads page to install it for free.

На некоторых снимках экрана в этом учебнике используется темная тема. Some of the screenshots in this tutorial use the dark theme. Если вы не используете темную тему, но хотите переключиться на нее, см. страницу Персонализация интегрированной среды разработки и редактора Visual Studio. If you aren’t using the dark theme but would like to, see the Personalize the Visual Studio IDE and Editor page to learn how.

Создание проекта Create a project

Сначала вы создадите проект приложения Visual Basic. First, you’ll create a Visual Basic application project. Для этого типа проекта уже имеются все нужные файлы шаблонов, что избавляет вас от лишней работы. The project type comes with all the template files you’ll need, before you’ve even added anything.

Откройте Visual Studio 2017. Open Visual Studio 2017.

В верхней строке меню последовательно выберите Файл > Создать > Проект. From the top menu bar, choose File > New > Project.

В левой области диалогового окна Новый проект разверните узел Visual Basic и выберите Рабочий стол Windows. In the New Project dialog box in the left pane, expand Visual Basic, and then choose Windows Desktop. На средней панели выберите Приложение Windows Forms (.NET Framework) . In the middle pane, choose Windows Forms App (.NET Framework). Назовите файл HelloWorld . Then name the file HelloWorld .

Если шаблон проекта Приложение Windows Forms (.NET Framework) отсутствует, закройте диалоговое окно Новый проект и в верхней строке меню выберите Сервис > Получить средства и компоненты. If you don’t see the Windows Forms App (.NET Framework) project template, cancel out of the New Project dialog box and from the top menu bar, choose Tools > Get Tools and Features. Запускается Visual Studio Installer. The Visual Studio Installer launches. Выберите рабочую нагрузку .Разработка классических приложений .NET и затем элемент Изменить. Choose the .NET desktop development workload, then choose Modify.

Запустите Visual Studio 2019. Open Visual Studio 2019.

На начальном экране выберите Создать проект. On the start window, choose Create a new project.

В окне Создать проект выберите шаблон Приложение Windows Forms (.NET Framework) для Visual Basic. On the Create a new project window, choose the Windows Forms App (.NET Framework) template for Visual Basic.

(При желании вы можете уточнить условия поиска, чтобы быстро перейти к нужному шаблону. (If you prefer, you can refine your search to quickly get to the template you want. Например, введите Приложение Windows Forms в поле поиска. For example, enter or type Windows Forms App in the search box. Затем выберите Visual Basic в списке языков и Windows в списке платформ.) Next, choose Visual Basic from the Language list, and then choose Windows from the Platform list.)

Если шаблон Приложение Windows Forms (.NET Framework) отсутствует, его можно установить из окна Создание проекта. If you do not see the Windows Forms App (.NET Framework) template, you can install it from the Create a new project window. В сообщении Не нашли то, что искали? выберите ссылку Установка других средств и компонентов. In the Not finding what you’re looking for? message, choose the Install more tools and features link.

После этого в Visual Studio Installer выберите рабочую нагрузку Разработка классических приложений .NET. Next, in the Visual Studio Installer, choose the Choose the .NET desktop development workload.

Затем нажмите кнопку Изменить в Visual Studio Installer. After that, choose the Modify button in the Visual Studio Installer. Вам может быть предложено сохранить результаты работы; в таком случае сделайте это. You might be prompted to save your work; if so, do so. Выберите Продолжить, чтобы установить рабочую нагрузку. Next, choose Continue to install the workload. После этого вернитесь к шагу 2 в процедуре Создание проекта. Then, return to step 2 in this «Create a project» procedure.

В поле Имя проекта окна Настроить новый проект введите HelloWorld. In the Configure your new project window, type or enter HelloWorld in the Project name box. Затем нажмите Создать. Then, choose Create.

Новый проект открывается в Visual Studio. Visual Studio opens your new project.

Читайте также:  Linux не могу запустить файл php

Создание приложения Create the application

Когда вы выберете шаблон проекта Visual Basic и зададите имя файла, Visual Studio открывает форму. After you select your Visual Basic project template and name your file, Visual Studio opens a form for you. Форма является пользовательским интерфейсом Windows. A form is a Windows user interface. Мы создадим приложение Hello World, добавив элементы управления на форму, а затем запустим его. We’ll create a «Hello World» application by adding controls to the form, and then we’ll run the app.

Добавление кнопки на форму Add a button to the form

Щелкните Панель элементов, чтобы открыть всплывающее окно «Панель элементов». Click Toolbox to open the Toolbox fly-out window.

(Если параметр для всплывающего окна Панель элементов отсутствует, его можно открыть в строке меню. (If you don’t see the Toolbox fly-out option, you can open it from the menu bar. Для этого выберите Вид > Панель элементов. To do so, View > Toolbox. Либо нажмите клавиши CTRL+ALT+X.) Or, press Ctrl+Alt+X.)

Щелкните значок Закрепить, чтобы закрепить окно Панель элементов. Click the Pin icon to dock the Toolbox window.

Щелкните элемент управления Кнопка и перетащите его на форму. Click the Button control and then drag it onto the form.

В разделе Внешний вид (или Шрифты) окна Свойства введите Click this и нажмите клавишу ВВОД. In the Appearance section (or the Fonts section) of the Properties window, type Click this , and then press Enter.

(Если окно Свойства не отображается, его можно открыть в строке меню.) (If you don’t see the Properties window, you can open it from the menu bar. Для этого щелкните Вид > Окно свойств. To do so, click View > Properties Window. Или нажмите клавишу F4.) Or, press F4.)

В разделе Проектирование окна Свойства измените имя с Button1 на btnClickThis , а затем нажмите клавишу ВВОД. In the Design section of the Properties window, change the name from Button1 to btnClickThis , and then press Enter.

Если список был упорядочен по алфавиту в окне Свойства, Button1 появится в разделе (DataBindings) . If you’ve alphabetized the list in the Properties window, Button1 appears in the (DataBindings) section, instead.

Добавление метки на форму Add a label to the form

Теперь, когда мы добавили элемент управления »Кнопка» для создания действия, давайте добавим элемент управления «Метка», куда можно отправлять текст. Now that we’ve added a button control to create an action, let’s add a label control to send text to.

Выберите элемент управления Метка в окне Панель элементов, а затем перетащите его на форму и расположите под кнопкой Нажмите это. Select the Label control from the Toolbox window, and then drag it onto the form and drop it beneath the Click this button.

В разделе Проект или (DataBindings) окна Свойства измените имя Label1 на lblHelloWorld и нажмите клавишу ВВОД. In either the Design section or the (DataBindings) section of the Properties window, change the name of Label1 to lblHelloWorld , and then press Enter.

Добавление кода на форму Add code to the form

В окне Form1.vb [Design] дважды щелкните кнопку Нажмите это, чтобы открыть окно Form1.vb. In the Form1.vb [Design] window, double-click the Click this button to open the Form1.vb window.

(Кроме того, можно развернуть узел Form1.vb в обозревателе решений, а затем выбрать Form1.) (Alternatively, you can expand Form1.vb in Solution Explorer, and then click Form1.)

В окне Form1.vb между строками Private Sub и End Sub введите lblHelloWorld.Text = «Hello World!» , как показано на следующем снимке экрана: In the Form1.vb window, between the Private Sub and End Sub lines, type or enter lblHelloWorld.Text = «Hello World!» as shown in the following screenshot:

Запуск приложения Run the application

Нажмите кнопку Запустить, чтобы запустить приложение. Click the Start button to run the application.

Будет выполнено несколько операций. Several things will happen. В интегрированной среде разработки Visual Studio откроются окна Средства диагностики и Вывод. In the Visual Studio IDE, the Diagnostics Tools window will open, and an Output window will open, too. Кроме того, вне этой среды откроется диалоговое окно Form1. But outside of the IDE, a Form1 dialog box appears. Оно будет содержать вашу кнопку Нажмите это и текст Label1. It will include your Click this button and text that says Label1.

Нажмите кнопку Нажмите это в диалоговом окне Form1. Click the Click this button in the Form1 dialog box. Обратите внимание, что текст Label1 меняется на Hello World! . Notice that the Label1 text changes to Hello World!.

Закройте диалоговое окно Form1, чтобы завершить работу приложения. Close the Form1 dialog box to stop running the app.

Следующие шаги Next steps

Для получения дополнительных сведений перейдите к следующему руководству: To learn more, continue with the following tutorial:

Оцените статью