Brook Miles - theForger's Win32 API Tutorial

Здесь есть возможность читать онлайн «Brook Miles - theForger's Win32 API Tutorial» весь текст электронной книги совершенно бесплатно (целиком полную версию без сокращений). В некоторых случаях можно слушать аудио, скачать через торрент в формате fb2 и присутствует краткое содержание. Жанр: Программирование, на английском языке. Описание произведения, (предисловие) а так же отзывы посетителей доступны на портале библиотеки ЛибКат.

theForger's Win32 API Tutorial: краткое содержание, описание и аннотация

Предлагаем к чтению аннотацию, описание, краткое содержание или предисловие (зависит от того, что написал сам автор книги «theForger's Win32 API Tutorial»). Если вы не нашли необходимую информацию о книге — напишите в комментариях, мы постараемся отыскать её.

Visit
Software! Code North
This tutorial attempts to get you started developing with the Win32 API as quickly and clearly as possible. It's meant to be read as a whole You may use this tutorial for absolutely no charge, however there are costs associated with hosting it on the web. If you found it to be of use to you and want to give something back, I would be grateful for donations of any amount to help pay for this website. This page gets approximately 11 thousand hits a month, and it adds up after a while :)
Enjoy the tutorial,
Brook
I would like to thank the following for the contributions they've made: Yih Horng, Todd Troxell, T Frank Zvovushe, Suzanne Lorrin, Seth McCarus, Crispina Chong, John Crutchfield, Scott Johnstone, Patrick Sears. As well as those who have simply written to say they've found the tutorial useful. It's much appreciated!
Welcome to Version 2.0 of theForger's Win32 API Tutorial

theForger's Win32 API Tutorial — читать онлайн бесплатно полную книгу (весь текст) целиком

Ниже представлен текст книги, разбитый по страницам. Система сохранения места последней прочитанной страницы, позволяет с удобством читать онлайн бесплатно книгу «theForger's Win32 API Tutorial», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

Next thing is a C following a LP indicates a const pointer. LPCSTR indicates a pointer to a const string, one that can not or will not be modified. LPSTR on the other hand is not const and may be changed.

You might also see a T mixed in there. Don't worry about this for now, unless you are intentionally working with Unicode , it means nothing.

A Simple Window

Example: simple_window

Sometimes people come on IRC and ask "How do I make a window?"… Well it's not entirely that simple I'm afraid. It's not difficult once you know what you're doing but there are quite a few things you need to do to get a window to show up; And they're more than can be simply explained over a chat room, or a quick note.

I always liked to do things first and learn them later… so here is the code to a simple window which will be explained shortly.

#include

const char g_szClassName[] = "myWindowClass";

// Step 4: the Window Procedure

LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) {

switch (msg) {

case WM_CLOSE:

DestroyWindow(hwnd);

break;

case WM_DESTROY:

PostQuitMessage(0);

break;

default:

return DefWindowProc(hwnd, msg, wParam, lParam);

}

return 0;

}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {

WNDCLASSEX wc;

HWND hwnd;

MSG Msg;

//Step 1: Registering the Window Class

wc.cbSize = sizeof(WNDCLASSEX);

wc.style = 0;

wc.lpfnWndProc = WndProc;

wc.cbClsExtra = 0;

wc.cbWndExtra = 0;

wc.hInstance = hInstance;

wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);

wc.hCursor = LoadCursor(NULL, IDC_ARROW);

wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);

wc.lpszMenuName = NULL;

wc.lpszClassName = g_szClassName;

wc.hIconSm = LoadIcon(NULL, IDI_APPLICATION);

if (!RegisterClassEx(&wc)) {

MessageBox(NULL, "Window Registration Failed!", "Error!", MB_ICONEXCLAMATION | MB_OK);

return 0;

}

// Step 2: Creating the Window

hwnd = CreateWindowEx(WS_EX_CLIENTEDGE, g_szClassName, "The title of my window", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 240, 120, NULL, NULL, hInstance, NULL);

