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

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

Интервал:

Закладка:

Сделать

HWND g_hToolbar = NULL;

case WM_CREATE:

g_hToolbar = CreateDialog(GetModuleHandle(NULL), MAKEINTRESOURCE(IDD_TOOLBAR), hwnd, ToolDlgProc);

if(g_hToolbar != NULL) {

ShowWindow(g_hToolbar, SW_SHOW);

} else {

MessageBox(hwnd, "CreateDialog returned NULL", "Warning!", MB_OK | MB_ICONINFORMATION);

}

break;

We check the return value, which is ALWAYS a good idea, and if it's valid (not NULL ) we show the window with ShowWindow() , with DialogBox() this isn't necessary since the system calls ShowWindow() for us.

Now we need a dialog procedure for our toolbar.

BOOL CALLBACK ToolDlgProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam) {

switch(Message) {

case WM_COMMAND:

switch(LOWORD(wParam)) {

case IDC_PRESS:

MessageBox(hwnd, "Hi!", "This is a message", MB_OK | MB_ICONEXCLAMATION);

break;

case IDC_OTHER:

MessageBox(hwnd, "Bye!", "This is also a message", MB_OK | MB_ICONEXCLAMATION);

break;

}

break;

default:

return FALSE;

}

return TRUE;

}

Most of the same message handling rules apply to dialogs created with CreateDialog() as with DialogBox() , don't call DefWindowProc() , return FALSE for messages you don't handle and TRUE for those you do.

One change is that we don't call EndDialog() for modeless dialogs, we can use DestroyWindow() just like for regular windows. In this case I destroy the dialog when the main window is destroyed. In the main window's WndProc()

case WM_DESTROY:

DestroyWindow(g_hToolbar);

PostQuitMessage(0);

break;

Last but not least, we want to be able to display and hide our toolbar whenever we choose so I've added two commands to my menu to do this, and handled them so:

case WM_COMMAND:

switch(LOWORD(wParam)) {

case ID_DIALOG_SHOW:

ShowWindow(g_hToolbar, SW_SHOW);

break;

case ID_DIALOG_HIDE:

ShowWindow(g_hToolbar, SW_HIDE);

break;

//… other command handlers

}

break;

You should be able to create your own menu using the resource editor or manually, but if not (as always) take a look at the example project dlg_two provided with the tutorial.

Now when you run the program, you should be able to access both the dialog window, and main window at the same time.

If you've run the program at this point and tried tabbing between the two buttons, you have probably noticed it doesn't work, neither does hitting Alt-P or Alt-O to activate the buttons. Why not? Whereas DialogBox() implements it's own message loop and handles these events by default, CreateDialog() does not. We can do it ourselves though, by calling IsDialogMessage() in our message loop which will do the default processing for us.

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

if (!IsDialogMessage(g_hToolbar, &Msg)) {

TranslateMessage(&Msg);

DispatchMessage(&Msg);

}

}

Here we first pass the message to IsDialogMessage() , if the message is destined for our toolbar (indicated by the window handle we pass in) the system will perform the default processing and return TRUE . Is this case the message has already been handled so we don't want to call TranslateMessage() or DispatchMessage() . If the message is for another window we process as usual.

And that is pretty much all there is to modeless dialogs! One issue that may arise is if you have more than one toolbar… what do you do? Well one possible solution is to have a list (either an array, an STL std::list , or similar) and loop through it in your message loop passing each handle to IsDialogMessage() until the right one is found, and if none, do the regular processing. This is a generic programming problem, not one that is Win32 related, and is left as an excersize to the reader.

Standard Controls: Button, Edit, List Box

Example: ctl_one

I realize I've already used buttons in previous examples, so you should already be more or less familiar with them, however I figured that since I was using them in this example I might as well add it to the title for the sake of being complete.

Controls

One thing to remember about controls is that they are just windows. Like any other window they have a window procedure, a window class etc… that is registered by the system. Anything you can do with a normal window you can do with a control.

Messages

As you may remember from our earlier discussion of the message loop, windows communicate using messages, you send them to get a control to do something, and when an event occurs on the control it will send you a notification message back. For the standard controls this notification will be a WM_COMMAND message as we've already seen with buttons and menus. For the Common Controls which I may get to later, it will be WM_NOTIFY .

The messages you send are widely varied between each control, and each control has it's own set of messages. Once in a while the same message will be used for more than one kind of control, but in general they will only work on the control they are intended for. This is especially annoying with the listbox and combobox messages ( LB_* and CB_* ) which although they perform nearly identical tasks, are NOT interchangeable, and I accidently get them mixed up more than I'd like to admit :)

On the other hand, generic messages like WM_SETTEXT are supported by almost all controls. A control is just a window after all.

You can send messages using the SendMessage() API, and use GetDlgItem() to retreive the handle to the control, or you can use SendDlgItemMessage() which does both steps for you, the results of both methods are identical.

Edits

One of the most commonly used controls in the windows environment, the EDIT control, is used to allow the user to enter, modify, copy, etc… text. Windows Notepad is little more than a plain old window with a big edit control inside it.

Here is the code used to interface with the edit control in this example:

SetDlgItemText(hwnd, IDC_TEXT, "This is a string");

That's all it takes to change the text contained in the control (this can be used for pretty much any control that has a text value associated with it, STATICs, BUTTONs and so on).

Retreiving the text from the control is easy as well, although slightly more work than setting it…

int len = GetWindowTextLength(GetDlgItem(hwnd, IDC_TEXT));

if (len > 0) {

int i; char* buf;

buf = (char*)GlobalAlloc(GPTR, len + 1);

GetDlgItemText(hwnd, IDC_TEXT, buf, len + 1);

//… do stuff with text …

GlobalFree((HANDLE)buf);

}

First of all, we need to allocate some memory to store the string in, it won't just return us a pointer to the string already in memory. In order to do this, we first need to know how much memory to allocate. There isn't a GetDlgItemTextLength() , but there is a GetWindowTextLength() , so all we need to do it get the handle to the control yourself using GetDlgItem() .

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

Интервал:

Закладка:

Сделать

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

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


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

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

x