А. Легалов - Применение Windows API

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

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

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

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

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

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

Интервал:

Закладка:

Сделать

void Update() {

:: UpdateWindow(_hwnd);

}

// Moving

void Move(int x, int y, int width, int height) {

:: MoveWindow(_hwnd, x, y, width, height, TRUE);

}

void MoveDelayPaint(int x, int y, int width, int height) {

:: MoveWindow(_hwnd, x, y, width, height, FALSE);

}

// Repainting

void Invalidate() {

:: InvalidateRect(_hwnd, 0, TRUE);

}

void ForceRepaint() {

Invalidate();

Update();

}

private:

HWND _hwnd;

};

Как обычно, Вы можете загрузить полный исходный текст приложения, которое использовалось в этом примере.

Далее: Следующая обучающая программа рассказывает о растрах.

Bitmaps

In this tutorial we'll learn how to load bitmaps from resources and from files, how to pass them around and blit them to the screen. We'll also see how to create and use an empty bitmap as a canvas, draw a picture on it and then blit it to the screen. Finally, we'll combine these techniques to write a simple program that uses double-buffering and timer messages to show a simple animation involving sprites.

First of all, in most cases Windows provides storage for bitmaps and takes care of the formatting of bits. The programmer gets access to the bitmap through a handle, whose type is HBITMAP. (Remember to set the STRICTflag when compiling Windows programs, to make sure HBITMAP is a distinct type, rather than just a pointer to void.)

Since a bitmap is a resource (in the Resource Managementsense), the first step is to encapsulate it in a “strong pointer” type of interface. Notice the transfer semantics of the constructor and the overloaded assignment operator, characteristic of a resource that can have only one owner at a time.

We instruct Windows to release the resources allocated to the bitmap by calling DeleteObject.

class Bitmap{

public:

Bitmap() : _hBitmap (0) {}

// Transfer semantics

Bitmap(Bitmap& bmp) : _hBitmap(bmp.Release()) {}

void operator=(Bitmap& bmp) {

if (bmp._hBitmap != _hBitmap) {

Free();

_hBitmap = bmp.Release();

}

}

HBITMAP Release() {

HBITMAP h = _hBitmap;

_hBitmap = 0;

return h;

}

~Bitmap() {

Free();

}

// implicit conversion for use with Windows API

operator HBITMAP() {

return _hBitmap;

}

protected:

Bitmap(HBITMAP hBitmap) : _hBitmap(hBitmap) {}

void Free() {

if (_hBitmap) :: DeleteObject(_hBitmap);

}

HBITMAP _hBitmap;

};

Now that the management issues are out of the way, we can concentrate on loading bitmaps. The simplest way to include a bitmap in your program is to add it to the resource file. In the resource editor of your development environment you can create new bitmaps or import them from external files. You can either give them names (strings) or numerical ids. When you want to access such a bitmap in your program you have to load it from the resources. Here are two methods that do just that. You have to give them a handle to the program instance.

void Bitmap::Load(HINSTANCE hInst, char const * resName) {

Free();

_hBitmap = (HBITMAP):: LoadImage(hInst, resName, IMAGE_BITMAP, 0, 0, LR_CREATEDIBSECTION);

if (_hBitmap == 0) throw WinException("Cannot load bitmap from resources", resName);

}

void Bitmap::Load(HINSTANCE hInst, int id) {

Free();

_hBitmap = (HBITMAP):: LoadImage(hInst, MAKEINTRESOURCE(id), IMAGE_BITMAP, 0, 0, LR_CREATEDIBSECTION);

if (_hBitmap == 0) throw WinException("Cannot load bitmap from resources");

}

Loading a bitmap directly from a file is also very simple and can be done using the same API, LoadImage. Remember, it will only work if the file is a Windows (or OS/2) bitmap — such files usually have the extension .bmp. There is no simple way of loading other types of graphics files, .gif, .jpg, .png, etc. You have to know their binary layout and decode them explicitly (there are other web sites that have this information).

void Bitmap::Load(char* path) {

Free();

_hBitmap = (HBITMAP):: LoadImage(0, path, IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE);

if(_hBitmap == 0) throw WinException("Cannot load bitmap from file", path);

}

Once you got hold of a bitmap, you may want to enquire about its dimensions. Here's how you do it.

void Bitmap::GetSize(int& width, int& height) {

BITMAP bm;

:: GetObject(_hBitmap, sizeof(bm), &bm);

width = bm.bmWidth;

height = bm.bmHeight;

}

Finally, you might want to create an empty bitmap and fill it with your own drawings programmatically. You have to specify the dimensions of the bitmap and you have to provide a device context (Canvas) for which the bitmap is targeted. Windows will create a different type of bitmap when your target is a monochrome monitor or printer, and different when it's a graphics card set to True Color. Windows will create a bitmap that is compatible with the target device.

Bitmap::Bitmap(Canvas& canvas, int dx, int dy) : _hBitmap (0) {

CreateCompatible(canvas, dx, dy);

}

void Bitmap::CreateCompatible(Canvas& canvas, int width, int height) {

Free();

_hBitmap = :: CreateCompatibleBitmap(canvas, width, height);

}

How do you display the bitmap on screen? You have to blit it. Blit stands for "block bit transfer" or something like that. When you blit a bitmap, you have to specify a lot of parameters, so we'll just encapsulate the blitting request in a separate object, the blitter. This is a very handy object that sets the obvious defaults for blitting, but at the same time lets you override each and any of them.

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

Интервал:

Закладка:

Сделать

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

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


libcat.ru: книга без обложки
Неизвестный Автор
Отзывы о книге «Применение Windows API»

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

x