Программирование windows from приложений

Создание приложения 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

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

Читайте также:  Стандартные команды для linux

В разделе Проект или (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 Get Windows app samples

Многие официальные примеры кода Windows доступны в различных репозиториях GitHub, включая примеры приложений универсальной платформы Windows (UWP), примеры классических приложений для Windows и коллекцию примеров, рассматриваемых в документации для разработчиков Windows. Many official Windows code samples are available in various GitHub repositories, including Universal Windows Platform (UWP) app samples, Windows classic samples, along with a collection of Windows developer documentation samples. В этих примерах демонстрируется, как применяются большинство функций Windows и их API. These samples demonstrate most Windows features and their API use patterns.

Чтобы немного упростить поиск конкретных примеров, используйте упорядоченную коллекцию, доступную в обозревателе примеров кода. В ней вы сможете просмотреть и найти различные технологии и средства для разработчиков Майкрософт. To make finding specific samples a little bit easier, you can browse and search a categorized collection of code samples for various Microsoft developer tools and technologies through the sample browser.

Примеры, рассматриваемые в документации для разработчиков Windows Windows developer documentation samples

Ниже приведен список примеров мини-приложений, созданных специально для поддержки документации для разработчиков Windows. Here’s a list of mini-app samples created specifically to support Windows developer documentation. Если не указано иное, все следующие примеры представляют собой приложения UWP, которые обновлены для использования элементов управления последней версии WinUI 2.4. Unless noted, the following samples are all Universal Windows Platform (UWP) apps that have been updated to use the latest WinUI 2.4 controls.

  • RSS Reader — получение сведений о RSS-каналах и просмотр статей. Rss Reader — Retrieve RSS feeds and view articles
  • Family Notes — изучение различных модальностей ввода и сценариев узнавания пользователей. Family Notes — Explore different input modalities and scenarios of user awareness
  • Customer Orders — демонстрация функций, полезных для корпоративных разработчиков, например аутентификации Azure Active Directory (AAD), элементов управления пользовательского интерфейса (включая сетку данных), интеграция Sqlite и Базы данных SQL Azure, Entity Framework и облачные службы API. Customer Orders — Features useful to enterprise developers, like Azure Active Directory (AAD) authentication, UI controls (including a data grid), Sqlite and SQL Azure database integration, Entity Framework, and cloud API services
  • Lunch Scheduler — планирование обедов с друзьями и коллегами. Lunch Scheduler — Schedule lunches with your friends and coworkers
  • Coloring Book — демонстрация работы Windows Ink (в том числе панели инструментов Windows Ink) и функций радиального контроллера (для устройств Wheel, например Surface Dial). Coloring Book — Windows Ink (including the Windows Ink Toolbar) and radial controller (for Wheel devices such as the Surface Dial) features
  • Network Helper (Quiz Game) — обнаружение сетей и реализация обмена данными. Network Helper (Quiz Game) — Network discovery and communication
  • HUE Lights Controller — интеллектуальная система домашней автоматики с использованием Кортаны и технологии Bluetooth Low Energy (Bluetooth LE). HUE Lights Controller — Intelligent home automation with Cortana and Bluetooth Low Energy (Bluetooth LE)
  • Marble Maze — простая трехмерная игра с использованием DirectX. Marble Maze — Basic 3D game using DirectX
  • PhotoLab — просмотр и изменение файлов изображений. PhotoLab — View and edit image files
Читайте также:  Как удалить microsoft edge windows 10 pro

Скачать код Download the code

Чтобы скачать примеры, перейдите в один из репозиториев Майкрософт, например репозиторий с примерами приложений универсальной платформы Windows (UWP). To download the samples, go to one of the Microsoft repos such as Universal Windows Platform (UWP) app samples. Выберите Clone or download (Клонировать или скачать), а затем — Download ZIP (Скачать ZIP-файл). Select Clone or download, and then select Download ZIP.

В ZIP-файле для скачивания всегда содержатся последние версии примеров. The samples download .zip file always has the latest samples. Для скачивания файла не требуется учетная запись GitHub. You don’t need a GitHub account to download the file. Если выпущено обновление SDK или необходимо получить только последние изменения и добавления, просто скачайте актуальный ZIP-файл. When an SDK update is released or if you want to pick up any recent changes and additions, just download the latest zip file.

Для открытия, создания и запуска примеров Windows требуется Visual Studio и пакет Windows SDK. To open, build, and run Windows samples, you must have Visual Studio and the Windows SDK. Вы можете получить бесплатную копию Visual Studio Community. You can get a free copy of Visual Studio Community.

Для правильной работы примеров нужно распаковать весь архив, а не только отдельные примеры. For the samples to work correctly, be sure to unzip the entire archive and not individual samples. Большинство примеров зависят от общих файлов из папки SharedContent и используют связанные файлы, включая файлы шаблонов примеров и ресурсы изображений, чтобы уменьшить дублирование общих файлов. Many of the samples depend on common files in the SharedContent folder and use linked files, including sample template files and image assets, to reduce duplication.

Открытие примеров Open the samples

Скачайте ZIP-файл и откройте примеры в Visual Studio. After you download the .zip file, open the samples in Visual Studio.

Прежде чем распаковывать архив, щелкните файл правой кнопкой мыши и выберите Свойства > Разблокировать > Применить. Before you unzip the archive, right-click the file, select Properties > Unblock > Apply. Затем распакуйте архив в локальную папку на компьютере. Then, unzip the archive in a local folder on your computer.

Каждая папка в папке Samples содержит пример функции Windows. Each folder in the Samples folder contains a Windows feature sample.

Выберите пример. Select a sample. Поддерживаемые языки обозначаются вложенной папкой для конкретного языка. Supported languages are indicated by a language-specific sub-folder.

Выберите папку для языка, который нужно использовать. Select the folder for the language you want to use. В содержимом папки вы увидите файл решения Visual Studio (с расширением .sln), который можно открыть в Visual Studio. In the folder contents, you’ll see a Visual Studio solution (.sln) file that you can open in Visual Studio.

Обратная связь, вопросы и сообщения о проблемах Give feedback, ask questions, and report issues

Если у вас возникают проблемы или вопросы, перейдите на вкладку Issues (Проблемы) репозитория, чтобы создать запрос. If you have problems or questions, use the Issues tab in the repository to create a new issue.

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