- Создание приложения Windows Forms на C# в Visual Studio Create a Windows Forms app in Visual Studio with C#
- Создание проекта Create a project
- Создание приложения Create the application
- Добавление кнопки на форму Add a button to the form
- Добавление метки на форму Add a label to the form
- Добавление кода на форму Add code to the form
- Запуск приложения Run the application
- Следующие шаги Next steps
- Учебник. Создание первого приложения универсальной платформы Windows в Visual Studio с помощью XAML и C# Tutorial: Create your first Universal Windows Platform application in Visual Studio with XAML and C#
- Создание проекта Create a project
- Создание приложения Create the application
- Добавление кнопки на холст конструктора Add a button to the Design canvas
- Добавление метки к кнопке Add a label to the button
- Добавление обработчика событий Add an event handler
- Что же мы только что сделали? What did we just do?
- Запуск приложения Run the application
- Следующие шаги Next steps
Создание приложения 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 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.
Выберите элемент управления Метка в окне Панель элементов, а затем перетащите его на форму и расположите под кнопкой Нажмите это. 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:
Учебник. Создание первого приложения универсальной платформы Windows в Visual Studio с помощью XAML и C# Tutorial: Create your first Universal Windows Platform application in Visual Studio with XAML and C#
В рамках этого краткого руководства по возможностям интегрированной среды разработки (IDE) Visual Studio вы создадите простое приложение «Hello World» для выполнения на устройстве с Windows 10. In this introduction to the Visual Studio integrated development environment (IDE), you’ll create a «Hello World» app that runs on any Windows 10 device. Для этого потребуется использование шаблона проекта универсальной платформы Windows (UWP), расширяемого языка разметки приложений (XAML) и языка программирования C#. To do so, you’ll use a Universal Windows Platform (UWP) project template, Extensible Application Markup Language (XAML), and the C# programming language.
Установите 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.
Создание проекта Create a project
Сначала создадим новый проект приложения для универсальной платформы Windows. First, create a Universal Windows Platform project. Для этого типа проекта уже имеются все нужные файлы шаблонов, что избавляет вас от лишней работы. The project type comes with all the template files you need, before you’ve even added anything!
Запустите Visual Studio. Open Visual Studio.
В верхней строке меню последовательно выберите Файл > Создать > Проект. From the top menu bar, choose File > New > Project.
В левой панели диалогового окна Новый проект разверните узел Visual C# и выберите Универсальные приложения. In the left pane of the New Project dialog box, expand Visual C#, and then choose Windows Universal. В средней панели выберите Пустое приложение (универсальное приложение Windows) . In the middle pane, choose Blank App (Universal Windows). Назовите проект HelloWorld и нажмите OK. Then, name the project HelloWorld and choose OK.
Убедитесь, что исходный проект находится на отформатированном диске NTFS, например на диске операционной системы (ОС). Make sure that the location of the source project is on a New Technology File System (NTFS) formatted drive, such as your Operating System (OS) drive. В противном случае могут возникнуть проблемы при сборке и выполнении проекта. Otherwise, you might have trouble building and running your project.
Если шаблон проекта Пустое приложение (универсальное приложение Windows) отсутствует, щелкните ссылку Открыть установщик Visual Studio в левой области диалогового окна Новый проект. If you don’t see the Blank App (Universal Windows) project template, click the Open Visual Studio Installer link in the left pane of the New Project dialog box.
Запускается Visual Studio Installer. The Visual Studio Installer launches. Выберите рабочую нагрузку Разработка приложений для универсальной платформы Windows и выберите Изменить. Choose the Universal Windows Platform development workload, and then choose Modify.
Подтвердите значения по умолчанию для параметров Целевая версия и Минимальная версия в диалоговом окне Новый проект приложения для универсальной платформы Windows. Accept the default Target version and Minimum version settings in the New Universal Windows Platform Project dialog box.
Откройте Visual Studio и в начальном окне выберите Создать проект. Open Visual Studio, and on the start window, choose Create a new project.
На экране Создание проекта введите в поле поиска Универсальная платформа Windows, выберите шаблон C# Пустое приложение (универсальная платформа Windows) и щелкните Далее. On the Create a new project screen, enter Universal Windows in the search box, choose the C# template for Blank App (Universal Windows), and then choose Next.
Если вы не видите здесь шаблон Пустое приложение (универсальное приложение Windows) , щелкните ссылку Установка других средств и компонентов. If you don’t see the Blank App (Universal Windows) project template, click the Install more tools and features link.
Запускается Visual Studio Installer. The Visual Studio Installer launches. Выберите рабочую нагрузку Разработка приложений для универсальной платформы Windows и выберите Изменить. Choose the Universal Windows Platform development workload, and then choose Modify.
Присвойте проекту имя HelloWorld и нажмите кнопку Создать. Give the project a name, HelloWorld, and choose Create.
Подтвердите значения по умолчанию для параметров Целевая версия и Минимальная версия в диалоговом окне Новый проект приложения для универсальной платформы Windows. Accept the default Target version and Minimum version settings in the New Universal Windows Platform Project dialog box.
При первом использовании Visual Studio для создания приложения UWP появится диалоговое окно Параметры. If this is the first time you have used Visual Studio to create a UWP app, a Settings dialog box might appear. Выберите Режим разработчика, затем нажмите Да. Choose Developer mode, and then choose Yes.
Visual Studio установит дополнительный пакет режима разработчика. Visual Studio installs an additional Developer Mode package for you. После завершения установки пакета закройте диалоговое окно Параметры. When the package installation is complete, close the Settings dialog box.
Создание приложения Create the application
Теперь можно приступить к разработке. It’s time to start developing. Мы добавим элемент управления »Кнопка», назначим кнопке действие и затем запустим приложение «Hello World», чтобы посмотреть, как оно выглядит. You’ll add a button control, add an action to the button, and then start the «Hello World» app to see what it looks like.
Добавление кнопки на холст конструктора Add a button to the Design canvas
В Обозревателе решений дважды щелкните на файле MainPage.xaml, чтобы открыть разделенное представление. In the Solution Explorer, double-click MainPage.xaml to open a split view.
Откроется две панели: Конструктор XAML, содержащий холст конструктора, и редактор XAML, в котором можно добавлять и изменять код. There are two panes: The XAML Designer, which includes a design canvas, and the XAML Editor, where you can add or change code.
Щелкните Панель элементов, чтобы открыть всплывающее окно «Панель элементов». Choose Toolbox to open the Toolbox fly-out window.
(Если параметр Панель элементов отсутствует, его можно открыть в строке меню. (If you don’t see the Toolbox option, you can open it from the menu bar. Для этого выберите Вид > Панель инструментов. To do so, choose View > Toolbar. Либо нажмите клавиши 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 design canvas.
Если посмотреть на код в редакторе XAML, мы увидим, что кнопка была также добавлена туда: If you look at the code in the XAML Editor, you’ll see that the Button has been added there, too:
Добавление метки к кнопке Add a label to the button
В редакторе XAML измените значение параметра Content кнопки с «Button» на «Hello World!». In the XAML Editor, change Button Content value from «Button» to «Hello World!»
Обратите внимание, что кнопка в Конструкторе XAML также изменится. Notice that the button in the XAML Designer changes, too.
Добавление обработчика событий Add an event handler
Название «обработчик событий» звучит как что-то сложное, но это всего лишь еще одно имя в коде, которое вызывается, когда происходит какое-то событие. An «event handler» sounds complicated, but it’s just another name for code that is called when an event happens. В нашем случае он добавляет действие к кнопке «Hello World!». In this case, it adds an action to the «Hello World!» . button.
Дважды щелкните элемент управления «Кнопка» на холсте конструктора. Double-click the button control on the design canvas.
Измените код обработчика событий в файле MainPage.xaml.cs, страница с выделенным кодом. Edit the event handler code in MainPage.xaml.cs, the code-behind page.
Здесь начинается самое интересное. Here is where things get interesting. Обработчик события по умолчанию выглядит так: The default event handler looks like this:
Давайте изменим его, чтобы он выглядел следующим образом: Let’s change it, so it looks like this:
Ниже приведен код для копирования и вставки: Here’s the code to copy and paste:
Что же мы только что сделали? What did we just do?
Этот код использует некоторые функции API Windows для создания объекта синтеза речи и передает ему некоторый текст для озвучивания. The code uses some Windows APIs to create a speech synthesis object and then gives it some text to say. (Дополнительные сведения об использовании SpeechSynthesis см. в статье System.Speech.Synthesis.) (For more information on using SpeechSynthesis , see System.Speech.Synthesis.)
Запуск приложения Run the application
Пришло время для построения, развертывания и запуска UWP-приложения «Hello World», чтобы посмотреть, как оно выглядит и как оно звучит. It’s time to build, deploy, and launch the «Hello World» UWP app to see what it looks and sounds like. Ниже описывается порядок действий. Here’s how.
Используйте кнопку воспроизведения (с меткой локальный компьютер), чтобы запустить приложение на локальном компьютере. Use the Play button (it has the text Local Machine) to start the application on the local machine.
(Вы также можете выбрать команду Отладка > Начать отладку в строке меню или нажать клавишу F5 для запуска приложения.) (Alternatively, you can choose Debug > Start Debugging from the menu bar or press F5 to start your app.)
Посмотрите на свое приложение, которое появится вскоре после исчезновения всплывающего окна. View your app, which appears soon after a splash screen disappears. Приложение должно выглядеть следующим образом: The app should look similar to this:
Нажмите кнопку Hello World. Click the Hello World button.
Ваше устройство с Windows 10 буквально произнесет «Hello, World!». Your Windows 10 device will literally say, «Hello, World!»
Для закрытия приложения нажмите кнопку Остановить отладку на панели инструментов. To close the app, click the Stop Debugging button in the toolbar. (Либо выберите пункт меню Отладка > Остановить отладку или нажмите клавиши SHIFT+F5.) (Alternatively, choose Debug > Stop debugging from the menu bar, or press Shift+F5.)
Пришло время для построения, развертывания и запуска UWP-приложения «Hello World», чтобы посмотреть, как оно выглядит и как оно звучит. It’s time to build, deploy, and launch the «Hello World» UWP app to see what it looks and sounds like. Ниже описывается порядок действий. Here’s how.
Используйте кнопку воспроизведения (с меткой локальный компьютер), чтобы запустить приложение на локальном компьютере. Use the Play button (it has the text Local Machine) to start the application on the local machine.
(Вы также можете выбрать команду Отладка > Начать отладку в строке меню или нажать клавишу F5 для запуска приложения.) (Alternatively, you can choose Debug > Start Debugging from the menu bar or press F5 to start your app.)
Посмотрите на свое приложение, которое появится вскоре после исчезновения всплывающего окна. View your app, which appears soon after a splash screen disappears. Приложение должно выглядеть следующим образом: The app should look similar to this:
Нажмите кнопку Hello World. Click the Hello World button.
Ваше устройство с Windows 10 буквально произнесет «Hello, World!». Your Windows 10 device will literally say, «Hello, World!»
Для закрытия приложения нажмите кнопку Остановить отладку на панели инструментов. To close the app, click the Stop Debugging button in the toolbar. (Либо выберите пункт меню Отладка > Остановить отладку или нажмите клавиши SHIFT+F5.) (Alternatively, choose Debug > Stop debugging from the menu bar, or press Shift+F5.)
Следующие шаги Next steps
Поздравляем с завершением этого учебника! Congratulations on completing this tutorial! Мы надеемся, что вы узнали некоторые основные сведения об универсальной платформе Windows (UWP) и интегрированной среде разработки Visual Studio. We hope you learned some basics about UWP and the Visual Studio IDE. Для получения дополнительных сведений перейдите к следующему руководству: To learn more, continue with the following tutorial: