You are on page 1of 24

Create a traditional Windows Desktop application (C++)

This walkthrough shows how to create a traditional Windows W tym instruktażu pokazano, jak utworzyć tradycyjną aplikację
desktop application in Visual Studio. The example application klasyczną systemu Windows w programie Visual Studio. Przykładowa
you'll create uses the Windows API to display "Hello, Windows aplikacja, którą utworzysz, używa interfejsu API systemu Windows
desktop!" in a window. You can use the code that you develop do wyświetlania komunikatu „Witaj, pulpit systemu Windows!” w
oknie. Możesz użyć kodu opracowanego w tym instruktażu jako
in this walkthrough as a pattern to create other Windows
wzorca do tworzenia innych aplikacji klasycznych systemu Windows.
desktop applications.

The Windows API (also known as the Win32 API, Windows Windows API (znany również jako Win32 API, Windows Desktop API
Desktop API, and Windows Classic API) is a C-language-based i Windows Classic API) to oparta na języku C struktura do tworzenia
framework for creating Windows applications. It has been in aplikacji systemu Windows. Istnieje od lat 80. XX wieku i od
existence since the 1980s and has been used to create Windows dziesięcioleci był używany do tworzenia aplikacji Windows. Bardziej
applications for decades. More advanced and easier-to-program zaawansowane i łatwiejsze do zaprogramowania struktury zostały
frameworks have been built on top of the Windows API. For zbudowane w oparciu o interfejs API systemu Windows. Na przykład
example, MFC, ATL, the .NET frameworks. Even the most modern MFC, ATL, platformy .NET. Nawet najnowocześniejszy kod
Windows Runtime code for UWP and Store apps written in środowiska wykonawczego systemu Windows dla aplikacji UWP i
C++/WinRT uses the Windows API underneath. For more aplikacji Store napisany w języku C ++ / WinRT korzysta z interfejsu
API systemu Windows poniżej. Aby uzyskać więcej informacji na
information about the Windows API, see Windows API Index.
temat interfejsu API systemu Windows, zobacz Indeks interfejsu API
There are many ways to create Windows applications, but the
systemu Windows. Istnieje wiele sposobów tworzenia aplikacji dla
process above was the first. systemu Windows, ale powyższy proces był pierwszy.
Prerequisites Wymagania wstępne

• Komputer z systemem Microsoft Windows 7 lub nowszym. Zalecamy


• A computer that runs Microsoft Windows 7 or later system Windows 10, aby uzyskać najlepsze wrażenia podczas
versions. We recommend Windows 10 for the best programowania.
development experience. • Kopia programu Visual Studio. Aby uzyskać informacje na temat
• A copy of Visual Studio. For information on how to pobierania i instalowania programu Visual Studio, zobacz Instalowanie
programu Visual Studio. Po uruchomieniu instalatora upewnij się, że
download and install Visual Studio, see Install Visual
programowanie pulpitu z obciążeniem C ++ jest zaznaczone. Nie martw się,
Studio. When you run the installer, make sure that jeśli nie zainstalowałeś tego obciążenia podczas instalowania programu
the Desktop development with C++ workload is Visual Studio. Możesz ponownie uruchomić instalator i zainstalować go
checked. Don't worry if you didn't install this workload teraz.
when you installed Visual Studio. You can run the installer
again and install it now.

• Znajomość podstaw korzystania z Visual Studio IDE. Jeśli korzystałeś


• An understanding of the basics of using the Visual Studio wcześniej z aplikacji komputerowych Windows, prawdopodobnie możesz
IDE. If you've used Windows desktop apps before, you can nadążyć.
probably keep up. • Znajomość podstaw języka C ++ wystarczająca do naśladowania. Nie
• An understanding of enough of the fundamentals of the martw się, nie robimy nic zbyt skomplikowanego.
C++ language to follow along. Don't worry, we don't do
anything too complicated.
Create a Windows desktop project Utwórz projekt pulpitu systemu Windows

Wykonaj poniższe czynności, aby utworzyć pierwszy projekt pulpitu