if (hwnd == NULL) {

MessageBox(NULL, "Window Creation Failed!", "Error!", MB_ICONEXCLAMATION | MB_OK);

return 0;

}

ShowWindow(hwnd, nCmdShow);

UpdateWindow(hwnd);

// Step 3: The Message Loop

while(GetMessage(&Msg, NULL, 0, 0)> 0) {

TranslateMessage(&Msg);

DispatchMessage(&Msg);

}

return Msg.wParam;

}

For most part this is the simplest windows program you can write that actually creates a functional window, a mere 70 or so lines. If you got the first example to compile then this one should work with no problems.

Step 1: Registering the Window Class

A Window Class stores information about a type of window, including it's Window Procedure which controls the window, the small and large icons for the window, and the background color. This way, you can register a class once, and create as many windows as you want from it, without having to specify all those attributes over and over. Most of the attributes you set in the window class can be changed on a per-window basis if desired.

A Window Class has NOTHING to do with C++ classes.

const char g_szClassName[] = "myWindowClass";

The variable above stores the name of our window class, we will use it shortly to register our window class with the system.

WNDCLASSEX wc;

wc.cbSize = sizeof(WNDCLASSEX);

wc.style = 0;

wc.lpfnWndProc = WndProc;

wc.cbClsExtra = 0;

wc.cbWndExtra = 0;

wc.hInstance = hInstance;

wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);

wc.hCursor = LoadCursor(NULL, IDC_ARROW);

wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);

wc.lpszMenuName = NULL;

wc.lpszClassName = g_szClassName;

wc.hIconSm = LoadIcon(NULL, IDI_APPLICATION);

if (!RegisterClassEx(&wc)) {

MessageBox(NULL, "Window Registration Failed!", "Error!", MB_ICONEXCLAMATION | MB_OK);

return 0;

}

This is the code we use in WinMain() to register our window class. We fill out the members of a WNDCLASSEX structure and call RegisterClassEx() .

The members of the struct affect the window class as follows:

cbSize

The size of the structure.

style

Class Styles ( CS_* ), not to be confused with Window Styles ( WS_* ) This can usually be set to 0 .

lpfnWndProc

Pointer to the window procedure for this window class.

cbClsExtra

Amount of extra data allocated for this class in memory. Usually 0 .

cbWndExtra

Amount of extra data allocated in memory per window of this type. Usually 0 .

hInstance

Handle to application instance (that we got in the first parameter of WinMain() ).

hIcon

Large (usually 32×32) icon shown when the user presses Alt+Tab.

hCursor

Cursor that will be displayed over our window.

hbrBackground

Background Brush to set the color of our window.

lpszMenuName

Name of a menu resource to use for the windows with this class.

lpszClassName

Name to identify the class with.

hIconSm

Small (usually 16×16) icon to show in the taskbar and in the top left corner of the window. Don't worry if that doesn't make much sense to you yet, the various parts that count will be explained more later. Another thing to remember is to not try and remember this stuff. I rarely (never) memorize structs, or function parameters, this is a waste of effort and, more importantly, time. If you know the functions you need to call then it is a matter of seconds to look up the exact parameters in your help files. If you don't have help files, get them. You are lost without. Eventually you will come to know the parameters to the functions you use most.

We then call RegisterClassEx() and check for failure, if it fails we pop up a message which says so and abort the program by returning from the WinMain() function.

Step 2: Creating the Window

Once the class is registered, we can create a window with it. You should look up the paramters for CreateWindowEx() (as you should ALWAYS do when using a new API call), but I'll explain them briefly here.

HWND hwnd;

hwnd = CreateWindowEx(WS_EX_CLIENTEDGE, g_szClassName, "The title of my window", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 240, 120, NULL, NULL, hInstance, NULL);

Читать дальше
Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

Похожие книги на «theForger's Win32 API Tutorial»

Представляем Вашему вниманию похожие книги на «theForger's Win32 API Tutorial» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.


Отзывы о книге «theForger's Win32 API Tutorial»

Обсуждение, отзывы о книге «theForger's Win32 API Tutorial» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.

x