С windows program example

Module 1. Your First Windows Program

In this module, we will write a minimal Windows desktop program. All it does is create and show a blank window. This first program contains about 50 lines of code, not counting blank lines and comments. It will be our starting point; later we’ll add graphics, text, user input, and other features.

If you are looking for more details on how to create a traditional Windows desktop application in Visual Studio, check out Walkthrough: Create a traditional Windows Desktop application (C++).

Here is the complete code for the program:

You can download the complete Visual Studio project from Windows Hello World Sample.

It may be useful to give a brief outline of what this code does. Later topics will examine the code in detail.

  1. wWinMain is the program entry point. When the program starts, it registers some information about the behavior of the application window. One of the most important items is the address of a function, named WindowProc in this example. This function defines the behavior of the window—its appearance, how it interacts with the user, and so forth.
  2. Next, the program creates the window and receives a handle that uniquely identifies the window.
  3. If the window is created successfully, the program enters a while loop. The program remains in this loop until the user closes the window and exits the application.

Notice that the program does not explicitly call the WindowProc function, even though we said this is where most of the application logic is defined. Windows communicates with your program by passing it a series of messages. The code inside the while loop drives this process. Each time the program calls the DispatchMessage function, it indirectly causes Windows to invoke the WindowProc function, once for each message.

Примеры приложений для 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
Читайте также:  Driver overran stack buffer windows 10 что за ошибка

Скачать код 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.

Читайте также:  Ошибка windows system32 rstrui exe

Обратная связь, вопросы и сообщения о проблемах 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.

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.

Читайте также:  What is samba share in linux

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.

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