Windows API Tutorials
Здесь есть возможность читать онлайн «Windows API Tutorials» весь текст электронной книги совершенно бесплатно (целиком полную версию без сокращений). В некоторых случаях можно слушать аудио, скачать через торрент в формате fb2 и присутствует краткое содержание. Жанр: Программирование, на английском языке. Описание произведения, (предисловие) а так же отзывы посетителей доступны на портале библиотеки ЛибКат.
- Название:Windows API Tutorials
- Автор:
- Жанр:
- Год:неизвестен
- ISBN:нет данных
- Рейтинг книги:3 / 5. Голосов: 1
-
Избранное:Добавить в избранное
- Отзывы:
-
Ваша оценка:
- 60
- 1
- 2
- 3
- 4
- 5
Windows API Tutorials: краткое содержание, описание и аннотация
Предлагаем к чтению аннотацию, описание, краткое содержание или предисловие (зависит от того, что написал сам автор книги «Windows API Tutorials»). Если вы не нашли необходимую информацию о книге — напишите в комментариях, мы постараемся отыскать её.
Windows API Tutorials — читать онлайн бесплатно полную книгу (весь текст) целиком
Ниже представлен текст книги, разбитый по страницам. Система сохранения места последней прочитанной страницы, позволяет с удобством читать онлайн бесплатно книгу «Windows API Tutorials», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.
Интервал:
Закладка:
void SplitController::LButtonDrag(POINTS pt) {
if (_hwnd.HasCapture ()) {
// Erase previous divider and draw new one
UpdateCanvas canvas (_hwndParent);
ModeSetter mode (canvas, R2_NOTXORPEN);
canvas.Line (_dragX, 0, _dragX, _cy - 1);
_dragX = _dragStart + pt.x;
canvas.Line (_dragX, 0, _dragX, _cy - 1);
}
}
We draw the vertical line in the xor mode using the previous remembered position. Since this is the second time we draw this line in the same place, the net result will be the restoration of the original pixels from under the line. Then we draw the new line in the new position, still in the xor mode. We remember this position, so that next time LButtonDragis called we'll erase it too. And so on, until finally the user releases the mouse button.
void SplitController::LButtonUp(POINTS pt) {
// Calling ReleaseCapture will send us the WM_CAPTURECHANGED
_hwnd.ReleaseMouse ();
_hwndParent.SendMessage (MSG_MOVESPLITTER, _dragStart + pt.x);
}
At this point we should erase the vertical line for the last time. However, we don't do it directly--we use a little trick here. We release the mouse capture. As a side effect, Windows sends us the WM_CAPTURECHANGEDmessage. It's during the processing of that message that we actually erase the vertical line.
void SplitController::CaptureChanged() {
// We are losing capture
// End drag selection — for whatever reason
// Erase previous divider
UpdateCanvas canvas (_hwndParent);
ModeSetter mode (canvas, R2_NOTXORPEN);
canvas.Line (_dragX, 0, _dragX, _cy - 1);
}
Why do we do that? It's because Windows can force us to release the mouse capture before the user releases the mouse button. It might happen, for instance, when another application suddenly decides to pop up its window while the user is in the middle of dragging. In such a case our window would never get the button-up message and, if we weren't clever, wouldn't be able to cleanly finish the drag. Fortunately, before taking away the mouse capture, Windows manages to send us the WM_CAPTURECHANGEDmessage, and we take it as a clue to do our cleanup.
Going back to LButtonUp— once the user finishes dragging, we send the parent our special message MSG_MOVESPLITTER, passing it the new position of the center of the splitter bar measured in parent's client area coordinates. You've already seen the client code response to this message.
This is how one might define a client message.
// Reserved by Reliable Software Library
const UINT MSG_RS_LIBRARY = WM_USER + 0x4000;
// wParam = new position wrt parent's left edge
const UINT MSG_MOVESPLITTER = MSG_RS_LIBRARY + 1;
Finally, here's an excerpt from a very useful class HWndthat encapsulates a lot of basic Windows APIs that deal with windows. In particular, look at the methods MoveDelayPaintand ForceRepaintthat we used in repainting the splitter bar.
class HWnd{
public:
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;
};
Next tutorial talks about bitmaps.
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 Management sense), 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.
Читать дальшеИнтервал:
Закладка:
Похожие книги на «Windows API Tutorials»
Представляем Вашему вниманию похожие книги на «Windows API Tutorials» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.
Обсуждение, отзывы о книге «Windows API Tutorials» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.