Windows API Tutorials

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

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

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

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

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

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

Интервал:

Закладка:

Сделать

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!

}

All the various types of Canvas share the common ancestor — the Canvas class. Notice that Canvas' constructor is protected. You can't actually instantiate an object of this class. However, the derived classes are free to provide their own constructors. By the way, you can keep adding new methods to Canvas as the need arises.

class Canvas{

public:

// operator cast to HDC

// (used when passing Canvas to Windows API)

operator HDC () { return _hdc; }

void Point (int x, int y, COLORREF color) {

:: SetPixel(_hdc, x, y, color);

}

void MoveTo (int x, int y) {

:: MoveToEx(_hdc, x, y, 0);

}

void Line ( int x1, int y1, int x2, int y2 ) {

MoveToEx(_hdc, x1, y1, 0);

LineTo(_hdc, x2, y2);

}

void Rectangle (int left, int top, int right, int bottom) {

// draw rectangle using current pen

// and fill it using current brush

:: Rectangle(_hdc, left, top, right, bottom);

}

void GetTextSize (int & cxChar, int & cyChar) {

TEXTMETRIC tm;

GetTextMetrics(_hdc, & tm);

cxChar = tm.tmAveCharWidth;

cyChar = tm.tmHeight + tm.tmExternalLeading;

}

void Text (int x, int y, char const * buf, int cBuf) {

:: TextOut( _hdc, x, y, buf, cBuf );

}

void Char (int x, int y, char c) {

TextOut(_hdc, x, y, & c, 1);

}

void SelectObject (void* pObj) {

:: SelectObject(_hdc, pObj);

}

protected:

Canvas (HDC hdc): _hdc (hdc) {}

HDC _hdc;

};

In response to the WM_PAINT message one should construct the PaintCanvas object. Notice the way PaintCanvas obtains and releases the DC.

class PaintCanvas: public Canvas{

public:

// Constructor obtains the DC

PaintCanvas (HWND hwnd) : Canvas ( BeginPaint(hwnd, & _paint)), _hwnd (hwnd) {}

// Destructor releases the DC

~PaintCanvas () {

EndPaint(_hwnd, & _paint);

}

protected:

PAINTSTRUCT _paint;

HWND _hwnd;

};

Another important example is the UpdateCanvas which is used for graphical operations outside of the context of WM_PAINT processing. Of course, your program may always force the repainting by calling InvalidateRect, but in many cases it would be an overkill. If your program keeps painting new things as it executes or in response to user actions, you can update the window using UpdateCanvas.

class UpdateCanvas: public Canvas{

public:

UpdateCanvas (HWND hwnd) : Canvas ( GetDC(hwnd)), _hwnd(hwnd) {}

~UpdateCanvas () {

ReleaseDC(_hwnd, _hdc);

}

protected:

HWND _hwnd;

};

There are other types of Canvas: DrawItemCanvas used for owner-draw controls, MemCanvas for drawing on a piece of memory, etc.

Use pens and brushesto draw and paint on your canvas.

Drawing with Pens and Painting with Brushes

Like a painter, you will need pens and brushes to create artwork on your canvas. When you call Canvas::Line or Canvas::Rectangle, Windows uses the currently attached pen to draw the lines and the currently attached brush to fill the insides of the shapes.

When you attach an object to the Canvas, you have to remember to detach it after you're done. Unless… you let C++ remember about that. Just use a local object whose constructor attaches, and destructor (called automatically when exiting the scope) detaches the object (see the Resource Management page for more details on this methodology). Notice that the following objects take HDC (handle to Device Context) as an argument in their constructors. However, you should simply pass them a Canvas object instead. Remember that Canvas can be automatically cast to HDC.

class StockObject{

public:

StockObject (HDC hdc, int type) : _hdc(hdc) {

_hObjOld = SelectObject(_hdc, GetStockObject(type));

}

~StockObject () {

SelectObject(_hdc, _hObjOld);

}

private:

HGDIOBJ _hObjOld;

HDC _hdc;

};

Windows comes with a set of pre-defined pens and brushes. It is enough to attach them to your canvas for the time you want to use them.

class WhitePen: public StockObject{

public:

WhitePen (HDC hdc): StockObject (hdc, WHITE_PEN) {}

};

// example

void Controller::Paint (HWND hwnd) {

PaintCanvas canvas (hwnd);

WhitePen pen (canvas);

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

// destructor of WhitePen

// destructor of PaintCanvas

}

If your program keeps using a small set of non-stock pens, you might want to create them up-front (e.g. by embedding them in the View object) and use a PenHolder object to temporarily attach them to your Canvas.

class Pen{

public:

Pen (COLORREF color) {

_hPen = CreatePen(PS_SOLID, 0, color);

}

~Pen () {

DeleteObject(_hPen);

}

operator HPEN () { return _hPen; }

private:

HPEN _hPen;

};

class PenHolder{

public:

PenHolder (HDC hdc, HPEN hPen) : _hdc (hdc) {

_hPenOld = (HPEN) SelectObject(_hdc, hPen);

}

~PenHolder () {

SelectObject(_hdc, _hPenOld);

}

private:

HDC _hdc;

HPEN _hPenOld;

};

class View{

public:

View () : _penGreen (RGB (0, 255, 128)) {}

void Paint (Canvas & canvas) {

PenHolder holder (canvas, _penGreen);

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

// destructor of PenHolder

}

private:

Pen _penGreen;

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

Интервал:

Закладка:

Сделать

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

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


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

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

x