Follow these steps to create your first Windows desktop project.
systemu Windows. W trakcie wpisywania kodu działającej aplikacji
As you go, you'll enter the code for a working Windows desktop komputerowej systemu Windows. Aby wyświetlić dokumentację
application. To see the documentation for your preferred preferowanej wersji programu Visual Studio, użyj kontrolki selektora
version of Visual Studio, use the Version selector control. It's wersji. Znajduje się na górze spisu treści na tej stronie.
found at the top of the table of contents on this page.
Aby utworzyć projekt pulpitu systemu Windows w programie Visual Studio
2019
To create a Windows desktop project in Visual Studio 2019
1. Z menu głównego wybierz Plik> Nowy> Projekt, aby otworzyć okno
1. From the main menu, choose File > New > Project to dialogowe Utwórz nowy projekt.
open the Create a New Project dialog box.
2. At the top of the dialog, set Language to C++, 2. W górnej części okna dialogowego ustaw Język na C ++, ustaw Platformę
set Platform to Windows, and set Project na Windows i ustaw Typ projektu na Pulpit.
type to Desktop.
3. Z przefiltrowanej listy typów projektów wybierz Kreator pulpitu
3. From the filtered list of project types, choose Windows Windows, a następnie wybierz Dalej. Na następnej stronie wprowadź
Desktop Wizard then choose Next. In the next page, nazwę projektu, na przykład DesktopApp.
enter a name for the project, for example, DesktopApp.
4. Choose the Create button to create the project. 4. Wybierz przycisk Utwórz, aby utworzyć projekt.
5. The Windows Desktop Project dialog now appears.
5. Pojawi się okno dialogowe Windows Desktop Project. W obszarze Typ
Under Application type, select Desktop application aplikacji wybierz opcję Aplikacja komputerowa (.exe). W obszarze Opcje
(.exe). Under Additional options, select Empty project. dodatkowe wybierz opcję Pusty projekt. Wybierz OK, aby utworzyć projekt.
Choose OK to create the project.
6. In Solution Explorer, right-click the DesktopApp project, 6. W Eksploratorze rozwiązań kliknij prawym przyciskiem myszy projekt
choose Add, and then choose New Item. DesktopApp, wybierz opcję Dodaj, a następnie wybierz opcję Nowy
element.
7. In the Add New Item dialog box, select C++ File (.cpp). In 7. W oknie dialogowym Dodaj nowy element wybierz opcję Plik C ++ (.cpp).
the Name box, type a name for the file, for W polu Nazwa wpisz nazwę pliku, na przykład HelloWindowsDesktop.cpp.
example, HelloWindowsDesktop.cpp. Choose Add. Wybierz Dodaj.

Your project is now created and your source file is opened in the Twój projekt został utworzony, a plik źródłowy został otwarty w edytorze.
editor. To continue, skip ahead to Create the code. Aby kontynuować, przejdź od razu do tworzenia kodu.
To start a Windows desktop application Aby uruchomić aplikację komputerową Windows

Tak jak każda aplikacja C i aplikacja C ++ musi mieć główną funkcję jako
1. Just as every C application and C++ application must have punkt wyjścia, tak każda aplikacja komputerowa Windows musi mieć
a main function as its starting point, every Windows funkcję WinMain. WinMain ma następującą składnię.
desktop application must have
a WinMain function. WinMain has the following syntax.

Note Uwaga

Czym są te wszystkie dodatkowe słowa, takie jak CALLBACK, HINSTANCE lub


What are all those extra words, such as CALLBACK, or HINSTANCE,
_In_? Tradycyjny interfejs API systemu Windows korzysta z typedefs i makr
or _In_? The traditional Windows API uses typedefs and preprocesora, aby wyodrębnić niektóre szczegóły typów i kodu
preprocessor macros extensively to abstract away some of the specyficznego dla platformy, takie jak konwencje wywoływania, deklaracje
details of types and platform-specific code, such as calling __declspec i pragmy kompilatora. W programie Visual Studio można użyć
conventions, __declspec declarations, and compiler pragmas. In funkcji Szybkie informacje IntelliSense, aby zobaczyć, co definiują te typy
Visual Studio, you can use the IntelliSense Quick Info feature to definicji i makra. Najedź myszą na słowo, które Cię interesuje, lub zaznacz je
i naciśnij Ctrl + K, Ctrl + I, aby wyświetlić małe wyskakujące okienko
see what these typedefs and macros define. Hover your mouse zawierające definicję. Aby uzyskać więcej informacji, zobacz Korzystanie z
over the word of interest, or select it and technologii IntelliSense. Parametry i typy zwracane często używają
press Ctrl+K, Ctrl+I for a small pop-up window that contains
the definition. For more information, see Using IntelliSense. adnotacji SAL, aby pomóc Ci wychwycić błędy programistyczne. Aby uzyskać
Parameters and return types often use SAL Annotations to help więcej informacji, zobacz Korzystanie z adnotacji SAL w celu zmniejszenia
liczby defektów kodu w języku C / C ++.
you catch programming errors. For more information,
see Using SAL Annotations to Reduce C/C++ Code Defects.

