- Создание приложения 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
- Overview of Windows Programming in C++
- Command line (console) applications
- Native desktop client applications
- C++ or .NET?
- COM Components
- Universal Windows Platform apps
- Desktop Bridge
- Games
- SQL Server database clients
- Windows device drivers
- Windows services
- SDKs, libraries, and header files
- Development Tools
Создание приложения 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:
Overview of Windows Programming in C++
There are several broad categories of Windows applications that you can create with C++. Each has its own programming model and set of Windows-specific libraries, but the C++ standard library and third-party C++ libraries can be used in any of them.
This section discusses how to use Visual Studio and the MFC/ATL wrapper libraries to create Windows programs. For documentation on the Windows platform itself, see Windows documentation.
Command line (console) applications
C++ console applications run from the command line in a console window and can display text output only. For more information, see Create a console calculator in C++.
Native desktop client applications
A native desktop client application is a C or C++ windowed application that uses the original native Windows C APIs or Component Object Model (COM) APIs to access the operating system. Those APIs are themselves written mostly in C. There’s more than one way to create a native desktop app: You can program using the Win32 APIs directly, using a C-style message loop that processes operating system events. Or, you can program using Microsoft Foundation Classes (MFC), a lightly object-oriented C++ library that wraps Win32. Neither approach is considered «modern» compared to the Universal Windows Platform (UWP), but both are still fully supported and have millions of lines of code running in the world today. A Win32 application that runs in a window requires the developer to work explicitly with Windows messages inside a Windows procedure function. Despite the name, a Win32 application can be compiled as a 32-bit (x86) or 64-bit (x64) binary. In the Visual Studio IDE, the terms x86 and Win32 are synonymous.
To get started with traditional Windows C++ programming, see Get Started with Win32 and C++. After you gain some understanding of Win32, it will be easier to learn about MFC Desktop Applications. For an example of a traditional C++ desktop application that uses sophisticated graphics, see Hilo: Developing C++ Applications for Windows.
C++ or .NET?
In general, .NET programming in C# is less complex, less error-prone, and has a more modern object-oriented API than Win32 or MFC. In most cases, its performance is more than adequate. .NET features the Windows Presentation Foundation (WPF) for rich graphics, and you can consume both Win32 and the modern Windows Runtime API. As a general rule, we recommend using C++ for desktop applications when you require:
- precise control over memory usage
- the utmost economy in power consumption
- usage of the GPU for general computing
- access to DirectX
- heavy usage of standard C++ libraries
It’s also possible to combine the power and efficiency of C++ with .NET programming. You can create a user interface in C# and use C++/CLI to enable the application to consume native C++ libraries. For more information, see .NET Programming with C++/CLI.
COM Components
The Component Object Model (COM) is a specification that enables programs written in different languages to communicate with one another. Many Windows components are implemented as COM objects and follow standard COM rules for object creation, interface discovery, and object destruction. Using COM objects from C++ desktop applications is relatively straightforward, but writing your own COM object is more advanced. The Active Template Library (ATL) provides macros and helper functions that simplify COM development. For more information, see ATL COM desktop components.
Universal Windows Platform apps
The Universal Windows Platform (UWP) is the modern Windows API. UWP apps run on any Windows 10 device, use XAML for the user-interface, and are fully touch-enabled. For more information about UWP, see What’s a Universal Windows Platform (UWP) app? and Guide to Windows Universal Apps.
The original C++ support for UWP consisted of (1) C++/CX, a dialect of C++ with syntax extensions, or (2) the Windows Runtime Library (WRL), which is based on standard C++ and COM. Both C++/CX and WRL are still supported. For new projects, we recommend C++/WinRT, which is entirely based on standard C++ and provides faster performance.
Desktop Bridge
In Windows 10, you can package your existing desktop application or COM object as a UWP app, and add UWP features such as touch, or call APIs from the modern Windows API set. You can also add a UWP app to a desktop solution in Visual Studio, and package them together in a single package and use Windows APIs to communicate between them.
Visual Studio 2017 version 15.4 and later lets you create a Windows Application Package Project to greatly simplify the work of packaging your existing desktop application. A few restrictions apply to the registry calls or APIs your desktop application can use. However, in many cases you can create alternate code paths to achieve similar functionality while running in an app package. For more information, see Desktop Bridge.
Games
DirectX games can run on the PC or Xbox. For more information, see DirectX Graphics and Gaming.
SQL Server database clients
To access SQL Server databases from native code, use ODBC or OLE DB. For more information, see SQL Server Native Client.
Windows device drivers
Drivers are low-level components that make data from hardware devices accessible to applications and other operating system components. For more information, see Windows Driver Kit (WDK).
Windows services
A Windows service is a program that can run in the background with little or no user interaction. These programs are called daemons on UNIX systems. For more information, see Services.
SDKs, libraries, and header files
Visual Studio includes the C Runtime Library (CRT), the C++ Standard Library, and other Microsoft-specific libraries. Most of the include folders that contain header files for these libraries are located in the Visual Studio installation directory under the \VC\ folder. The Windows and CRT header files are found in the Windows SDK installation folder.
The Vcpkg package manager lets you conveniently install hundreds of third-party open-source libraries for Windows.
The Microsoft libraries include:
Microsoft Foundation Classes (MFC): An object-oriented framework for creating traditional Windows programs—especially enterprise applications—that have rich user interfaces that feature buttons, list boxes, tree views, and other controls. For more information, see MFC Desktop Applications.
Active Template Library (ATL): A powerful helper library for creating COM components. For more information, see ATL COM Desktop Components.
C++ AMP (C++ Accelerated Massive Parallelism): A library that enables high-performance general computational work on the GPU. For more information, see C++ AMP (C++ Accelerated Massive Parallelism).
Concurrency Runtime: A library that simplifies the work of parallel and asynchronous programming for multicore and many-core devices. For more information, see Concurrency Runtime.
Many Windows programming scenarios also require the Windows SDK, which includes the header files that enable access to the Windows operating system components. By default, Visual Studio installs the Windows SDK as a component of the C++ Desktop workload, which enables development of Universal Windows apps. To develop UWP apps, you need the Windows 10 version of the Windows SDK. For information, see Windows 10 SDK. (For more information about the Windows SDKs for earlier versions of Windows, see the Windows SDK archive).
Program Files (x86)\Windows Kits is the default location for all versions of the Windows SDK that you’ve installed.
Other platforms such as Xbox and Azure have their own SDKs that you may have to install. For more information, see the DirectX Developer Center and the Azure Developer Center.
Development Tools
Visual Studio includes a powerful debugger for native code, static analysis tools, graphics debugging tools, a full-featured code editor, support for unit tests, and many other tools and utilities. For more information, see Get started developing with Visual Studio, and Overview of C++ development in Visual Studio.