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», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

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

Интервал:

Закладка:

Сделать

Now that we have the length, we can allocate some memory. Here I've added a check to see if there is any text to begin with, since most likely you don't want to be working with an empty string… sometimes you might, but that's up to you. Assuming that there is something there to work with, we call GlobalAlloc() to allocate some memory. GlobalAlloc() as I've used it hereis equivalent to calloc() , if you're used to DOS/UNIX coding. It allocates some memory, initializes it's contents to 0 and returns a pointer to that memory. There are different flags you can pass as the first paramter to make it behave differently for different purposes, but this is the only way I will be using it in this tutorial.

Note that I added 1 to the length in two places, what's up with that? Well, GetWindowTextLength() returns the number of characters of text the control contains NOT INCLUDING the null terminator. This means that if we were to allocate a string without adding 1 , the text would fit, but the null terminator would overflow the memory block, possibly corrupting other data, causing an access violation, or any number of other bad things. You must be careful when dealing with string sizes in windows, some APIs and messages expect text lengths to include the null and others don't, always read the docs thoroughly.

If I lost you talking about null terminators, please refer to a basic C book or tutorial which discusses strings.

Finally we can call GetDlgItemText() to retrieve the contents of the control into the memory buffer that we've just allocated. This call expects the size of the buffer INCLUDING the null terminator. The return value, which we ignored here, is the number of characters copied, NOT including the null terminator…. fun eh? :)

After we're all done using the text (which we'll get to in a moment), we need to free up the memory that we allocated so that it doesn't leak out and drip down onto the CPU and short circuit your computer. To accomplish this, we simply call GlobalFree() and pass in our pointer.

You may be or become aware of a second set of APIs named LocalAlloc() , LocalFree() , etc… which are legacy APIs from 16-bit windows. In Win32, the Local* and Global* memory functions are identical.

Edits with Numbers

Entering text is all well and fine, but what if you want the user to enter in a number? This is a pretty common task, and fortunately there is an API to make this simpler, which takes care of all the memory allocation, as well as converting the string to an integer value.

BOOL bSuccess;

int nTimes = GetDlgItemInt(hwnd, IDC_NUMBER, &bSuccess, FALSE);

GetDlgItemInt() works much like GetDlgItemText() , except that instead of copying the string to a buffer, it converts it internally into an integer and returns the value to you. The third parameter is optional, and takes a pointer to a BOOL . Since the function returns 0 on failure, there is no way to tell just from that whether or not the function failed or the user just entered 0 . If you are fine with a value of 0 in the event of an error, then feel free to ignore this parameter.

Another useful feature is the ES_NUMBER style for edit controls, which allows only the characters 0 through 9 to be entered. This is very handy if you only want positive integers, otherwise it's not much good, since you can't enter any other characters, including – (minus) . (decimel) or , (comma).

List Boxes

Another handy control is the list box. This is the last standard control that I'm going to cover for now, cause frankly they aren't that interesting, and if you aren't bored yet well, I am :)

Adding Items

The first thing you'll want to do with a listbox is add items to it.

int index = SendDlgItemMessage(hwnd, IDC_LIST, LB_ADDSTRING, 0, (LPARAM)"Hi there!");

As you can see, this is a pretty simple task. If the listbox has the LBS_SORT style, the new item will be added in alphabetical order, otherwise it will just be added to the end of the list.

This message returns the index of the new item either way, and we can use this to perform other tasks on the item, such as associating some data with it. Usually this will be things like a pointer to a struct containing more information, or maybe an ID that you will use to identify the item, it's up to you.

SendDlgItemMessage(hwnd, IDC_LIST, LB_SETITEMDATA, (WPARAM)index, (LPARAM)nTimes);

Notifications

The whole purpose of listboxes is to allow the user to select things from a list. Now sometimes we don't care when exactly they do this, for example with our Remove button, we don't need to know when the selection changes right away, we just check when the user activates the button.

However, sometimes you want to be able to do something right away, perhaps display different or updated information based on what items are selected. In order to do this we need to handle the notification messages that the listbox passes to us. In this case, we are interested in LBN_SELCHANGE , which tells us that the selection has been modified by the user. LBN_SELCHANGE is sent via WM_COMMAND but unlike handling the WM_COMMAND from buttons or menu's, which are usually only in response to a click, a list box sends WM_COMMAND for various reasons, and we need a second check to find out what it's telling us. The Notification Code is passed as the HIWORD of wParam , the other half of the parameter that gave us the control ID in the first place.

case WM_COMMAND:

switch(LOWORD(wParam)) {

case IDC_LIST:

// It's our listbox, check the notification code

switch(HIWORD(wParam)) {

case LBN_SELCHANGE:

// Selection changed, do stuff here.

break;

}

break;

// … other controls

}

break;

Getting Data from the ListBox

Now that we know the selection has changed, or at the request of the user, we need to get the selection from the listbox and do something useful with it.

In this example I've used a multiselection list box, so getting the list of selected items is a little trickier. If it were a single selection listbox, than you could simply send LB_GETCURSEL to retrieve the item index.

First we need to get the number of selected items, so that we can allocate a buffer to save the indexes in.

HWND hList = GetDlgItem(hwnd, IDC_LIST);

int count = SendMessage(hList, LB_GETSELCOUNT, 0, 0);

Then we allocate a buffer based on the number of items, and send LB_GETSELITEMS to fill in the array.

int *buf = GlobalAlloc(GPTR, sizeof(int) * count);

SendMessage(hList, LB_GETSELITEMS, (WPARAM)count, (LPARAM)buf);

// … Do stuff with indexes

GlobalFree(buf);

In this example, buf[0] is the first index, and so on up to buf[count – 1] .

One of the things you would likely want to do with this list of indexes, is retreive the data associated with each item, and do some processing with it. This is just as simple as setting the data was originally, we just send another message.

int data = SendMessage(hList, LB_GETITEMDATA, (WPARAM)index, 0);

If the data was some other type of value (anything that is 32-bits) you could simply cast to the appropriate type. For example if you stored HBITMAP s instead of int s…

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

Интервал:

Закладка:

Сделать

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

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


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

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

x