Заголовочный файл windows h

The `windows.h` header file in C++ provides the necessary declarations for Windows API functions, allowing programmers to create and manage windows, handle messages, and utilize various system features.

Here’s an example code snippet demonstrating how to create a simple Windows application using `windows.h`:

#include <windows.h>

LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
    switch (uMsg) {
        case WM_DESTROY:
            PostQuitMessage(0);
            return 0;
        case WM_PAINT:
            {
                PAINTSTRUCT ps;
                HDC hdc = BeginPaint(hwnd, &ps);
                FillRect(hdc, &ps.rcPaint, (HBRUSH)(COLOR_WINDOW + 1));
                EndPaint(hwnd, &ps);
            }
            return 0;
    }
    return DefWindowProc(hwnd, uMsg, wParam, lParam);
}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE, LPSTR, int nShowCmd) {
    const char CLASS_NAME[]  = "Sample Window Class";
    
    WNDCLASS wc = {};
    wc.lpfnWndProc   = WindowProc;
    wc.hInstance     = hInstance;
    wc.lpszClassName = CLASS_NAME;

    RegisterClass(&wc);

    HWND hwnd = CreateWindowEx(0, CLASS_NAME, "Hello Windows", WS_OVERLAPPEDWINDOW, 
        CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, 
        NULL, NULL, hInstance, NULL);
    
    ShowWindow(hwnd, nShowCmd);
    
    MSG msg;
    while (GetMessage(&msg, NULL, 0, 0)) {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }

    return 0;
}

Understanding `windows.h`

What is `windows.h`?

The `windows.h` header file is a fundamental component of the Windows API, which provides a rich set of functions, data types, and constants that allow developers to create applications that can interact with the Windows operating system at a high level. This header is essential for any application that requires functionalities tied to Windows, such as GUI creation, file handling, or system-level programming.

Why Use `windows.h`?

Using `windows.h` allows you to harness the full power of Windows OS functionalities. This means you can:

  • Create and manage windows for your applications.
  • Handle user input from keyboard and mouse actions.
  • Create multi-threaded applications, allowing for more efficient processing.
  • Access system resources such as files, memory, and other operating system components.

Common use cases include GUI applications, background services, and games that need to interact with the operating system.

Mastering Llama.cpp: Your Guide for Windows Users

Mastering Llama.cpp: Your Guide for Windows Users

Setting Up Your Development Environment

Choosing the Right Compiler

When working with `cpp windows.h`, it’s vital to choose the right development environment. Popular options include:

  • Visual Studio: A feature-rich IDE with comprehensive debugging tools. It’s widely accepted in the industry for Windows development.
  • MinGW: A minimalist option that provides a GCC-based environment for Windows programming. This is suitable for those who prefer lightweight setups.

Configuring the Project

Once a compiler is chosen, you can create a new C++ project. Ensure that you include the `windows.h` header at the top of your source file to utilize its functions and features:

#include <windows.h>

C++ Windows.h Documentation: A Quick Reference Guide

C++ Windows.h Documentation: A Quick Reference Guide

Core Components of `windows.h`

Data Types and Constants

Common Data Types

  • HANDLE: This opaque data type represents a reference to an object. It is crucial for various Windows API functions.
  • DWORD: This is an unsigned 32-bit integer, typically used to represent various bits of information, such as error codes or process status.
  • LPCTSTR: A pointer to a constant string. This data type is used across many API functions to handle string inputs.

Constants and Macros in `windows.h`

Constants such as WIN32_API, NULL, TRUE, and FALSE are often utilized throughout your code, serving as standard values and enhancing readability.

Structures Defined in `windows.h`

Overview of Key Structures

  • MSG: A structure that holds message information. Essential for handling events in the message loop.
  • WNDCLASS: This structure defines the window class properties. It allows you to specify how your windows will behave and appear.

Mastering C++ Windows: A Quick Guide to Get You Started

Mastering C++ Windows: A Quick Guide to Get You Started

Functions Provided by `windows.h`

Creating Windows

The Message Loop

Understanding the message loop is critical for any GUI application because it processes all incoming messages from the operating system. The message loop typically looks like this:

MSG msg;
while (GetMessage(&msg, NULL, 0, 0)) {
    TranslateMessage(&msg);
    DispatchMessage(&msg);
}

