Windows API Tutorials

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

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

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

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

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

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

Интервал:

Закладка:

Сделать

bltMask.SetMode (SRCPAINT);

bltMask.SetDest (x, y);

bltMask.BlitTo (bmpCanvas);

Blitter bltSprite (_sprite);

bltSprite.SetMode (SRCAND);

bltSprite.SetDest (x, y);

bltSprite.BlitTo (bmpCanvas);

// update the buffer

_bitmapBuf = bmp;

}

For completeness, here's the definition of bitmap canvas. You draw directly on this canvas using standard canvas methods, like Line, Text, SetPixel, etc… Here we only blit bitmaps into it.

class BitmapCanvas: public MemCanvas{

public:

BitmapCanvas (HDC hdc, HBITMAP hBitmap) : MemCanvas (hdc) {

// convert bitmap to format compatible with canvas

_hOldBitmap = reinterpret_cast (:: SelectObject(_hdc, hBitmap));

}

~BitmapCanvas () {

:: SelectObject(_hdc, _hOldBitmap);

}

private:

HBITMAP _hOldBitmap;

};

class MemCanvas: public Canvas{

public:

MemCanvas (HDC hdc) : Canvas (:: CreateCompatibleDC(hdc)) {}

~MemCanvas () {

:: DeleteDC(_hdc);

}

};

Now, if you want more speed, read about DirectDraw.

Direct Draw

Direct Draw App

If you want fast animation (games!), you have to use DirectX. Try filling the screen by drawing each pixel separately using GDI. Compare it with DirectX, which gives you practically direct access to the screen buffer. There's no competition!

The bad news is that DirectX involves dealing with COM interfaces. The good news is that you can encapsulate them nicely inside C++ classes. Let me show you first how to use these classes to write a simple application that displays an animated, rotating, bitmap. We'll use Windows timer to drive the animation. We'll have to:

• Initialize the program, including the DirectX subsystem

• Respond to timer messages

• Respond to window resizing (we'll use the window mode, rather than full screen)

• Respond to paint messages

Let's start with the WM_PAINT message. This message is sent to us when Windows needs to repaint our window. We have to stash somewhere a complete animation frame, so that we can quickly blit it to screen in response to WM_PAINT. The storage for this frame will be called the back surface.

Upon receiving the timer message, we have to paint a new frame on the back surface. Once we're done, we'll invalidate our window, so that WM_PAINT message will be sent to us.

Upon resizing the window, we have to create a new back surface, corresponding to the new window size. Then we'll draw on it and invalidate the window.

The initialization involves creating the timer, creating the World (that's where we keep our bitmap and drive the animation), creating the View, and setting the first timer countdown.

void Controller::Create (CREATESTRUCT * create) {

_timer.Create (_h, 1);

_world = new World (create->hInstance, IDB_RS);

_view.Create (_h, _world);

_timer.Set (10);

}

Here's our response to WM_SIZE. We let the View know about the new size (it will create a new back surface), we call it's Update method which draws the animation frame, and we invalidate the window.

bool Controller::Size (int width, int height) {

_view.Size (_h, width, height);

_view.Update ();

// force repaint

_h.Invalidate (false);

return true;

}

In response to WM_PAINT, we let the View do the painting (blit the back surface to the screen). We also have to tell Windows that the painting is done-validate the uncovered area. This is done simply by constructing the PaintCanvas object.

bool Controller::Paint (HDC hdc) {

_view.Paint (_h);

// validate painted area

PaintCanvas canvas (_h);

return true;

}

In response to WM_TIMER, we kill the timer, tell the World to move one frame ahead, let the View repaint the frame on the back surface, invalidate the window (so that Paint is called) and set the timeout again.

bool Controller::Timer (int id, TIMERPROC * proc) {

_timer.Kill ();

_world->Step ();

_view.Update ();

// force repaint

_h.Invalidate (false);

_timer.Set (10);

return true;

}

There is one more thing. DirectX doesn't like when a screen saver kicks in, so we have to preempt it.

bool Controller::SysCommand (int cmd) {

// disable screen savers

if (cmd == SC_SCREENSAVE || cmd == SC_MONITORPOWER) return true;

return false;

}

By the way, this is how SysCommand is called from the window procedure:

case WM_SYSCOMMAND:

if (pCtrl->SysCommand (wParam & 0xfff0)) return 0;

break;

Let's now have a closer look at View, which is the class dealing with output to screen. Notice two important data members, the Direct::Draw object and the Direct::Surface object.

class View {

public: View ();

void Create (HWND h, World * world);

void Size (HWND h, int width, int height);

void Update ();

void Paint (HWND h);

private:

Direct::Draw_draw;

Direct::Surface_backSurface;

World * _world;

int _dx;

int _dy;

};

I have encapsulated all DirectX classes inside the namespace Direct. this trick enforces a very nice naming convention, namely, you have to prefix all directx classes with the prefix Direct::.

The Direct::Draw object's duty is to initialize the DirectX subsystem. It does it in it's constructor, so any time View is constructed (once per program instantiation), DirectX is ready to use. It's destructor, by the way, frees the resources used by DirectX.

Direct::Surface _backSurface will be used by View to draw the animation upon it.

The initialization of DirectX also involves setting up the collaboration level with Windows. Here, we are telling it to work nicely with other windows, rather then taking over in the full-screen mode.

void View::Create (HWND h, World * world) {

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

Интервал:

Закладка:

Сделать

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

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


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

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

x