- Get started with desktop Windows apps that use the Win32 API
- Get set up
- Learn how to create desktop apps using the Win32 API
- Modernize your desktop apps for Windows 10
- C++/WinRT
- What’s new for Win32 APIs in Windows 10
- Get started with Win32 features and technologies
- Tutorial: Create a .NET console application using Visual Studio
- Prerequisites
- Create the app
- Run the app
- Enhance the app
- Additional resources
- Next steps
- Общие сведения о программировании на C++ в Windows Overview of Windows Programming in C++
- Приложения командной строки (консоль) Command line (console) applications
- Собственные клиентские приложения для настольных систем Native desktop client applications
- C++ или .NET? C++ or .NET?
- COM-компоненты COM Components
- Приложения универсальной платформы Windows Universal Windows Platform apps
- Мост для классических приложений Desktop Bridge
- Игры Games
- Клиенты базы данных SQL Server SQL Server database clients
- Драйверы устройств Windows Windows device drivers
- Службы Windows Windows services
- Пакеты SDK, библиотеки и файлы заголовков SDKs, libraries, and header files
- средства разработки: Development Tools
Get started with desktop Windows apps that use the Win32 API
The Win32 API (also called the Windows API) is the original platform for native C/C++ Windows applications that require direct access to Windows and hardware. It provides a first-class development experience without depending on a managed runtime environment like .NET and WinRT (for UWP apps for Windows 10). This makes the Win32 API the platform of choice for applications that need the highest level of performance and direct access to system hardware.
This documentation covers how to create desktop Windows apps with the Win32 API. The Win32 API is one of several app platforms you can use to build desktop Windows apps. For more info about other app platforms, see Choose your platform.
Get set up
Follow these instructions and start creating desktop apps for Windows 10 that use the Win32 API.
Download or update Visual Studio 2019. If you don’t already have Visual Studio 2019, you can install the free Microsoft Visual Studio Community 2019. When you install Visual Studio, make sure to select the Desktop development with C++ option. For download links, see our Downloads page.
When you install Visual Studio, you can optionally select the .NET desktop development and Universal Windows Platform development options for access to other project types and app platforms for building desktop Windows apps.
If you want to build your desktop app into an MSIX package and test or debug the packaged app on your development computer, you’ll need to enable Developer Mode on your computer.
For scripts you can use to set up your development computer and install other features or packages, check out this GitHub project.
Learn how to create desktop apps using the Win32 API
If you’re new to building desktop apps using the Win32 API, the following tutorials and articles will help get you started.
Topic | Description |
---|---|
Create your first C++ Win32 app | This tutorial teaches you how to write a Windows program in C++ using Win32 and COM APIs. |
Create your first app using DirectX | This basic tutorial will get you started with DirectX app development. |
Programming Guide for 64-bit Windows | Describes programming for 64-bit versions of the Windows operating system. |
Using the Windows Headers | Provides an overview of some of the conventions used in the Windows header files. |
You can also browse the desktop app samples.
Modernize your desktop apps for Windows 10
If you have an existing desktop Win32 app, there are many features in the Universal Windows Platform (UWP) that you can use to deliver the best possible experience on Windows 10. For example, starting in Windows 10, version 1903, you can host UWP XAML controls in your desktop Win32 app using a feature called XAML Islands.
Most of these UWP features are available as modular components that you can adopt in your desktop app at your own pace without having to rewrite your entire application. You can enhance your existing desktop app by choosing which parts of Windows 10 and UWP to adopt.
C++/WinRT
Optionally, you can configure your development computer to use C++/WinRT. C++/WinRT is an entirely standard modern C++17 language projection enables you to easily consume Windows Runtime APIs Windows Runtime (WinRT) APIs from your C++ Win32 desktop application. C++/WinRT is implemented as a header-file-based library.
To configure your project for C++/WinRT:
- For new projects, you can install the C++/WinRT Visual Studio Extension (VSIX) and use one of the C++/WinRT project templates included in that extension.
- For existing Windows desktop application projects, you can install the Microsoft.Windows.CppWinRT NuGet package in the project.
For more details about these options, see this article.
What’s new for Win32 APIs in Windows 10
To learn about new Win32 APIs that have been introduced in Windows 10, see what’s new.
Get started with Win32 features and technologies
Win32 APIs exist for many features and technologies in Windows 10, including core user interface and windowing APIs, audio and graphics, and networking. For guidance and code samples about using these APIs, see our features and technologies index.
Tutorial: Create a .NET console application using Visual Studio
This tutorial shows how to create and run a .NET console application in Visual Studio 2019.
Prerequisites
Visual Studio 2019 version 16.9.2 or a later version with the .NET Core cross-platform development workload installed. The .NET 5.0 SDK is automatically installed when you select this workload.
Create the app
Create a .NET console app project named «HelloWorld».
Start Visual Studio 2019.
On the start page, choose Create a new project.
On the Create a new project page, enter console in the search box. Next, choose C# or Visual Basic from the language list, and then choose All platforms from the platform list. Choose the Console Application template, and then choose Next.
If you don’t see the .NET templates, you’re probably missing the required workload. Under the Not finding what you’re looking for? message, choose the Install more tools and features link. The Visual Studio Installer opens. Make sure you have the .NET Core cross-platform development workload installed.
In the Configure your new project dialog, enter HelloWorld in the Project name box. Then choose Next.
In the Additional information dialog, select .NET 5.0 (Current), and then select Create.
The template creates a simple «Hello World» application. It calls the Console.WriteLine(String) method to display «Hello World!» in the console window.
The template code defines a class, Program , with a single method, Main , that takes a String array as an argument:
Main is the application entry point, the method that’s called automatically by the runtime when it launches the application. Any command-line arguments supplied when the application is launched are available in the args array.
If the language you want to use is not shown, change the language selector at the top of the page.
Run the app
Press Ctrl + F5 to run the program without debugging.
A console window opens with the text «Hello World!» printed on the screen.
Press any key to close the console window.
Enhance the app
Enhance the application to prompt the user for their name and display it along with the date and time.
In Program.cs or Program.vb, replace the contents of the Main method, which is the line that calls Console.WriteLine , with the following code:
This code displays a prompt in the console window and waits until the user enters a string followed by the Enter key. It stores this string in a variable named name . It also retrieves the value of the DateTime.Now property, which contains the current local time, and assigns it to a variable named currentDate . And it displays these values in the console window. Finally, it displays a prompt in the console window and calls the Console.ReadKey(Boolean) method to wait for user input.
NewLine is a platform-independent and language-independent way to represent a line break. Alternatives are \n in C# and vbCrLf in Visual Basic.
The dollar sign ( $ ) in front of a string lets you put expressions such as variable names in curly braces in the string. The expression value is inserted into the string in place of the expression. This syntax is referred to as interpolated strings.
Press Ctrl + F5 to run the program without debugging.
Respond to the prompt by entering a name and pressing the Enter key.
Press any key to close the console window.
Additional resources
Next steps
In this tutorial, you created a .NET console application. In the next tutorial, you debug the app.
Общие сведения о программировании на C++ в Windows Overview of Windows Programming in C++
Существует несколько обширных категорий приложений Windows, которые можно создать с помощью C++. There are several broad categories of Windows applications that you can create with C++. Каждый из них имеет собственную модель программирования и набор библиотек для Windows, но в любом из них можно использовать стандартную библиотеку C++ и сторонние библиотеки 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.
В этом разделе описывается, как использовать Visual Studio и библиотеки оболочек MFC/ATL для создания программ Windows. This section discusses how to use Visual Studio and the MFC/ATL wrapper libraries to create Windows programs. Документацию по самой платформе Windows см. в документации по Windows. For documentation on the Windows platform itself, see Windows documentation.
Приложения командной строки (консоль) Command line (console) applications
Консольные приложения C++ запускаются из командной строки в окне консоли и могут отображать только текстовые выходные данные. C++ console applications run from the command line in a console window and can display text output only. Дополнительные сведения см. в разделе Создание калькулятора консоли в C++. For more information, see Create a console calculator in C++.
Собственные клиентские приложения для настольных систем Native desktop client applications
Собственное клиентское приложение для настольных систем — это оконное приложение c или C++, которое использует исходные интерфейсы API для Windows c или COM для доступа к операционной системе. 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. Эти интерфейсы API написаны в основном на языке C. Существует несколько способов создания собственного классического приложения: вы можете программировать напрямую с помощью API-интерфейсов Win32, используя цикл сообщений в стиле C, который обрабатывает события операционной системы. 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. Или можно программировать с помощью Microsoft Foundation Classes (MFC), объектно-ориентированной библиотеки C++, которая заключает в оболочку Win32. Or, you can program using Microsoft Foundation Classes (MFC), a lightly object-oriented C++ library that wraps Win32. Ни один из подходов не считается «современным» по сравнению с универсальная платформа Windows (UWP), но оба они все еще полностью поддерживаются и миллионы строк кода работают в мире уже сегодня. 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. Приложение Win32, выполняемое в окне, требует, чтобы разработчик работал явно с сообщениями Windows внутри функции процедуры Windows. A Win32 application that runs in a window requires the developer to work explicitly with Windows messages inside a Windows procedure function. Несмотря на имя, приложение Win32 можно скомпилировать 32 как 64-разрядный (x86) или 64-разрядный (x64) двоичный файл. Despite the name, a Win32 application can be compiled as a 32-bit (x86) or 64-bit (x64) binary. В интегрированной среде разработки Visual Studio термины x86 и Win32 являются синонимами. In the Visual Studio IDE, the terms x86 and Win32 are synonymous.
Чтобы приступить к работе с традиционным программированием на языке Windows C++, см. статью Начало работы с Win32 и C++. To get started with traditional Windows C++ programming, see Get Started with Win32 and C++. Когда вы получите представление об использовании Win32, будет проще изучить классическое приложение MFC. After you gain some understanding of Win32, it will be easier to learn about MFC Desktop Applications. Пример традиционного классического приложения C++, использующего сложную графику, см. в разделе Hilo: Разработка приложений c++ для Windows. For an example of a traditional C++ desktop application that uses sophisticated graphics, see Hilo: Developing C++ Applications for Windows.
C++ или .NET? C++ or .NET?
Как правило, программирование .NET в C# менее сложное, менее подверженное ошибкам и имеет более современный объектно-ориентированный API, чем Win32 или MFC. 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 использует Windows Presentation Foundation (WPF) для расширенной графики, и вы можете использовать как Win32, так и современный среда выполнения Windows API. .NET features the Windows Presentation Foundation (WPF) for rich graphics, and you can consume both Win32 and the modern Windows Runtime API. В качестве общего правила рекомендуется использовать C++ для классических приложений, когда требуется: 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
- Использование GPU для общих вычислений usage of the GPU for general computing
- доступ к DirectX access to DirectX
- интенсивное использование стандартных библиотек C++ heavy usage of standard C++ libraries
Также можно сочетать мощь и эффективность C++ с программированием на .NET. It’s also possible to combine the power and efficiency of C++ with .NET programming. Вы можете создать пользовательский интерфейс на C# и использовать C++/CLI, чтобы позволить приложению использовать собственные библиотеки C++. You can create a user interface in C# and use C++/CLI to enable the application to consume native C++ libraries. Дополнительные сведения см. в разделе программирование .NET с помощью C++/CLI. For more information, see .NET Programming with C++/CLI.
COM-компоненты COM Components
Модель COM — это спецификация, которая позволяет программам, написанным на разных языках, взаимодействовать друг с другом. The Component Object Model (COM) is a specification that enables programs written in different languages to communicate with one another. Многие компоненты Windows реализуются как COM-объекты и следуют стандартным правилам COM для создания объектов, обнаружения интерфейсов и уничтожения объектов. Many Windows components are implemented as COM objects and follow standard COM rules for object creation, interface discovery, and object destruction. Использование объектов COM из классических приложений C++ относительно просто, но написание собственного COM-объекта является более сложным. Using COM objects from C++ desktop applications is relatively straightforward, but writing your own COM object is more advanced. Библиотека активных шаблонов (ATL) предоставляет макросы и вспомогательные функции, УПРОЩАЮЩИЕ разработку com. The Active Template Library (ATL) provides macros and helper functions that simplify COM development. Дополнительные сведения см. в разделе компоненты ATL com Desktop. For more information, see ATL COM desktop components.
Приложения универсальной платформы Windows Universal Windows Platform apps
Универсальная платформа Windows (UWP) — это современный API Windows. The Universal Windows Platform (UWP) is the modern Windows API. Приложения UWP работают на любом устройстве Windows 10, используют XAML для пользовательского интерфейса и полностью поддерживают касание. UWP apps run on any Windows 10 device, use XAML for the user-interface, and are fully touch-enabled. Дополнительные сведения об универсальномконтроллере платформы Windows см. в статье что такое приложение универсальная платформа Windows (UWP) . For more information about UWP, see What’s a Universal Windows Platform (UWP) app? and Guide to Windows Universal Apps.
Исходная поддержка C++ для UWP состояла из (1) C++/CX, диалекта C++ с расширениями синтаксиса или (2) библиотеки среда выполнения Windows (WRL), основанной на стандартном C++ и COM. 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. C++/CX и WRL по-прежнему поддерживаются. Both C++/CX and WRL are still supported. Для новых проектов рекомендуется использовать c++/WinRT, который полностью основан на стандартном c++ и обеспечивает более высокую производительность. For new projects, we recommend C++/WinRT, which is entirely based on standard C++ and provides faster performance.
Мост для классических приложений Desktop Bridge
В Windows 10 можно упаковать существующее классическое приложение или COM-объект в качестве приложения UWP и добавить функции UWP, такие как сенсорный ввод, или вызвать API из современного набора API Windows. 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. Можно также добавить приложение UWP в решение для настольных систем в Visual Studio и упаковать их в один пакет и использовать интерфейсы API Windows для обмена данными между ними. 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 версии 15,4 и более поздних версий позволяет создать проект пакета приложений Windows, чтобы значительно упростить работу по упаковке существующего настольного приложения. 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. К вызовам реестра или API-интерфейсам, которые может использовать настольное приложение, применяются некоторые ограничения. 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 могут работать на компьютере или Xbox. DirectX games can run on the PC or Xbox. Дополнительные сведения см. в статье DirectX Graphics и игровыеустройства. For more information, see DirectX Graphics and Gaming.
Клиенты базы данных SQL Server SQL Server database clients
Для доступа к базам данных SQL Server из машинного кода используйте ODBC или OLE DB. To access SQL Server databases from native code, use ODBC or OLE DB. Дополнительные сведения см. в разделе SQL Server Native Client. For more information, see SQL Server Native Client.
Драйверы устройств Windows Windows device drivers
Драйверы — это низкоуровневые компоненты, которые делают данные из аппаратных устройств доступными для приложений и других компонентов операционной системы. Drivers are low-level components that make data from hardware devices accessible to applications and other operating system components. Дополнительные сведения см. в разделе Windows Driver Kit (WDK). For more information, see Windows Driver Kit (WDK).
Службы Windows Windows services
Служба Windows — это программа, которая может выполняться в фоновом режиме с небольшим или без участия пользователя. A Windows service is a program that can run in the background with little or no user interaction. Эти программы называются демоны на системах UNIX. These programs are called daemons on UNIX systems. Дополнительные сведения см. в разделе Службы. For more information, see Services.
Пакеты SDK, библиотеки и файлы заголовков SDKs, libraries, and header files
Visual Studio включает в себя библиотеку времени выполнения C (CRT), стандартную библиотеку C++ и другие библиотеки, относящиеся к Microsoft. Visual Studio includes the C Runtime Library (CRT), the C++ Standard Library, and other Microsoft-specific libraries. Большинство папок включения, содержащих файлы заголовков для этих библиотек, находятся в каталоге установки Visual Studio в папке \ВК Most of the include folders that contain header files for these libraries are located in the Visual Studio installation directory under the \VC\ folder. Файлы заголовков Windows и CRT находятся в папке установки Windows SDK. The Windows and CRT header files are found in the Windows SDK installation folder.
Диспетчер пакетов Vcpkg позволяет легко устанавливать сотни сторонних библиотек с открытым исходным кодом для Windows. 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): объектно-ориентированная платформа для создания традиционных программ Windows (в частности, корпоративных приложений), со сложным пользовательским интерфейсом, включающим кнопки, поля списков, древовидные структуры и другие элементы управления. 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. Дополнительные сведения см. в разделе MFC Desktop Applications. For more information, see MFC Desktop Applications.
Active Template Library (ATL): многофункциональная вспомогательная библиотека для создания компонентов COM. Active Template Library (ATL): A powerful helper library for creating COM components. Для получения дополнительной информации см. ATL COM Desktop Components. For more information, see ATL COM Desktop Components.
C++ AMP (C++ Accelerated Massive Parallelism): библиотека, предоставляющая возможность выполнять высокопроизводительные вычислительные задачи общего характера в графическом процессоре. C++ AMP (C++ Accelerated Massive Parallelism): A library that enables high-performance general computational work on the GPU. Для получения дополнительной информации см. C++ AMP (C++ Accelerated Massive Parallelism). 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. Для получения дополнительной информации см. Concurrency Runtime. For more information, see Concurrency Runtime.
Для многих сценариев программирования Windows также требуется пакет Windows SDK, в который входят файлы заголовков, обеспечивающие доступ к компонентам операционной системы Windows. Many Windows programming scenarios also require the Windows SDK, which includes the header files that enable access to the Windows operating system components. По умолчанию Visual Studio устанавливает Windows SDK как компонент рабочей нагрузки C++ для настольных систем, который позволяет разрабатывать универсальные приложения для Windows. By default, Visual Studio installs the Windows SDK as a component of the C++ Desktop workload, which enables development of Universal Windows apps. Для разработки приложений UWP требуется версия Windows 10 Windows SDK. To develop UWP apps, you need the Windows 10 version of the Windows SDK. Дополнительные сведения см. в разделе пакет SDK для Windows 10. For information, see Windows 10 SDK. (Дополнительные сведения о пакетах Windows SDK для более ранних версий Windows см. в Windows SDK архиве). (For more information about the Windows SDKs for earlier versions of Windows, see the Windows SDK archive).
Программные файлы (x86) \Windows Kit — это расположение по умолчанию для всех версий Windows SDK, которые вы установили. Program Files (x86)\Windows Kits is the default location for all versions of the Windows SDK that you’ve installed.
Другие платформы, например Xbox и Azure, обладают собственными пакетами SDK, которые вам, возможно, потребуется установить. Other platforms such as Xbox and Azure have their own SDKs that you may have to install. Дополнительные сведения см. в Центре разработчика DirectX и в Центре разработчика Azure. For more information, see the DirectX Developer Center and the Azure Developer Center.
средства разработки: Development Tools
Visual Studio включает многофункциональный отладчик для машинного кода, средства статического анализа, графические средства отладки, полнофункциональный редактор кода, поддержку модульных тестов, а также множество других средств и служебных программ. 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. Дополнительные сведения см. в статьях Приступая к разработке с помощью Visual Studioи Общие сведения о разработке C++ в Visual Studio. For more information, see Get started developing with Visual Studio, and Overview of C++ development in Visual Studio.