In this loop:

  • `GetMessage` retrieves messages from the queue.
  • `TranslateMessage` translates keyboard messages into character messages.
  • `DispatchMessage` sends the message to the window procedure.

Handling Windows Messages

Understanding Windows Messages

Windows messages are notifications sent to applications regarding events, such as user input or system requests. Each message has a unique identifier and carries information about the event.

Example of Handling Messages

To process these messages, you define a window procedure that handles different types of messages. Here’s an example:

LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
    switch (uMsg) {
        case WM_DESTROY:
            PostQuitMessage(0);
            return 0;
        case WM_PAINT:
            // Handle window painting
            break;
        // Additional cases for other messages
    }
    return DefWindowProc(hwnd, uMsg, wParam, lParam);
}

This function will manage various messages such as window destruction and painting, enabling you to create responsive applications.

CPP Institute: Your Quick Guide to Mastering C++ Commands

CPP Institute: Your Quick Guide to Mastering C++ Commands

Working with the Windows API

Creating and Managing Windows

Window Creation

Creating a window is one of the first steps in building a GUI application. The `CreateWindowEx` function is used for this purpose. Here’s its basic structure followed by an example:

HWND hwnd = CreateWindowEx(
    0, 
    CLASS_NAME, 
    "Sample Window", 
    WS_OVERLAPPEDWINDOW,
    CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
    NULL, NULL, hInstance, NULL
);

In this code:

  • `CLASS_NAME` is the name of the window class.
  • The window style and dimensions are specified, allowing you to customize the appearance and behavior of your window.

Interacting with Windows

Basic User Input

To read user input, you can use `GetMessage()`, which retrieves messages from the application’s message queue. Below is a simple input handling demonstration:

while(GetMessage(&msg, NULL, 0, 0)) {
    TranslateMessage(&msg);
    DispatchMessage(&msg);
}

This snippet continuously checks for user activity and processes the messages accordingly.

Update Windows C++: A Quick Guide to Essentials

Update Windows C++: A Quick Guide to Essentials

Advanced Topics

Multi-threading with `windows.h`

Understanding Threads

Threads allow applications to perform multiple tasks simultaneously. Using the Windows API, you can create threads to improve the performance of your application.

To create a thread, use the `CreateThread` function, as shown in this example:

DWORD WINAPI MyThreadFunction(LPVOID lpParam) {
    // Thread code here
    return 0;
}

This function will run in a separate thread, allowing your program to execute concurrent operations.

Working with System Resources

Memory Management

Efficient memory management is vital for any application. Windows API provides functions like `HeapAlloc` and `GlobalAlloc` for memory allocation. Using them, you can allocate and free memory dynamically:

HANDLE hHeap = GetProcessHeap();
LPVOID lpvMemory = HeapAlloc(hHeap, HEAP_ZERO_MEMORY, size);

This snippet allocates memory from the process heap, ready for your application’s use.

File Operations

To interact with files, you can use functions such as `CreateFile`, `ReadFile`, and `WriteFile`. Here’s a basic code example for opening a file and reading its content:

HANDLE hFile = CreateFile("example.txt", GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile != INVALID_HANDLE_VALUE) {
    DWORD bytesRead;
    char buffer[100];
    ReadFile(hFile, buffer, sizeof(buffer), &bytesRead, NULL);
    CloseHandle(hFile);
}

This example demonstrates how to open a file and read its content into a buffer while managing errors appropriately.

Setup Windows C++ Dev Env: Your Quickstart Guide

Setup Windows C++ Dev Env: Your Quickstart Guide

Conclusion

Summary of Key Points

In this guide, we’ve explored the breadth of functionalities offered by `windows.h`. You learned about core data types, constants, structures, and essential functions for creating and managing windows and input handling. Moreover, we delved into advanced topics like multi-threading and file operations, providing a solid foundation for developing Windows applications using C++.

Further Reading and Resources

To expand your knowledge further, consider referring to:

  • Books on Windows API Programming
  • Online tutorials and documentation such as Microsoft’s official documentation on the Windows API.

Encouragement to Practise

Practice makes perfect! The best way to become proficient in using `windows.h` is through hands-on experience. Start building small applications, incrementally adding more complexity as you feel comfortable with the API.

Llama.cpp Download: Your Quick Guide to Getting Started

Llama.cpp Download: Your Quick Guide to Getting Started

