Windows API Tutorials

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

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

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

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

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

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

Интервал:

Закладка:

Сделать

void Controller::Edit(HWND hwnd) {

EditorData data (_model.GetText ());

ControllerFactory factory (& data);

ModalDialog dialog (_hInst, hwnd, IDD_EDITDIALOG, & factory);

if (dialog.IsOk ()) {

_model.SetText (data.GetName ());

// Force repaint

InvalidateRect (hwnd, 0, TRUE);

}

}

First, the EditorDataobject is created and initialized with a string. Next, the ControllerFactorytemplate is instantiated. We parametrize it with the two client classes, EditorCtrland EditorData. The factory object is initialized with a pointer to our data. Next, the ModalDialogobject is created. it takes the pointer to our factory as an argument. it uses it to create the controller object and to retrieve data from the argument list. After the interaction with the user is done, we check whether the user blessed the results by clicking the ok button, and if so, we retrieve the result from the editor data object and incorporate it in our program. This is pretty much the standard way to set up a dialog box.

The EditorDataclass in our example is pretty simple.

class EditorData{

public:

enum { maxLen = 128 };

EditorData (char const * name) {

SetName (name);

}

BOOL IsNameOK () { return (_name[0] != '\0'); }

void SetName (char const *name) {

strcpy (_name, name);

}

char const *GetName () { return _name; }

private:

char _name [maxLen];

};

The controller class, EditorCtrl, is where all the action is. First of all, it has the Edit control embedded in it. This object is responsible for the interaction with the edit gizmo embedded in the dialog box. The gizmo has the id IDC_NAME_EDIT that we gave it in the resource editor. Second of all, the controller stores a pointer to EditorData. This pointer is retrieved from the base class DlgController. Three virtual methods of DlgControllerhave to be overridden in our EditorControl. These are OnInitDialog, which is called immediately after the dialog has been initialized, OnCommand, which is called whenever any dialog box gizmo sends us a command and, finally, OnNotify, which is used by the new Windows95 controls.

class EditorCtrl: public DlgController{

public:

EditorCtrl (HWND hwndDlg, EditorData *argList) : DlgController (argList), _nameEdit (hwndDlg, IDC_NAME_EDIT) {

_dlgData = argList;

}

void OnInitDialog (HWND hwnd);

bool OnCommand (HWND hwnd, int ctrlID, int notifyCode);

bool OnNotify (HWND hwnd, int idCtrl, NMHDR *hdr);

private:

Edit _nameEdit;

EditorData *_dlgData;

};

In the OnInitDialogmethod we retrieve the string that was passed in EditorDataand use it to initialize the edit control.

void EditorCtrl::OnInitDialog(HWND hwnd) {

char const * name = _dlgData->GetName ();

_nameEdit.SetString (name);

}

OnCommandreceives commands from various gizmos. The gizmos are identified by their control id. For instance, if the control id is IDC_NAME_EDIT, it means that something happend to the edit control. In our implementation we are a little overzelous and we react to every change by copying the whole string into EditorDataobject. There are cases though, when you need to keep validating the string or displaying it in some other control and then you really have to react to every change message.

When the user clicks the OK button, we get a command with the IDOK control id. We verify the string and, if it's okay, we end the dialog passing TRUE as the return code. When the control id is IDCANCEL (from the Cancel button) we end the dialog with the FALSE return code.

The OnNotifymethod does nothing in the case of pre-Windows95 controls, such as the edit control and the buttons.

bool EditorCtrl::OnCommand(HWND hwnd, int ctrlID, int notifyCode) {

switch (ctrlID) {

case IDC_NAME_EDIT:

if (_nameEdit.IsChanged (notifyCode)) {

char nameBuf [EditorData::maxLen];

int len = _nameEdit.GetLen();

if (len < EditorData::maxLen) {

_nameEdit.GetString (nameBuf, sizeof (nameBuf));

_dlgData->SetName (nameBuf);

}

return true;

}

break;

case IDOK:

if (_dlgData->IsNameOK ()) {

EndDialog(hwnd, TRUE);

} else {

MessageBox (hwnd, "Please, enter valid name", "Name Editor", MB_ICONINFORMATION | MB_OK);

}

return true;

case IDCANCEL:

EndDialog(hwnd, FALSE);

return true;

}

return false;

}

bool EditorCtrl::OnNotify(HWND hwnd, int idCtrl, NMHDR *hdr) {

return false;

}

Now that you knowhow to use it, let's have a look at the implementation of the whole dialog box pattern. The controller factory is a very simple template class. All it does it to accept the generic argument list and store it as a void pointer. Only the client-defined controller knows what the actual class of the argument list is and it will perform a cast (see the constructor of EditorCtrl).

The code common to all controller factories is isolated in the class CtrlFactoryfrom which the actual template is derived. The template overrides the MakeControllermethod to create a new controller of the client-defined class ActualCtrl. Notice however that the method returns ActualCtrlas a pointer to its base class DlgControllerand that's what the rest of the implementation sees.

class CtrlFactory{

public:

CtrlFactory (void *argList) : _argList (argList) {}

virtual DlgController * MakeController (HWND hwndDlg) = 0;

protected:

void *_argList;

};

template

class ControllerFactory: public CtrlFactory{

public:

ControllerFactory (void *argList) : CtrlFactory (argList) {}

DlgController* MakeController (HWND hwndDlg) {

return new ActualCtrl(hwndDlg, (ActualArgList *) GetArgList ());

}

};

Here is the definition of the abstract class DlgControllerthat is used as a base for all client-defined controller classes. We've already seen how this derivation works in the case of the client class EditorCtrl.

class DlgController{

public:

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

Интервал:

Закладка:

Сделать

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

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


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

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

x