На главную

On-line справка по Win32 API

Написать письмо
БЕСПЛАТНАЯ ежедневная online лотерея! Выигрывай каждый день БЕСПЛАТНО!
Список всех статей A-B-C-D-E-F-G-H-I-J-K-L-M-N-O-P-Q-R-S-T-U-V-W-X-Y-Z | Скачать Вниз

Drawing at Timed Intervals



You can draw at timed intervals by creating a timer with the SetTimer function. By using a timer to send WM_TIMER messages to the window procedure at regular intervals, an application can carry out simple animation in the client area while other applications continue running.

In the following example, the application bounces a star from side to side in the client area. Each time the window procedure receives a WM_TIMER message, the procedure erases the star at the current position, calculates a new position, and draws the star within the new position. The procedure starts the timer by calling SetTimer while processing the WM_CREATE message.

RECT rcCurrent = {0,0,20,20};
POINT aptStar[6] = {10,1, 1,19, 19,6, 1,6, 19,19, 10,1};
int X = 2, Y = -1, idTimer = -1;
BOOL fVisible = FALSE;
HDC hdc;

LRESULT APIENTRY WndProc(hwnd, message, wParam, lParam)
HWND hwnd;
UINT message;
WPARAM wParam;
LPARAM lParam;
{
PAINTSTRUCT ps;
RECT rc;

switch (message) {
case WM_CREATE:

/* Calculate the starting point. */

GetClientRect(hwnd, &rc);

OffsetRect(&rcCurrent, rc.right / 2, rc.bottom / 2);

/* Initialize the private DC. */

hdc = GetDC(hwnd);
SetViewportOrgEx(hdc, rcCurrent.left,
rcCurrent.top, NULL);
SetROP2(hdc, R2_NOT);

/* Start the timer. */

SetTimer(hwnd, idTimer = 1, 10, NULL);
return 0L;

case WM_DESTROY:
KillTimer(hwnd, 1);
PostQuitMessage(0);

return 0L;

case WM_SIZE:
switch (wParam) {
case SIZE_MINIMIZED:

/* Stop the timer if the window is minimized. */

KillTimer(hwnd, 1);
idTimer = -1;
break;

case SIZE_RESTORED:

/*
* Move the star back into the client area
* if necessary.

*/

if (rcCurrent.right > (int) LOWORD(lParam))
rcCurrent.left =
(rcCurrent.right =
(int) LOWORD(lParam)) - 20;
if (rcCurrent.bottom > (int) HIWORD(lParam))
rcCurrent.top =
(rcCurrent.bottom =
(int) HIWORD(lParam)) - 20;

/* Fall through to the next case. */


case SIZE_MAXIMIZED:

/* Start the timer if it had been stopped. */

if (idTimer == -1)
SetTimer(hwnd, idTimer = 1, 10, NULL);
break;
}
return 0L;

case WM_TIMER:

/* Hide the star if it is visible. */

if (fVisible)
Polyline(hdc, aptStar, 6);

/* Bounce the star off a side if necessary. */


GetClientRect(hwnd, &rc);
if (rcCurrent.left + X < rc.left ||
rcCurrent.right + X > rc.right)
X = -X;
if (rcCurrent.top + Y < rc.top ||
rcCurrent.bottom + Y > rc.bottom)
Y = -Y;

/* Show the star in its new position. */

OffsetRect(&rcCurrent, X, Y);
SetViewportOrgEx(hdc, rcCurrent.left,
rcCurrent.top, NULL);

fVisible = Polyline(hdc, aptStar, 6);

return 0L;

case WM_ERASEBKGND:

/* Erase the star. */

fVisible = FALSE;
return DefWindowProc(hwnd, message, wParam, lParam);

case WM_PAINT:

/*
* Show the star if it is not visible. Use BeginPaint
* to clear the update region.
*/

BeginPaint(hwnd, &ps);
if (!fVisible)

fVisible = Polyline(hdc, aptStar, 6);
EndPaint(hwnd, &ps);
return 0L;
}
return DefWindowProc(hwnd, message, wParam, lParam);
}


This application uses a private DC to minimize the time required to prepare the DC for drawing. The window procedure retrieves and initializes the private DC when processing the WM_CREATE message, setting the binary raster operation mode to allow the star to be erased and drawn using the same call to the Polyline function. The window procedure also sets the viewport origin to allow the star to be drawn using the same set of points regardless of the star's position in the client area.

The application uses the WM_PAINT message to draw the star whenever the window must be updated. The window procedure draws the star only if it is not visible; that is, only if it has been erased by the WM_ERASEBKGND message. The window procedure intercepts the WM_ERASEBKGND message to set the fVisible variable, but passes the message to DefWindowProc so that Windows can draw the window background.
The application uses the WM_SIZE message to stop the timer when the window is minimized and to restart the timer when the minimized window is restored. The window procedure also uses the message to update the current position of the star if the size of the window has been reduced so that the star is no longer in the client area. The application keeps track of the star's current position by using the structure specified by rcCurrent, which defines the bounding rectangle for the star. Keeping all corners of the rectangle in the client area keeps the star in the area. The window procedure initially centers the star in the client area when processing the WM_CREATE message.


Пригласи друзей и счет твоего мобильника всегда будет положительным!
Предыдущая статья
 
Сайт Народ.Ру Интернет
Следующая статья
Пригласи друзей и счет твоего мобильника всегда будет положительным!

Чертеж в Синхронизированных Интервалах



Вы можете сделать в синхронизированных интервалах создавая таймер с функцией SetTimer. Используя таймер, чтобы посылать сообщения WM_TIMER в процедуру окна в регулярных интервалах, приложение может выполнить простое оживление в области клиента тогда как другие приложения продолжают работать.