FAQs

Common Questions About `windows.h`

What is the purpose of `windows.h`?
`windows.h` serves as the gateway for developers to access the numerous functionalities of the Windows API, enabling them to create robust applications that interface with the operating system.

How do I handle errors in Windows API?
Error handling can be done through the use of `GetLastError()` to retrieve error codes, allowing you to implement error handling routines in your code.

Can I use `windows.h` in cross-platform applications?
`windows.h` is specific to Windows, so if you’re looking to develop cross-platform applications, consider using libraries like Qt or wxWidgets that abstract away the platform-specific details.

The windows.h header file is a fundamental header file for the Microsoft Windows operating system. It includes declarations for a wide range of functions and data types used in Windows programming. Here’s a basic example demonstrating the usage of windows.h for creating a simple Windows GUI application:

Contents

  • 1 C Library – windows.h File
  • 2 Predefined functions of C Library – windows.h
    • 2.1 C Library – windows.h predefined functions List
    • 2.2 Note
  • 3 sleep() in C Library – windows.h
  • 4 Sleep() Example-1
    • 4.1 Code
    • 4.2 Explanation
  • 5 Sleep() Example-2
  • 6 Slep() Example-3
  • 7 Next
    • 7.1 Explore more
#include <windows.h>

// Function prototype for the window procedure
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);

int main() {
    // Get the handle to the instance of this application
    HINSTANCE hInstance = GetModuleHandle(NULL);

    // Create the main window
    HWND hwnd = CreateWindowEx(
        0,                              // Optional window styles
        L"WindowClass",                 // Window class
        L"My First Window",             // Window title
        WS_OVERLAPPEDWINDOW,            // Window style

        // Size and position
        CW_USEDEFAULT, CW_USEDEFAULT, 800, 600,

        NULL,       // Parent window    
        NULL,       // Menu
        hInstance,  // Instance handle
        NULL        // Additional application data
    );

    // Display the window
    ShowWindow(hwnd, SW_SHOWNORMAL);

    // Enter the message loop
    MSG msg;
    while (GetMessage(&msg, NULL, 0, 0)) {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }

    return 0;
}

// The window procedure
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
    switch (uMsg) {
        case WM_DESTROY:
            PostQuitMessage(0);
            return 0;
        default:
            return DefWindowProc(hwnd, uMsg, wParam, lParam);
    }
    return 0;
}

This above example creates a simple window using the Windows API. The WindowProc function is the window procedure, which handles messages for the main window. The CreateWindowEx function creates the main window, and the ShowWindow function displays it. The program then enters a message loop (while (GetMessage...)) where it waits for and processes messages until the user closes the window.

Remember that this is just a basic example, and real-world Windows applications will involve more complexities and considerations. Additionally, GUI programming in Windows often involves using additional libraries, such as MFC (Microsoft Foundation Classes) or newer frameworks like WinUI.

Predefined functions of C Library – windows.h

The windows.h header in Windows programming provides declarations for various functions, data types, and constants used in Windows API. Here are some commonly used predefined functions available in windows.h:

C Library – windows.h predefined functions List

Function Category Function Note
Window Management Functions: CreateWindowEx()  Creates an extended window.
ShowWindow()  Sets the specified window’s show state.
UpdateWindow()  Updates the client area of the specified window.
DestroyWindow()  Destroys the specified window.
DefWindowProc()  The default window procedure for window messages not processed by your window procedure.
Message Handling Functions: GetMessage()  Retrieves a message from the calling thread’s message queue.
TranslateMessage()  Translates virtual-key messages into character messages.
DispatchMessage()  Dispatches a message to a window procedure.
PostQuitMessage()  Posts a quit message to the message queue.
Thread Functions: CreateThread()  Creates a new thread for parallel execution.
GetCurrentThreadId()  Retrieves the thread identifier of the calling thread.
Synchronization Functions: CreateMutex()  Creates or opens a named or unnamed mutex object.
CreateEvent()  Creates or opens a named or unnamed event object.
WaitForSingleObject()  Waits until the specified object is in the signaled state.
ReleaseMutex()  Releases ownership of the specified mutex object.
File and File I/O Functions: CreateFile()  Creates or opens a file or I/O device.
ReadFile, WriteFile()  Reads from or writes to a file or I/O device.
CloseHandle()  Closes an open object handle.
Memory Management Functions: VirtualAlloc()  Reserves or commits a region of memory within the virtual address space of a specified process.
VirtualFree()  Releases, decommits, or releases and decommits a region of memory.
Time Functions: GetSystemTime()  Retrieves the current system date and time.
Sleep()  Suspends the execution of the current thread for a specified interval.
Miscellaneous Functions: MessageBox()  Displays a modal dialog box that contains a system icon, a set of buttons, and a brief application-specific message.
GetLastError()  Retrieves the calling thread’s last-error code value.
LoadLibrary, GetProcAddress()  Loads a dynamic-link library (DLL) into the calling process’s address space.
C Library – windows.h predefined functions

