Windows API Tutorials

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

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

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

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

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

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

Интервал:

Закладка:

Сделать

Window procedure is called with a handle to a window to which a given message is directed. This handle uniquely identifies an internal Windows' data structure that corresponds to a given window instance. It so happens that we can access this data structure and use it to store some instance-specific data. Here's the type safe way of accessing this structure. By the way, the GWL_USERDATA member of this structure is guaranteed to be present in all windows, including message boxes, dialog boxes and even buttons.

template

inline T WinGetLong(hwnd hwnd, int which = gwl_userdata) {

return reinterpret_cast (:: GetWindowLong(hwnd, which));

}

template

inline void WinSetLong(hwnd hwnd, t value, int which = gwl_userdata) {

:: SetWindowLong(hwnd, which, reinterpret_cast (value));

}

Every time Windows calls our window procedure, we want to first retrieve its controller object. Remember, there may be several windows sharing the same window procedure and we want to have a separate controller for each window. How do we know which controller to use when we are called? We find out by looking at the window handle. In this handle we store the pointer to this particular window's controller using the Win[Set/Get]Long trick.

The Window procedure is first called with the WM_CREATE message. At that time we create the controllerobject and initialize it with the window handle and a special data structure called CREATESTRUCT that is passed to us by Windows. once we have the controller, we store the pointer to it in the corresponding internal Windows' data structure under the label of the current hwnd. next time the window procedure is called, with a message other than WM_CREATE, we simply retrieve the pointer to our controller using the hwnd.

The rest is easy. The Window procedure interprets message parameters and calls the appropriate methods of the controller.

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

Controller * pCtrl = WinGetLong (hwnd);

switch (message) {

case WM_CREATE:

// Have to catch exception in case new throws!

try {

pCtrl = new Controller (hwnd, reinterpret_cast (lParam));

WinSetLong (hwnd, pCtrl);

}

catch (WinException e) {

:: MessageBox(hwnd, e.GetMessage(), "Initialization", MB_ICONEXCLAMATION | MB_OK);

return –1;

}

catch (…) {

:: MessageBox(hwnd, "Unknown Error", "Initialization", MB_ICONEXCLAMATION | MB_OK);

return –1;

}

return 0;

case WM_SIZE:

pCtrl->Size (LOWORD(lParam), HIWORD(lParam));

return 0;

case WM_PAINT:

pCtrl->Paint ();

return 0;

case WM_COMMAND:

pCtrl->Command (LOWORD (wParam));

return 0;

case WM_DESTROY:

WinSetLong (hwnd, 0);

delete pCtrl;

return 0;

}

return :: DefWindowProc(hwnd, message, wParam, lParam);

}

Here are examples of simple implementations of a few controller methods. The constructor has to remember the handle to the window for later use, the destructor has to post the quit message, The Sizemethod passes its argument to View, etc. we'll talk about painting the window a little later. for now, notice that the controller prepares the paint canvas for the Viewto work with.

Controller::Controller(HWND hwnd, CREATESTRUCT * pCreate) :_hwnd (hwnd), _model ("Generic") { }

Controller::~Controller() {

:: PostQuitMessage(0);

}

void Controller::Size(int cx, int cy) {

_view.SetSize (cx, cy);

}

void Controller::Paint() {

// prepare the canvas and let View do the rest

PaintCanvas canvas (_hwnd);

_view.Paint (canvas, _model);

// Notice: The destructor of PaintCanvas called automatically!

}

When the user selects one of the menu items, Window procedure is called with the message WM_COMMAND. The appropriate controller method dispatches the command based on the command id. When you create the menu using your resource editor, you pick these command ids for each menu item. They are stored in the appropriate header file (resource.h in our case) that has to be included in the controller's source file.

Our menu contains only three items with the ids IDM_EXIT, IDM_HELP, and IDM_ABOUT. the dialog box that is displayed in response to IDM_ABOUTis also created using the resource editor and given the id IDD_ABOUT. Its dialog procedure is AboutDlgProc.

Finally, in order to display a dialog box we need the handle to the application instance. The standard way to retrieve it is to access the internal Windows data structure using the appropriate hwnd.

// Menu command processing

void Controller::Command(int cmd) {

switch (cmd) {

case IDM_EXIT:

:: SendMessage(_hwnd, WM_CLOSE, 0, 0L);

break;

case IDM_HELP:

:: MessageBox(_hwnd, "Go figure!", "Generic", MB_ICONINFORMATION | MB_OK);

break;

case IDM_ABOUT:

{

// Instance handle is available through HWND

HINSTANCE hInst = WinGetLong (_hwnd, GWL_HINSTANCE);

:: DialogBox(hInst, MAKEINTRESOURCE (IDD_ABOUT), _hwnd, AboutDlgProc);

}

break;

}

}

The view object usually stores the dimensions of the client area. They are updated whenever the controller processes the WM_SIZE message. The first WM_SIZE message is sent during window creation and before WM_PAINT, so we can safely assume that when Paint is called, the dimensions of the client area are known.

Graphical output to the window is done by calling appropriate methods of the Canvas object. In our case, we print text obtained from the model and draw a vertical line ten pixels from the left edge of the client area.

class View{

public:

void SetSize (int cxNew, int cyNew) {

_cx = cxNew;

_cy = cyNew;

}

void Paint (Canvas & canvas, Model & model);

protected:

int _cx;

int _cy;

};

void View::Paint(Canvas & canvas, Model & model) {

canvas.Text (12, 1, model.GetText(), model.GetLen());

canvas.Line (10, 0, 10, _cy);

}

The canvas object encapsulates what is called a Device Context in Windows parlance. Our Canvas is very simple, it only knows how to print text and draw lines, but your Canvas can have many more methods that do creative things. We'll talk about Canvas more in one of the next tutorials.

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

Интервал:

Закладка:

Сделать

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

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


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

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

x