Читаем Применение Windows API полностью

В этой точке мы должны стереть вертикальную строку в последний раз. Однако, мы не делаем это непосредственно — мы используем здесь небольшой прием. Мы прекращаем сбор данных мыши. Как побочный эффект, Windows посылает нам сообщение WM_CAPTURECHANGED. Во время обработки этого сообщения, мы фактически и стираем вертикальную строку.

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);

}

Почему мы делаем это таким образом? Потому, что Windows может заставить нас, прекратить обработку данных от мыши прежде, чем пользователь опустит ее кнопку. Это может случиться, например, когда другое приложение внезапно решает распахнуть его окно, в то время как пользователь находится в процессе перемещения. В этом случае наше окно никогда не получило бы сообщение об отжатии кнопки. Если бы мы не были так умны, мы бы не были способны чисто перемещаться. К счастью, перед завершением обработки данных мыши, Windows сумеет послать нам сообщение WM_CAPTURECHANGED, и мы примем его к сведению, чтобы сделать нашу очистку.

Вернемся снова к LBUTTONUP — когда пользователь заканчивает перемещение, мы посылаем родителю наше специальное сообщение MSG_MOVESPLITTER, передавая ему новую позицию центра полосы расщепителя, измеряемой в координатах клиентской области родителя. Вы уже видели клиентский код, реагирующий на это сообщение.

Здесь показано, как можно определить клиентское сообщение.

// 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;

В заключение представлен фрагмент из очень полезного класса HWnd, который инкапсулирует многие базисных функции API Windows, имеющие дело с окнами. В частности, рассмотрите методы MoveDelayPaint и ForceRepaint, который мы использовали в перерисовке полоски расщепителя.

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;

};

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

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

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 STRICT flag 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) {

Перейти на страницу:

Похожие книги

1С: Управление торговлей 8.2
1С: Управление торговлей 8.2

Современные торговые предприятия предлагают своим клиентам широчайший ассортимент товаров, который исчисляется тысячами и десятками тысяч наименований. Причем многие позиции могут реализовываться на разных условиях: предоплата, отсрочка платежи, скидка, наценка, объем партии, и т.д. Клиенты зачастую делятся на категории – VIP-клиент, обычный клиент, постоянный клиент, мелкооптовый клиент, и т.д. Товарные позиции могут комплектоваться и разукомплектовываться, многие товары подлежат обязательной сертификации и гигиеническим исследованиям, некондиционные позиции необходимо списывать, на складах периодически должна проводиться инвентаризация, каждая компания должна иметь свою маркетинговую политику и т.д., вообщем – современное торговое предприятие представляет живой организм, находящийся в постоянном движении.Очевидно, что вся эта кипучая деятельность требует автоматизации. Для решения этой задачи существуют специальные программные средства, и в этой книге мы познакомим вам с самым популярным продуктом, предназначенным для автоматизации деятельности торгового предприятия – «1С Управление торговлей», которое реализовано на новейшей технологической платформе версии 1С 8.2.

Алексей Анатольевич Гладкий

Финансы / Программирование, программы, базы данных
C++ Primer Plus
C++ Primer Plus

C++ Primer Plus is a carefully crafted, complete tutorial on one of the most significant and widely used programming languages today. An accessible and easy-to-use self-study guide, this book is appropriate for both serious students of programming as well as developers already proficient in other languages.The sixth edition of C++ Primer Plus has been updated and expanded to cover the latest developments in C++, including a detailed look at the new C++11 standard.Author and educator Stephen Prata has created an introduction to C++ that is instructive, clear, and insightful. Fundamental programming concepts are explained along with details of the C++ language. Many short, practical examples illustrate just one or two concepts at a time, encouraging readers to master new topics by immediately putting them to use.Review questions and programming exercises at the end of each chapter help readers zero in on the most critical information and digest the most difficult concepts.In C++ Primer Plus, you'll find depth, breadth, and a variety of teaching techniques and tools to enhance your learning:• A new detailed chapter on the changes and additional capabilities introduced in the C++11 standard• Complete, integrated discussion of both basic C language and additional C++ features• Clear guidance about when and why to use a feature• Hands-on learning with concise and simple examples that develop your understanding a concept or two at a time• Hundreds of practical sample programs• Review questions and programming exercises at the end of each chapter to test your understanding• Coverage of generic C++ gives you the greatest possible flexibility• Teaches the ISO standard, including discussions of templates, the Standard Template Library, the string class, exceptions, RTTI, and namespaces

Стивен Прата

Программирование, программы, базы данных