Note

These are just a few examples, and there are many more functions provided by Windows.h for various purposes. When working with Windows programming, documentation is an essential resource to understand and use these functions effectively. The next section only discussed Sleep() function.

sleep() in C Library – windows.h

if you have the following questions like

  • How to use the delay function in C?
  • How to use the C program delay function in Windows?

Here is your solution,

If you wanna use the delay feature, you can use the Sleep() function in the Windows platform, based on the compiler the Sleep() will call in different library files(Some times Sleep function will be winbase.h, Sometimes different). Don’t worry about that, if you include the windows.h the header file, that will be taken care of. why because everything all the sleep function necessary headers are already included in windows.h the file.

  • Rule-1: You should add the header file #include <windows.h>
  • Rule-2: Sleep() function first letter always Uppercase, if you declare in the small case the compiler might generate error “Undefined reference to sleep”.
  • Rule-3: Sleep() function argument (Milliseconds) should be unsigned long type. If your call [Example : Sleep("ArunEworld")] Sleep() function with char type or other types, the compiler will generate an Error.

Please note that the sleep function may not be very precise, and the actual delay could be slightly longer due to system-related factors. If you need more precise timing, you might want to explore other methods or libraries for that purpose.

Sleep() Example-1

Code

#include <stdio.h>
#include <unistd.h>  // for sleep function

int main() {
    printf("ArunEworld: This is before the delay.\n");

    // Sleep for 3 seconds
    sleep(3);

    printf("ArunEworld: This is after the delay.\n");

    return 0;
}

Explanation

In this above example, the program will print the first message, then pause for 3 seconds using sleep(3), and finally print the second message after the delay.

Remember to include the <unistd.h> header for the sleep function to work.

Sleep() Example-2

The below code will be printed ArunEworld website every 1 second

#include <stdio.h>
#include <Windows.h>
int main() 
{
	while(1)
	{
		//print the aruneworld website address
		printf("www.ArunEworld.com.\r\n");
		
		//make a delay every in millisecond
		Sleep(1000);
	}
	
	return 0; 
}

Slep() Example-3

#include <stdio.h>
#include <Windows.h>
int main() 
{
	while(1)
	{
		//print the aruneworld website address
		printf("www.ArunEworld.com.\r\n");
		
		//make a delay every in millisecond
		Sleep("ArunEworld");
	}
	
	return 0; 
}

The above code will show the Error like "[Note] expected 'DWORD' but argument is of type 'char *'". Why because Sleep() the argument should be unsigned long. here ‘ArunEworld' is a charter pointer.

Refer to the C Examples – Time Delay


Next

C – Basic
C – Operator
C – Decision making, Branching, Looping
C – Functions
C – Storage Class
C – Extern
C – Array
C – Pointer
C – Memory Allocation
C – Structure
C – Union
C – Structure and Union
C – Macros
C – Preprocessor and Macros
C – File Management
C – Coding Standard
C – Compilers
C – Compiling Process
C File Management
C Library
C Example

Hits (since 2024-Jan-26) — 17,909

Материал из РУВИКИ — свободной энциклопедии

Стандартная библиотека
языка программирования С
  • assert.h
  • complex.h (C99)
  • ctype.h
  • errno.h
  • fenv.h (C99)
  • float.h
  • inttypes.h (C99)
  • iso646.h
  • limits.h
  • locale.h
  • math.h
  • setjmp.h
  • signal.h
  • stdalign.h (C11)
  • stdarg.h
  • stdatomic.h (C11)
  • stdbool.h (C99)
  • stddef.h
  • stdint.h (C99)
  • stdio.h
  • stdlib.h
  • stdnoreturn.h (C11)
  • string.h
  • tgmath.h
  • threads.h (C11)
  • time.h
  • uchar.h (C11)
  • wchar.h
  • wctype.h