2. Windows desktop programs require <windows.h>. <tchar.h> 2. Programy pulpitu Windows wymagają <windows.h>. <tchar.h> definiuje
defines the TCHAR macro, which resolves ultimately to wchar_t if makro TCHAR, które ostatecznie jest rozpoznawane jako wchar_t, jeśli
symbol UNICODE jest zdefiniowany w twoim projekcie, w przeciwnym razie
the UNICODE symbol is defined in your project, otherwise it jest rozpoznawany jako char. Jeśli zawsze budujesz z włączonym UNICODE,
resolves to char. If you always build with UNICODE enabled, you nie potrzebujesz TCHAR i możesz po prostu użyć bezpośrednio wchar_t.
don't need TCHAR and can just use wchar_t directly.

3. Along with the WinMain function, every Windows desktop 3. Oprócz funkcji WinMain każda aplikacja komputerowa systemu Windows
application must also have a window-procedure function. This musi mieć również funkcję procedury okna. Ta funkcja ma zwykle nazwę
function is typically named WndProc, but you can name it whatever WndProc, ale możesz ją nazwać dowolnie. WndProc ma następującą
you like. WndProc has the following syntax. składnię.
In this function, you write code to handle messages that the W tej funkcji piszesz kod obsługujący komunikaty, które aplikacja odbiera z
application receives from Windows when events occur. For example, if systemu Windows, gdy wystąpią zdarzenia. Na przykład, jeśli użytkownik
a user chooses an OK button in your application, Windows will send a wybierze przycisk OK w twojej aplikacji, system Windows wyśle do ciebie
message to you and you can write code inside your WndProc function wiadomość i możesz napisać kod wewnątrz funkcji WndProc, która wykona
wszystko, co jest odpowiednie. Nazywa się to obsługą zdarzenia.
that does whatever work is appropriate. It's called handling an event.
Obsługujesz tylko zdarzenia, które są istotne dla Twojej aplikacji.
You only handle the events that are relevant for your application.
Aby dodać funkcjonalność do funkcji WinMain
To add functionality to the WinMain function

1. In the WinMain function, you populate a structure of 1. W funkcji WinMain wypełniasz strukturę typu WNDCLASSEX. Struktura
type WNDCLASSEX. The structure contains information zawiera informacje o oknie: między innymi ikonę aplikacji, kolor tła okna,
about the window: the application icon, the background nazwę wyświetlaną na pasku tytułowym. Co ważne, zawiera wskaźnik
funkcji do procedury okna. Poniższy przykład przedstawia typową strukturę
color of the window, the name to display in the title bar,
WNDCLASSEX.
among other things. Importantly, it contains a function
pointer to your window procedure. The following example
shows a typical WNDCLASSEX structure.
2. Register the WNDCLASSEX with Windows so that it knows about your 2. Zarejestruj WNDCLASSEX w systemie Windows, aby wiedział o Twoim
window and how to send messages to it. Use oknie i jak wysyłać do niego wiadomości. Użyj funkcji RegisterClassEx i
the RegisterClassEx function and pass the window class structure as przekaż strukturę klasy okna jako argument. Makro _T jest używane,
an argument. The _T macro is used because we use the TCHAR type. ponieważ używamy typu TCHAR.

3. Now you can create a window. Use the CreateWindow function. 3. Teraz możesz utworzyć okno. Użyj funkcji CreateWindow.
This function returns an HWND, which is a handle to a window. A Ta funkcja zwraca HWND, który jest uchwytem do okna. Uchwyt
handle is somewhat like a pointer that Windows uses to keep przypomina nieco wskaźnik, którego system Windows używa do śledzenia
otwartych okien. Aby uzyskać więcej informacji, zobacz Typy danych
track of open windows. For more information, see Windows systemu Windows.
Data Types.

4. At this point, the window has been created, but we still need 4. W tym momencie okno zostało utworzone, ale nadal musimy powiedzieć
to tell Windows to make it visible. That's what this code does: systemowi Windows, aby je pokazał. To właśnie robi ten kod:

The displayed window doesn't have much content because you Wyświetlane okno nie ma zbyt dużej zawartości, ponieważ nie
haven't yet implemented the WndProc function. In other words, zaimplementowałeś jeszcze funkcji WndProc. Innymi słowy, aplikacja nie
obsługuje jeszcze komunikatów wysyłanych do niej przez system Windows.
the application isn't yet handling the messages that Windows is
now sending to it.

5. To handle the messages, we first add a message loop to 5. Aby obsłużyć komunikaty, najpierw dodajemy pętlę komunikatów, aby
listen for the messages that Windows sends. When the nasłuchiwać komunikatów wysyłanych przez system Windows. Gdy
application receives a message, this loop dispatches it to aplikacja odbiera komunikat, ta pętla wysyła go do funkcji WndProc w celu
obsługi. Pętla komunikatów przypomina następujący kod.
your WndProc function to be handled. The message loop
resembles the following code.
At this point, the WinMain function should resemble the following code. / W tym momencie funkcja WinMain powinna przypominać następujący

