Brook Miles - theForger's Win32 API Tutorial

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

theForger's Win32 API Tutorial: краткое содержание, описание и аннотация

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

Visit
Software! Code North
This tutorial attempts to get you started developing with the Win32 API as quickly and clearly as possible. It's meant to be read as a whole You may use this tutorial for absolutely no charge, however there are costs associated with hosting it on the web. If you found it to be of use to you and want to give something back, I would be grateful for donations of any amount to help pay for this website. This page gets approximately 11 thousand hits a month, and it adds up after a while :)
Enjoy the tutorial,
Brook
I would like to thank the following for the contributions they've made: Yih Horng, Todd Troxell, T Frank Zvovushe, Suzanne Lorrin, Seth McCarus, Crispina Chong, John Crutchfield, Scott Johnstone, Patrick Sears. As well as those who have simply written to say they've found the tutorial useful. It's much appreciated!
Welcome to Version 2.0 of theForger's Win32 API Tutorial

theForger's Win32 API Tutorial — читать онлайн бесплатно полную книгу (весь текст) целиком

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

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

Интервал:

Закладка:

Сделать

case ID_FILE_NEW:

CreateNewMDIChild(g_hMDIClient);

break;

case ID_FILE_OPEN:

{

HWND hChild = CreateNewMDIChild(g_hMDIClient);

if (hChild) {

DoFileOpen(hChild);

}

}

break;

case ID_FILE_CLOSE:

{

HWND hChild = (HWND)SendMessage(g_hMDIClient, WM_MDIGETACTIVE,0,0);

if (hChild) {

SendMessage(hChild, WM_CLOSE, 0, 0);

}

}

break;

We can also provide some default MDI processing of window arrangment for our Window menu, since MDI supports this itself it's not much work.

case ID_WINDOW_TILE:

SendMessage(g_hMDIClient, WM_MDITILE, 0, 0);

break;

case ID_WINDOW_CASCADE:

SendMessage(g_hMDIClient, WM_MDICASCADE, 0, 0);

break;

Graphics Device Interface

Bitmaps, Device Contexts and BitBlt

Example: bmp_one

GDI

The really great thing about MS Windows is that unlike DOS, you don't need to know anything about what video hardware you are using to display graphics. Instead, windows provides an API called the Graphics Device Interface, or GDI. The GDI uses a set of generic graphics objects that can be used to draw to the screen, to memory, or even to printers.

Device Contexts

The GDI revolves around an object called the Device Context (DC), represented by the data type HDC (Handle to Device Context). An HDC is basically a handle to something you can draw on; it can represent the entire screen, an entire window, the client area of a window, a bitmap stored in memory, or a printer. The nice part is that you don't even need to know which one it refers to, you can use it basically the same way, which is especially handy for writing custom drawing functions which you can then use on any of these devices without changing it for each one.

An HDC like most GDI objects is opaque, meaning that you can't access it's data directly… but you can pass it to various GDI functions that will operate on it, either to draw something, get information about it, or change the object in some way.

For example, if you wanted to draw on a window, first you would retreive an HDC representing the window with GetDC() , then you could use any of the GDI functions that take an HDC like BitBlt() for drawing images, TextOut() for drawing text, LineTo() for lines and so on.

Bitmaps

Bitmaps can be loaded much like icons in earlier examples, there is LoadBitmap() for the most basic functionality of simply loading a bitmap resource, and LoadImage() can be used to load bitmaps from a *.bmp file just as it can for icons.

One of the quirks of GDI is that you can't draw to bitmap objects ( HBITMAP type) directly. Remember that drawing operations are abstracted by Device Contexts, so in order to use these drawing functions on a bitmap, you need to create a Memory DC, and then select the HBITMAP into it with SelectObject() . The effect is that the "device" that the HDC refers to is the bitmap in memory, and when you operate on the HDC , the resulting graphic operations are applied to the bitmap. As I mentioned, this is actually a very conveiniant way of doing things, as you can write code that draws to an HDC and you can use it on a Window DC or a Memory DC without any checks or changes.

You do have the option of manipulating the bitmap data in memory yourself. You can do this with Device Independant Bitmaps (DIB), and you can even combine GDI and manual operations on the DIB. However for the time being, this is beyond the scope of the basic tutorial and for now we're just cover the simpler GDI operations on their own.

GDI Leaks

Once you're finished with an HDC , it's very important to release it (just how you do that depends on how you got it, which we'll talk about in a bit). GDI objects are limited in number. In versions of windows prior to Windows 95, they were not only incredably limited but also shared system wide, so that if one program used up too many, none of the rest would be able to draw anything! Fortunately this isn't the case any longer, and you could get away with using up quite a lot of resources in Windows 2000 or XP before anything too bad happened… but it's easy to forget to free GDI objects and they can quickly run your program out of GDI resources under Windows 9x. Theorehtically you shouldn't be able to drain the system of GDI resources in NT systems (NT/2K/XP) but it still happens in extreme cases, or if you hit the right bug on the nose.

If your program runs fine for a few minutes and then starts drawing strangely or not at all, it's a good sign that you're leaking GDI resources. HDCs aren't the only GDI objects you need to be careful about releasing, but generally it's ok to keep things like bitmaps and fonts around for the entire lifetime of your program, since it's much more efficiant than reloading them each time you need them.

Also, an HDC can only contain one of each type of object (bitmap, font, pen…) at a time, and when you select a new one in it will return the last one. It's very important that you deal with this object properly. If you ignore it completely, it will be lost and they will pile up in memory causing GDI leaks. When an HDC is created, it's also created with some default objects selected into it… it's a good idea to store these when they are returned to you, and then when you are completed drawing with the HDC select them back into it. This will not only remove any of your own objects from the HDC (which is a good thing) but it will also cause the default objects to be properly disposed of when you release or destroy the HDC (a VERY good thing).

Important Update:Not all objects have defaults selected into HDC s, and you can refer to MSDN for the few that don't. Because of this I was previously uncertain as to wether HBITMAP s were one of them, since there doesn't seem to be any definitive documentation on it, and examples (even those by Microsoft) often ignored the default bitmap. Since the writing of the original tutorial several years ago, it was confirmed to me that there was in fact a default bitmap that needs releasing. This information is courtesy of Shaun Ivory, a software engineer for MS and a friend of mine from #winprog.

Apparently there was a bug in a screensaver written at MS, and it turns out it was because the default bitmap wasn't getting replaced or destroyed, and it eventually ran out of GDI resources. Be warned! It's an easy mistake to make.

Displaying Bitmaps

Ok, down to business. The simplest drawing operations on a window occure by handling WM_PAINT . When your window is first displayed, restored from being minimised, or uncovered from having another window on top of it, Windows sends the WM_PAINT message to the window to let it know that it needs to redraw it's contents. When you draw something on the screen it is NOT permanent, it's only there untill something else draws over it, and at that point you need to draw it again when the time comes.

HBITMAP g_hbmBall = NULL;

case WM_CREATE:

g_hbmBall = LoadBitmap(GetModuleHandle(NULL), MAKEINTRESOURCE(IDB_BALL));

if (g_hbmBall == NULL) MessageBox(hwnd, "Could not load IDB_BALL!", "Error", MB_OK | MB_ICONEXCLAMATION);

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

Интервал:

Закладка:

Сделать

Похожие книги на «theForger's Win32 API Tutorial»

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


Отзывы о книге «theForger's Win32 API Tutorial»

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

x