windows.h — Windows-специфичный заголовочный файл языка программирования С, в котором объявляются функции, предоставляющие интерфейс доступа к Windows API[1]. В случае, если в файле используются и другие заголовочные файлы, связанные с Windows API, windows.h должен быть первым[2].

  • excpt.h — обработка исключений
  • stdarg.h — функции с сигнатурами аргументов переменной длины (стандартный заголовочный файл C)
  • windef.h — различные макросы и типы
  • winnt.h — различные макросы и типы для Windows NT
  • basetsd.h — различные типы
  • guiddef.h — тип GUID
  • ctype.h — символьные типы (стандартный заголовочный файл C)
  • string.h — строчные типы и их буферы (стандартный заголовочный файл C)
  • winbase.h — kernel32.dll, advapi32.dll: функции ядра
  • winerror.h — Коды ошибок для Windows
  • wingdi.h — GDI
  • winuser.h — user32.dll
  • winnls.h — локализация
  • wincon.h — консольные службы
  • winver.h — информация о версии
  • winreg.h — реестр Windows
  • winnetwk.h — сетевые службы
  • winsvc.h — диспетчер управления службами
  • imm.hhh — IME (редактор методов ввода)

Дополнительные заголовки[править | править код]

  • cderr.h — CommDlgExtendedError коды ошибок функций
  • commdlg.h — Common Dialog Boxes
  • dde.h — DDE
  • ddeml.h — библиотека управления DDE
  • dlgs.h — набор констант для Common Dialog Boxes
  • lzexpand.h — алгоритм сжатия LZ77
  • mmsystem.h — Windows Multimedia
  • nb30.h — NetBIOS
  • rpc.h — удалённый вызов процедур
  • shellapi.h — Windows Shell API
  • wincrypt.h — криптографическое API
  • winperf.h — измерение производительности
  • winresrc.h — ресурсы
  • winsock.h — Winsock (сокеты Windows), версия 1.1
  • winspool.h — управление очередью печати
  • winbgim.h — стандартная графическая библиотека

OLE и COM[править | править код]

  • ole2.h — OLE
  • objbase.h — COM
  • oleauto.h — OLE Automation
  • olectlid.h — различные определения для GUID

В данном примере рассматривается создание нового окна[3].

#include <windows.h>
 
LPSTR szClassName = "MyClass";
HINSTANCE hInstance;
LRESULT __stdcall MyWndProc(HWND, UINT, WPARAM, LPARAM);
 
int __stdcall WinMain(HINSTANCE hInst, HINSTANCE hPrevInstance, LPSTR szCmdLine, int iCmdShow)
{
    WNDCLASS wnd;
    MSG msg;
    HWND hwnd;
 
    hInstance = hInst;
         
    wnd.style = CS_HREDRAW | CS_VREDRAW; //объяснение ниже
    wnd.lpfnWndProc = MyWndProc;
    wnd.cbClsExtra = 0;
    wnd.cbWndExtra = 0;
    wnd.hInstance = hInstance;
    wnd.hIcon = LoadIcon(NULL, IDI_APPLICATION); //иконка по умолчанию
    wnd.hCursor = LoadCursor(NULL, IDC_ARROW);   //курсор по умолчанию
    wnd.hbrBackground = (HBRUSH)(COLOR_BACKGROUND+1);
    wnd.lpszMenuName = NULL;                     //без меню
    wnd.lpszClassName = szClassName;
 
    if(!RegisterClass(&wnd))                     //зарегистрировать WNDCLASS
    {
        MessageBox(NULL, "This Program Requires Windows NT", 
                         "Error", MB_OK);
        return 0;
    }
 
    hwnd = CreateWindow(szClassName,
                        "Window Title",
                        WS_OVERLAPPEDWINDOW, //оформление окна поумолчанию
                        CW_USEDEFAULT,
                        CW_USEDEFAULT,       //координаты по умолчанию
                        CW_USEDEFAULT,
                        CW_USEDEFAULT,       //ширина и высота по умолчанию
                        NULL,                //без родительского окна
                        NULL,                //без меню
                        hInstance,
                        NULL);               //без параметра
    ShowWindow(hwnd, iCmdShow);              //отрисовать окно на экране
    UpdateWindow(hwnd);             //окно должно правильно обновляться
 
    while(GetMessage(&msg, NULL, 0, 0))      //цикл сообщений
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
    return msg.wParam;
}
 