kod.
To add functionality to the WndProc function Aby dodać funkcjonalność do funkcji WndProc

1. To enable the WndProc function to handle the messages that 1. Aby umożliwić funkcji WndProc obsługę komunikatów odbieranych
the application receives, implement a switch statement. przez aplikację, zaimplementuj instrukcję switch.

Ważną wiadomością do obsłużenia jest wiadomość WM_PAINT.


One important message to handle is the WM_PAINT message.
Aplikacja otrzymuje komunikat WM_PAINT, gdy część wyświetlanego
The application receives the WM_PAINT message when part of its
okna musi zostać zaktualizowana. Zdarzenie może wystąpić, gdy
displayed window must be updated. The event can occur when
użytkownik przesunie okno przed okno, a następnie ponownie je
a user moves a window in front of your window, then moves it odsunie. Twoja aplikacja nie wie, kiedy wystąpią te zdarzenia. Tylko
away again. Your application doesn't know when these events system Windows wie, więc powiadamia Twoją aplikację komunikatem
occur. Only Windows knows, so it notifies your app with WM_PAINT. Kiedy okno jest wyświetlane po raz pierwszy, należy je
a WM_PAINT message. When the window is first displayed, all of it zaktualizować.
must be updated.

To handle a WM_PAINT message, first call BeginPaint, then handle Aby obsłużyć komunikat WM_PAINT, najpierw wywołaj BeginPaint,
all the logic to lay out the text, buttons, and other controls in następnie obsłuż całą logikę, aby rozmieścić tekst, przyciski i inne
the window, and then call EndPaint. For the application, the kontrolki w oknie, a następnie wywołaj EndPaint. W przypadku
logic between the beginning call and the ending call displays aplikacji logika między wywołaniem początkowym a wywołaniem
końcowym wyświetla ciąg „Hello, pulpit Windows!” w oknie. W
the string "Hello, Windows desktop!" in the window. In the
poniższym kodzie funkcja TextOut służy do wyświetlania ciągu.
following code, the TextOut function is used to display the
string.
HDC in the code is a handle to a device context, which is used to HDC w kodzie jest uchwytem do kontekstu urządzenia, który jest
draw in the window's client area. Use używany do rysowania w obszarze roboczym okna. Użyj funkcji
the BeginPaint and EndPaint functions to prepare for and BeginPaint i EndPaint, aby przygotować i zakończyć rysowanie w
complete the drawing in the client area. BeginPaint returns a obszarze roboczym. BeginPaint zwraca uchwyt do kontekstu
urządzenia wyświetlającego używanego do rysowania w obszarze
handle to the display device context used for drawing in the
roboczym; EndPaint kończy żądanie malowania i zwalnia kontekst
client area; EndPaint ends the paint request and releases the
urządzenia.
device context.
An application typically handles many other messages. For Aplikacja zazwyczaj obsługuje wiele innych komunikatów. Na
example, WM_CREATE when a window is first created, przykład WM_CREATE, gdy okno jest tworzone po raz pierwszy, i
and WM_DESTROY when the window is closed. The following code WM_DESTROY, gdy okno jest zamknięte. Poniższy kod przedstawia
shows a basic but complete WndProc function. podstawową, ale kompletną funkcję WndProc.
Build the code Zbuduj kod

As promised, here's the complete code for the working Zgodnie z obietnicą, oto pełny kod działającej aplikacji.
application.
Aby zbudować ten przykład
To build this example
Usuń kod, który wprowadziłeś w HelloWindowsDesktop.cpp w
Delete any code you've entered in HelloWindowsDesktop.cpp in
edytorze. Skopiuj ten przykładowy kod, a następnie wklej go do
the editor. Copy this example code and then paste it HelloWindowsDesktop.cpp:
into HelloWindowsDesktop.cpp:
On the Build menu, choose Build Solution. The results of the W menu Kompiluj wybierz opcję Kompiluj rozwiązanie. Wyniki
compilation should appear in the Output window in Visual Studio. kompilacji powinny pojawić się w oknie danych wyjściowych w
programie Visual Studio.
To run the application, press F5. A window that contains the text "Hello, Aby uruchomić aplikację, naciśnij klawisz F5. Okno
Windows desktop!" should appear in the upper-left corner of the zawierające tekst „Hello, Windows desktop!” powinien
display. pojawić się w lewym górnym rogu wyświetlacza.

Congratulations! You've completed this walkthrough and built a Gratulacje! Ukończyłeś ten przewodnik i utworzyłeś
traditional Windows desktop application. tradycyjną aplikację komputerową dla systemu Windows.

Opracowanie: Małgorzata Popko

Źródło: https://docs.microsoft.com/en-us/cpp/windows/walkthrough-creating-windows-desktop-applications-cpp?view=msvc-160

You might also like