В следующем примере, приложение прыгает звезду от стороны до стороны в области клиента. Всякий раз, когда процедура окна получает сообщение WM_TIMER, процедура стирает звезду в текущей позиции, вычисляет новую позицию и делает звездой в пределах новой позиции. Процедура начинает таймер вызывая SetTimer при обработке сообщения WM_CREATE.

RECT rcCurrent = {0,0,20,20};
ТОЧКА aptStar[6] = {10,1, 1,19, 19,6, 1,6, 19,19, 10,1};
int X = 2, Y = -1, idTimer = -1;
BOOL fVisible = ЛОЖЬ;
hdc HDC;

LRESULT APIENTRY WndProc(hwnd, СООБЩЕНИЕ, wParam, lParam) HWND hwnd;
СООБЩЕНИЕ UINT;
WPARAM wParam;
LPARAM lParam;
{
ps PAINTSTRUCT;
rc RECT;

ключ (сообщение) { случай WM_CREATE:

/* Вычислите запуск point. */

GetClientRect(hwnd, &rc);

OffsetRect(&rcCurrent, rc.right / 2, rc.bottom / 2);

/* Инициализируйте частный DC. */

hdc = GetDC(hwnd);
SetViewportOrgEx(hdc, rcCurrent.left, rcCurrent.top, НЕДЕЙСТВИТЕЛЬНЫЙ);
SetROP2(hdc, R2_NOT);

/* Запустите timer. */

SetTimer(hwnd, idTimer = 1, 10, НЕДЕЙСТВИТЕЛЬНОЕ);
возвращайте 0L;

случай WM_DESTROY: KillTimer(hwnd, 1);
PostQuitMessage(0);

возвращайте 0L;

случай WM_SIZE: ключ (wParam) { случай SIZE_MINIMIZED:

/* Остановите таймер если окно является minimized. */

KillTimer(hwnd, 1);
idTimer = -1;
прерывание;

случай SIZE_RESTORED:

/*
* Переместите звезду снова в область клиента
* если необходимо.

*/

если (rcCurrent.right > (int) LOWORD(lParam)) rcCurrent.left = (rcCurrent.right = (int) LOWORD(lParam)) - 20;
если (rcCurrent.bottom > (int) HIWORD(lParam)) rcCurrent.top = (rcCurrent.bottom = (int) HIWORD(lParam)) - 20;

/* Провалите в следующий case. */


случай SIZE_MAXIMIZED:

/* Запустите таймер если это было stopped. */

если (idTimer == -1) SetTimer(hwnd, idTimer = 1, 10, НЕДЕЙСТВИТЕЛЬНОЕ);
прерывание;
}
возвращайте 0L;

случай WM_TIMER:

/* Спрячьте звезду если это visible. */

если Ломаная линия (fVisible)(hdc, aptStar, 6);

/* Прыгните звезде сторону если necessary. */


GetClientRect(hwnd, &rc);
если (rcCurrent.left + X < rc.left || rcCurrent.right + X > rc.right) X = -X;
если (rcCurrent.top + Y < rc.top || rcCurrent.bottom + Y > rc.bottom) Y = -Y;

/* Покажите звезду в своем новом position. */

OffsetRect(&rcCurrent, X, Y);
SetViewportOrgEx(hdc, rcCurrent.left, rcCurrent.top, НЕДЕЙСТВИТЕЛЬНЫЙ);

fVisible = Ломаная линия(hdc, aptStar, 6);

возвращайте 0L;

случай WM_ERASEBKGND:

/* Выстирайте звезду. */

fVisible = ЛОЖЬ;
возвращайте DefWindowProc(hwnd, сообщение, wParam, lParam);

случай WM_PAINT:

/*
* Покажите звезду если это не видимое. Использование BeginPaint
*, чтобы очищать регион коррекции.
*/

BeginPaint(hwnd, &ps);
если (!fVisible)

fVisible = Ломаная линия(hdc, aptStar, 6);
EndPaint(hwnd, &ps);
возвращайте 0L;
}
возвращайте DefWindowProc(hwnd, сообщение, wParam, lParam);
}


Это приложение использует частный DC, чтобы минимизировать время требовавшееся, чтобы подготавливать DC к чертежу. Процедура окна извлекает и инициализирует частный DC при обработке сообщения WM_CREATE, устанавливающем двоичный растровый способ действия, чтобы допускать звезду, которая нужно стирать и сделанным используя тот же вызов в функцию Ломаной линии. Процедура окна также устанавливает начало viewport, чтобы допускать звезду, которая нужно делать использованием того же набора точек независимо от звездной позиции в области клиента.

Приложение использует сообщение WM_PAINT, чтобы делать звездой всякий раз, когда окно должно быть скорректировано. Процедура окна делает звездой только если она не видимая; то есть, только если выстирано сообщением WM_ERASEBKGND. Процедура окна прерывает сообщение WM_ERASEBKGND, чтобы устанавливать переменную fVisible но передавать сообщение на DefWindowProc чтобы Окно может сделать фоном окна.
Приложение использует сообщение WM_SIZE, чтобы останавливать таймер когда окно минимизировано и, чтобы перезапускать таймер когда минимизированное окно восстановлено. Процедура окна также использует сообщение, чтобы корректировать текущую позицию звезды если размер окна уменьшен чтобы звезда не - больше в области клиента. Приложение следит звездной текущей позиции используя структуру определялся rcCurrent, которое определяет прямоугольник bounding для звезды. Хранение всех углов прямоугольника в области клиента держит звезду в области. Процедура окна первоначально центрирует звезду в области клиента при обработке сообщения WM_CREATE.


Вверх Version 1.3, Oct 26 2010 © 2007, 2010, mrhx Вверх
 mrhx software  Русский перевод OpenGL  Русский перевод Win32 API
 
Используются технологии uCoz