LRESULT __stdcall MyWndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
    switch(msg)
    {
        case WM_DESTROY:
            PostQuitMessage(0);
            return 0;
    }
    return DefWindowProc(hwnd, msg, wParam, lParam);
}
  • Microsoft Windows library files
  1. Richard Raposa. Understanding C++ for MFC. — ISBN 148228068X.
  2. Charles Petzold. Programming Windows. — 1998. — ISBN 0735646031.
  3. Module 1. Your First Windows Program — Win32 apps | Microsoft Docs
  • Документация Windows API (англ.)

From Wikibooks, open books for an open world

The primary C header file for accessing the Win32 API is the <windows.h> header file. To make a Win32 executable, the first step is to include this header file in your source code. The windows.h header file should be included before any other library include, even the C standard library files such as stdio.h or stdlib.h. This is because the windows.h file includes macros and other components that may modify, extend, or replace things in these libraries. This is especially true when dealing with UNICODE, because windows.h will cause all the string functions to use UNICODE instead. Also, because many of the standard C library functions are already included in the Windows kernel, many of these functions will be available to the programmer without needing to load the standard libraries. For example, the function sprintf is included in windows.h automatically.

There are a number of header files that are automatically included with windows.h. Many of these files cannot simply be included by themselves, because of dependencies. The windows.h header file is actually a relatively small file, that provides conditional inclusion for a number of other header files, definitions of a few important macros, etc.


For a list of child header files visit———-

http://en.wikipedia.org/wiki/Windows.h

This section will talk about some other interesting header files and libraries that can be included with your project, but which are not included by default with windows.h.

This section will briefly detail some of the changes that the user can make in the windows.h structure at compile time using macros.

The WIN32_LEAN_AND_MEAN macro causes several of the child headers to not be included in the build. This can help to speed up the compilation process.

These macros, which we will discuss later, can generally be used interchangeably, but are frequently both defined together. These cause the program to be compiled with UTF-16 encoded strings instead of ASCII encoded strings. UTF-16 is one internationalized encoding based on the UNICODE standard and allows for more characters than the American ASCII encoding, although UTF-8 is often preferred in modern programming.

You must set these to a number greater or equal to 0x500 or you will not get some of the useful functions that are in Windows 2000 (and thus in any modern Windows) but were not in Windows 98.

  • Handles and Data Types

Win32 API (далее WinAPI) – это набор функций (API – Application Programming Interface), работающих под управлением ОС Windows. Они содержатся в библиотеке windows.h.

С помощью WinAPI можно создавать различные оконные процедуры, диалоговые окна, программы и даже игры. Эта, скажем так, библиотека является базовой в освоении программирования Windows Forms, MFC, потому что эти интерфейсы являются надстройками этой библиотеки. Освоив её, Вы без труда будете создавать формы, и понимать, как это происходит.

Не будем внедряться в теорию. Начнём с того, как создать этот проект в MVS, а в конце статьи будет разобран простой пример.

Итак. Сначала открываем Visual Studio, затем, нажимаем на вкладку «Файл», далее «Создать проект»:

1

Затем, в раскрывающемся списке Visual C++ выбираем пункт Win32, там и будет «Проект Win32». Щелкаем по нему:

Безымянный

Вводим название проекта, указываем путь и нажимаем «ОК». Далее будет написано: «Добро пожаловать в мастер приложения Win32». Нажимаем далее. По-умолчанию у надписи «Пустой проект» галочка отсутствует. Нам нужно её поставить и убедиться, что у нас «Тип Приложения» — Приложение Windows. Если всё верно, нажимаем – «Готово».

2.

У нас должен быть пустой проект такого вида:

3

Ну а теперь начнём писать простую программу, которая традиционно будет выводить на экран надпись: «Привет, Мир!!!».

Естественно, к проекту нужно добавить файл типа «имя».cpp. Кликаем по «Файлы исходного кода» правой кнопкой мыши, в раскрывающемся списке выбираем вкладку – «Добавить», далее «Создать элемент…». В результате у нас должно появиться такое окно:

