Windows forms свой класс

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

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

Установите 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

Сначала вы создадите проект приложения на C#. First, you’ll create a C# 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 C# и выберите Рабочий стол Windows. In the New Project dialog box in the left pane, expand Visual C#, 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) для C#. On the Create a new project window, choose the Windows Forms App (.NET Framework) template for C#.

(При желании вы можете уточнить условия поиска, чтобы быстро перейти к нужному шаблону. (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. Затем выберите C# в списке языков и Windows в списке платформ.) Next, choose C# from the Language list, and then choose Windows from the Platform list.)

Читайте также:  Windows live mail запрещенный тип файла

Если шаблон Приложение 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.

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

Когда вы выберете шаблон проекта C# и зададите имя файла, Visual Studio открывает форму. After you select your C# 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

Щелкните Панель элементов, чтобы открыть всплывающее окно «Панель элементов». Choose 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.)

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

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

В окне Свойства найдите элемент Текст, измените имя с Button1 на Click this , а затем нажмите клавишу ВВОД. In the Properties window, locate Text, change the name from Button1 to 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, choose 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.

Читайте также:  Astra linux special edition руководство администратора часть 1

Выберите элемент управления Метка в окне Панель элементов, а затем перетащите его на форму и расположите под кнопкой Нажмите это. 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.cs [Проект] дважды щелкните кнопку Нажмите это, чтобы открыть окно Form1.cs. In the Form1.cs [Design] window, double-click the Click this button to open the Form1.cs window.

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

В окне Form1.cs после строки private void введите lblHelloWorld.Text = «Hello World!»; , как показано на следующем снимке экрана: In the Form1.cs window, after the private void line, type or enter lblHelloWorld.Text = «Hello World!»; as shown in the following screenshot:

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

Нажмите кнопку Запустить, чтобы запустить приложение. Choose 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. Choose 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:

Добавление класса Add a class

Чтобы добавить класс в проект Visual Studio C++, в обозревателе решений щелкните правой кнопкой мыши проект, выберите Добавить, а затем Класс. To add a class in a Visual Studio C++ project, in Solution Explorer, right-click the project, choose Add, and then choose Class. Откроется диалоговое окно Добавление класса. This opens the Add Class dialog box.

При добавлении класса нужно указать имя, которое отличается от классов, уже существующих в MFC или ATL. When you add a class, you must specify a name that is different from classes that already exist in MFC or ATL. Если указать имя, которое уже существует в одной из библиотек, интегрированная среда разработки выводит сообщение об ошибке. If you specify a name that already exists in either library, the IDE shows an error message.

Если по соглашению об именовании нужно использовать существующее имя, можно просто изменить регистр одной или нескольких букв в имени, так как C++ учитывает регистр. If your project naming convention requires you to use an existing name, then you can just change the case of one or more letters in the name because C++ is case-sensitive. Например, хотя вы не можете назвать класс CDocument , можно назвать его cdocument . For example, although you cannot name a class CDocument , you can name it cdocument .

Содержание раздела In this section

Класс какого типа вы хотите добавить? What kind of class do you want to add?

В диалоговом окне Добавление класса при развертывании узла Visual C++ на левой панели отображаются несколько групп установленных шаблонов. In the Add Class dialog box, when you expand the Visual C++ node in the left pane several groupings of installed templates are displayed. К этим группам относятся CLR, ATL, MFC и C++. The groups include CLR, ATL, MFC, and C++. При выборе группы на средней панели отображается список доступных шаблонов в этой группе. When you select a group, a list of the available templates in that group is displayed in the middle pane. Каждый шаблон содержит необходимые для класса файлы и исходный код. Each template contains the files and source code that are required for a class.

Читайте также:  Start device manager windows

Чтобы создать класс, выберите шаблон в средней области, введите имя класса в поле Имя и нажмите Добавить. To generate a new class, select a template in the middle pane, type a name for the class in the Name box, and select Add. Открывается мастер добавления классов, где можно указать параметры для класса. This opens the Add Class Wizard so that you can specify options for the class.

Дополнительные сведения о создании классов MFC см. в разделе Класс MFC. For more information about how to create MFC classes, see MFC class.

Дополнительные сведения о создании классов ATL см. в разделе Простой объект ATL. For more information about how to create ATL classes, see ATL simple object.

Шаблон Добавление поддержки ATL в MFC не создает класс, а настраивает проект для использования библиотеки ATL. The template Add ATL Support to MFC does not create a class, but instead configures the project to use ATL. Дополнительные сведения см. в разделе Поддержка ATL в проекте MFC. For more information, see ATL support in an MFC project.

Чтобы создать класс C++, который не использует MFC, ATL или CLR, воспользуйтесь шаблоном Класс C++ в группе C++ установленных шаблонов. To make a C++ class that does not use MFC, ATL, or CLR, use the C++ Class template in the C++ group of installed templates. Дополнительные сведения см. в разделе Добавление универсального класса C++. For more information, see Add a generic C++ class.

Доступны два типа классов C++ на основе форм. Two kinds of form-based C++ classes are available. Первый — класс CFormView — создает класс MFC. The first one, CFormView class, creates an MFC class. Второй создает класс Windows Forms для среды CLR. The second one creates a CLR Windows Forms class.

Диалоговое окно «Добавление класса» Add Class dialog box

Диалоговое окно Добавление класса содержит шаблоны, которые позволяют выполнить следующие действия. The Add Class dialog box contains templates that allow you to:

Открыть соответствующий мастер создания кода, если он доступен. Open a corresponding code wizard, if one is available. Дополнительные сведения см. в разделе Добавление функциональных возможностей с помощью мастеров кода. For more information, see Add functionality with code wizards.

Автоматически создать новый класс, добавив в проект соответствующие файлы и исходный код. Automatically create your new class by adding the appropriate files and source code to your project.

Перейти к диалоговому окну Добавление класса можно из меню Проект, обозревателя решений или представления классов. You can access the Add Class dialog box from the Project menu, Solution Explorer, or Class View.

При попытке добавить класс, который не подходит для текущего проекта, вы получите сообщение об ошибке. When you attempt to add a class that is not suited to your current project, you will receive an error message. Нажмите ОК, чтобы вернуться в диалоговое окно Добавление класса. Select OK to return to the Add Class dialog box.

Добавление шаблонов классов Add Class templates

Существует четыре категории шаблонов добавления классов : .NET, ATL, MFC и универсальные. There are four categories of Add Class templates: .NET, ATL, MFC, and Generic. При выборе шаблона в области Шаблоны текст, описывающий выбранный шаблон, появится в областях Категории и Шаблоны . When you select a template in the Templates pane, text describing your selection will appear under the Categories and Templates panes.

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