Windows API Tutorials

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

Windows API Tutorials: краткое содержание, описание и аннотация

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

Windows API Tutorials — читать онлайн бесплатно полную книгу (весь текст) целиком

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

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

Интервал:

Закладка:

Сделать

if (! IsDialogMessage(hDialog, & msg)) {

TranslateMessage( & msg );

DispatchMessage( & msg );

}

}

return msg.wParam;

}

The dialog procedure is just like Windows procedure, except that it returns TRUE when it processes a message and FALSE when it doesn't. There is no need to call the default procedure, because Windows does it for us whenever the dialog procedure returns FALSE (makes you think, "Why wasn't the same design used in the window procedure…?"). The first message the dialog gets is WM_INITDIALOG and the last one is WM_CLOSE. During the processing of these messages we create and destroy the Controller. Other than that, the dialog expects messages from its controls-these are passed as WM_COMMAND. One control that requires special processing is a (horizontal) scrollbar — it sends the WM_HSCROLL message. There are scrollbar controls in the Frequency Analyzer and that's how they are dealt with.

BOOL CALLBACK DialogProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) {

static Controller* control = 0;

switch (message) {

case WM_INITDIALOG:

try {

control = new Controller (hwnd);

}

catch (WinException e) {

MessageBox(0, e.GetMessage (), "Exception", MB_ICONEXCLAMATION | MB_OK);

PostQuitMessage(1);

}

catch (…) {

MessageBox(0, "Unknown", "Exception", MB_ICONEXCLAMATION | MB_OK);

PostQuitMessage(2);

}

return TRUE;

case WM_COMMAND:

control->Command(hwnd, LOWORD (wParam), HIWORD (wParam));

return TRUE;

case WM_HSCROLL:

control->Scroll (hwnd, LOWORD (wParam), HIWORD (wParam));

return 0;

case WM_DESTROY:

PostQuitMessage(0);

return TRUE;

case WM_CLOSE:

delete control;

DestroyWindow(hwnd);

return TRUE;

}

return FALSE;

}

Let's have a look at the Controller. Notice how every control on the face of the dialog box has a corresponding (embedded) control objectinside the Controller. There are edits, combos, radio buttons and scrollbars. There is a special metafile control that draws the frequency scale and two view objects corresponding to two static panes upon which we draw the graphs. Finally we have the Painter object that is responsible for the asynchronous repainting of the two panes.

class Controller{

public:

Controller(HWND hwnd);

~Controller ();

void Command (HWND hwnd, int id, int code);

void Scroll (HWND hwnd, int cmd, int pos);

void Paint (HWND hwnd);

void ReInit (HWND hwnd);

void Stop (HWND hwnd);

private:

void InitScrollPositions ();

void PaintScale ();

BOOL _isStopped;

int _bitsPerSample;

int _samplesPerSecond;

int _fftPoints;

int _samplesPerBuf;

EditReadOnly _edit;

Combo _comboFreq;

Combo _comboPoints;

RadioButton _radio8;

RadioButton _radio16;

ScrollBarMap _scroll;

StaticEnhMetafileControl _scaleFreq;

ViewWave _viewWave;

ViewFreq _viewFreq;

Painter _display;

};

The constructor of the Controller takes care of the initialization of all the controls by passing them the handle to the dialog box window and the appropriate identifiers. As a matter of cosmetics, we attach our own icon to the dialog-otherwise the system would use the standard Windows icon.

Controller::Controller(HWND hwnd) :_isStopped (TRUE), _bitsPerSample (16), _samplesPerSecond (SAMPLES_SEC), _fftPoints (FFT_POINTS * 4), _samplesPerBuf (FFT_POINTS * 2), _radio8 (hwnd, IDC_8_BITS), _radio16 (hwnd, IDC_16_BITS), _scroll (hwnd, IDC_SCROLLBAR), _edit (hwnd, IDC_EDIT), _comboFreq (hwnd, IDC_SAMPLING), _comboPoints (hwnd, IDC_POINTS), _viewWave (hwnd, IDS_WAVE_PANE, FFT_POINTS * 8), _viewFreq (hwnd, IDS_FREQ_PANE), _scaleFreq (hwnd, IDC_FREQ_SCALE), _display (hwnd, _viewWave, _viewFreq, _samplesPerBuf, _samplesPerSecond, _fftPoints) {

// Attach icon to main dialog

HICON hIcon = LoadIcon(TheInstance, MAKEINTRESOURCE(ICO_FFT));

SendMessage(hwnd, WM_SETICON, WPARAM (ICON_SMALL), LPARAM (hIcon));

// Other initializations…

}

Using a dialog box as the main window is a very handy and simple technique, especially for applications that display a panel-like interface. By the way, the Battleship app (see the home page) uses the same trick. You may now continue to the next tutorial on the use of dialog boxesin Windows applications.

Dialog Box

Dialog boxis for a Windows program what a function call is for a C program. First, a Windows programs passes some data to the dialog box in order to initialize it. Next, the dialog box solicits information from the user. When the user decides that the program's curiosity has been satisfied, he or she clicks the OK button. The new data is then returned back to the program.

A dialog box is usually spiked with all kinds of controls (widgets, gadgets, gizmos, whatever you call them). Dialog box code interacts with these gizmos by sending and receiving messages in its Dialog Box Procedure . There is a lot of common code in the implementation of various dialog boxes. We would like to write and test this code only once and then keep reusing it.

What varies from dialog to dialog is:

• The kind of data that is passed to and retrieved from the dialog box

• The kind of gizmos within the dialog box and

• The interactions between them.

This variability can be encapsulated in two custom client classes: the argument list class and the dialog controller class.

The argument list class encapsulates the in and out arguments and provides access for retrieving and changing them. The definition and the implementation of this class is under complete control of the client (the programmer who reuses our code).

The dialog controller class contains control objects for all the gizmos in the dialog and implements interactions between them. The client is supposed to derive this class from the abstract DlgControllerclass and implement all its pure virtual methods.

The rest is just glue. We need to instantiate a template CtrlFactoryclass that is used by our generic implementation of the ModalDialogclass. The controller factory creates the appropriate client-defined controller and returns a polymorphic pointer to it. Fig 1. shows the relationships between various classes involved in the implementation of a dialog box.

Fig 1. Classes involved in the dialog box design pattern.

Let's start with the client code. In our generic program we need a dialog box that lets the user edit a string. Using a resource editor, we create a dialog template that contains an edit control and two buttons, OK and CANCEL. The resource id of this dialog is IDD_EDITDIALOG. Next we define our own argument list class called EditorDataand a special controller class called EditorCtrl. When the user selects the Edit menu item, the following code is executed:

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

Интервал:

Закладка:

Сделать

Похожие книги на «Windows API Tutorials»

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


Отзывы о книге «Windows API Tutorials»

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

x