4

Выбираем «Файл С++», вводим имя, нажимаем «Добавить». Затем открываем этот файл и вставляем в него такой код (подробности далее):

#include <windows.h> // заголовочный файл, содержащий функции API

// Основная функция - аналог int main() в консольном приложении:
int WINAPI WinMain(HINSTANCE hInstance, // дескриптор экземпляра приложения
                   HINSTANCE hPrevInstance, // в Win32 не используется
                   LPSTR lpCmdLine, // нужен для запуска окна в режиме командной строки
                   int nCmdShow) // режим отображения окна
{
        // Функция вывода окна с кнопкой "ОК" на экран (о параметрах позже)
        MessageBox(NULL, L"Привет, мир!!!", L"Оконная процедура", MB_OK);
        return NULL; // возвращаем значение функции
}

Результат должен быть таким:

5

Теперь остановимся поподробнее на коде программы.

В первой строке мы подключаем заголовочный файл windows.h. В нём содержатся все необходимые «апишные» функции. Здесь всё понятно.

В 4-7 строках у нас описание функции int WINAPI WinMain().

Квалификатор WINAPI, нужен для функции WinMain всегда. Просто запомните это. WinMain – название функции. Она имеет четыре параметра. Первый из них – HINSTANCE hInstance (строка 4). hInstance является дескриптором экземпляра окна (это некий код оконной процедуры, идентификатор, по которой ОС будет отличать её от остальных окон). Через него можно обращаться к окну в процессе работы в других функциях (об этом позже), что-либо менять в параметрах окна.  HINSTANCE является одним из многочисленных типов данных определенных в WinAPI, таким же как int, например.  А запись HINSTANCE hInstance говорит нам о том, что мы создаём новую переменную типа HINSTANCE с названием hInstance.

О типах данным мы поговорим позже, поэтому переходим к следующему параметру: HINSTANCE hPrevInstance (строка 5). Как написано в комментариях, в Win32 он не используется, так как он создан для 3.x разрядной системы, из предыдущего понятно, что это дескриптор экземпляра окна. Далее у нас переменная типа LPSTR (строка 6) с именем lpCmdLine. Она используется в том случае, если мы запускаем окно через командную строку с прописью параметров. Очень экзотический способ, поэтому мы не будем на нём задерживаться.

И последний параметр: целочисленный, определяет способ показа окна. Нужен для функции ShowWindow, которая будет описана позже. Например, с помощью него мы можем развернуть окно на весь экран, сделать его определённой высоты, прозрачным или поверх остальных.

Переходим к функции MessageBox() (строка 10). Она имеет четыре параметра и нужна для вывода сообщений о ошибках, например. В данном случае мы использовали её для вывода сообщения. В общем виде описание функции выглядит следующим образом:

int MessageBox(HWND hWnd, // дескриптор родительского окна
               LPCTSTR lpText, // указатель на строку с сообщением
               LPCTSTR lpCaption, // указатель на строку с текстом заголовка               
               UINT uType);// флаги для отображения кнопок, стиля пиктограммы и прочее

В нашем случае, первому параметру присвоен ноль. Всё потому, что у нас нет родительских окон (оно не запущено какой-нибудь программой).

Далее у нас идут две переменные типа LPCTSTR: lpText и lpCaption. Первая сообщает информацию, которая будет выведена в окне в текстовом виде. Вторая сообщает, что будет написано в тексте заголовка к окну. Это аналог char *str, но всё же нет. Для того, чтобы текст выводился корректно, нужно перед строкой поставить букву L (UNICODE строка).

Ну и последний тип данных – UINT – 32-х битное целое без знака. То есть аналог unsigned int. Этому параметру можно передавать некоторые значения (о них тоже позже), за счёт чего можно менять вид кнопки. В нашем случае – это MB_OK — означает, что окно создаёт кнопку с надписью «ОК» и соответствующим действием при её нажатии (закрытием приложения).

В строке 11 мы возвращаем значение функции, так как она имеет не тип void.

Таким образом, общее представление о WinAPI теперь есть. Продолжение в следующих разделах.

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Установка динамических обоев windows 10
  • Что лучше macos или windows 10
  • Discord не слышит микрофон windows 11
  • Вход функции семьи учетных записей майкрософт как отключить windows 10
  • Windows 8 enable briefcase reg