На главную

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 Lines with the Mouse



The example in this section demonstrates how to track the mouse cursor. It contains portions of a window procedure that enables the user to draw lines in a window's client area by dragging the mouse.

When the window procedure receives a WM_LBUTTONDOWN message, it captures the mouse and saves the coordinates of the cursor, using the coordinates as the starting point of the line. It also uses the ClipCursor function to confine the cursor to the client area during the line drawing operation.
During the first WM_MOUSEMOVE message, the window procedure draws a line from the starting point to the current position of the cursor. During subsequent WM_MOUSEMOVE messages, the window procedure erases the previous line by drawing over it with an inverted pen color. Then it draws a new line from the starting point to the new position of the cursor.

The WM_LBUTTONUP message signals the end of the drawing operation. The window procedure releases the mouse capture and frees the mouse from the client area.

LRESULT APIENTRY MainWndProc(hwndMain, uMsg, wParam, lParam)
HWND hwndMain;
UINT uMsg;
WPARAM wParam;
LPARAM lParam;
{
HDC hdc; /* handle of device context */
RECT rcClient; /* client area rectangle */
POINT ptClientUL; /* client upper left corner */
POINT ptClientLR; /* client lower right corner */
static POINTS ptsBegin; /* beginning point */

static POINTS ptsEnd; /* new endpoint */
static POINTS ptsPrevEnd; /* previous endpoint */
static BOOL fPrevLine = FALSE; /* previous line flag */

switch (uMsg) {
case WM_LBUTTONDOWN:

/* Capture mouse input. */

SetCapture(hwndMain);

/*
* Retrieve the screen coordinates of the client area,
* and convert them into client coordinates.

/*

GetClientRect(hwndMain, &rcClient);
ptClientUL.x = rcClient.left;
ptClientUL.y = rcClient.top;

/*
* Add one to the right and bottom sides, because the
* coordinates retrieved by GetClientRect do not
* include the far left and lowermost pixels.
*/

ptClientLR.x = rcClient.right + 1;
ptClientLR.y = rcClient.bottom + 1;

ClientToScreen(hwndMain, &ptClientUL);
ClientToScreen(hwndMain, &ptClientLR);

/*
* Copy the client coordinates of the client area
* to the rcClient structure. Confine the mouse cursor
* to the client area by passing the rcClient structure
* to the ClipCursor function.
*/

SetRect(&rcClient, ptClientUL.x, ptClientUL.y,
ptClientLR.x, ptClientLR.y);

ClipCursor(&rcClient);

/*
* Convert the cursor coordinates into a POINTS
* structure, which defines the beginning point of the
* line drawn during a WM_MOUSEMOVE message.
*/

ptsBegin = MAKEPOINTS(lParam);
return 0;

case WM_MOUSEMOVE:

/*
* When moving the mouse, the user must hold down
* the left mouse button to draw lines.

*/

if (wParam & MK_LBUTTON) {

/*
* Retrieve a device context (DC) for the client
* area.
*/

hdc = GetDC(hwndMain);

/*
* The following function ensures that pixels of
* the previously drawn line are set to white and
* those of the new line are set to black.
*/


SetROP2(hdc, R2_NOTXORPEN);

/*
* If a line was drawn during an earlier
* WM_MOUSEMOVE message, draw over it. This erases
* the line by setting the color of its pixels to
* white.
*/

if (fPrevLine) {
MoveToEx(hdc, ptsBegin.x, ptsBegin.y,
(LPPOINT) NULL);
LineTo(hdc, ptsPrevEnd.x, ptsPrevEnd.y);

}

/*
* Convert the current cursor coordinates to a
* POINTS structure, and then draw a new line.
*/

ptsEnd = MAKEPOINTS(lParam);
MoveToEx(hdc, ptsBegin.x, ptsBegin.y,
(LPPOINT) NULL);
LineTo(hdc, ptsEnd.x, ptsEnd.y);

/*
* Set the previous line flag, save the ending

* point of the new line, and then release the DC.
*/

fPrevLine = TRUE;
ptsPrevEnd = ptsEnd;
ReleaseDC(hwndMain, hdc);
}
break;

case WM_LBUTTONUP:

/*
* The user has finished drawing the line. Reset the
* previous line flag, release the mouse cursor, and
* release the mouse capture.

*/

fPrevLine = FALSE;
ClipCursor(NULL);
ReleaseCapture();
return 0;

case WM_DESTROY:
PostQuitMessage(0);
break;

.
. /* Process other messages. */
.



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

Чертеж Линий с Мышью



Пример в этой секции демонстрирует как, чтобы прослеживать курсор мыши. Это содержит части процедуры окна, которое позволяет потребителя, чтобы делать линиями в области клиента окна таща мышь.

Когда процедура окна получает сообщение WM_LBUTTONDOWN, она захватывает мышь и сохраняет координаты курсора, используя координаты как отправной пункт линии. Это также использует функцию ClipCursor, чтобы ограничивать курсор в область клиента в течение линии, рисующей действие.
В течение первого сообщения WM_MOUSEMOVE, процедура окна вытаскивает линию из отправного пункта в текущую позицию курсора. В течение последующих сообщений WM_MOUSEMOVE, процедура окна стирает предшествующую линию рисуясь над этим с инвертировать цветом ручки. Затем это вытаскивает новую линию из отправного пункта в новую позицию курсора.

Сообщение WM_LBUTTONUP сигнализирует конец рисующего действия. Процедура окна выпускает мышь захватывать и освобождает мышь от области клиента.

LRESULT APIENTRY MainWndProc(hwndMain, uMsg, wParam, lParam) HWND hwndMain;
UINT uMsg;
WPARAM wParam;
LPARAM lParam;
{
hdc HDC; /* ручка контекста устройства */ RECT rcClient; /* прямоугольник области клиента */ ТОЧКА ptClientUL; /* верхний левый угол клиента */ ТОЧКА ptClientLR; /* правый нижний угол клиента */ статические ТОЧКИ ptsBegin; /* начиная точку */

статические ТОЧКИ ptsEnd; /* новая конечная точка */ статические ТОЧКИ ptsPrevEnd; /* предшествующая конечная точка */ статическая BOOL fPrevLine = ЛОЖЬ; /* предшествующий флаг линии */

ключ (uMsg) { случай WM_LBUTTONDOWN:

/* Мышь Сбора input. */

SetCapture(hwndMain);

/*
* Извлеките экранные координаты области клиента,
* и преобразование он в координаты клиента.

/*

GetClientRect(hwndMain, &rcClient);
ptClientUL.x = rcClient.left;
ptClientUL.y = rcClient.top;

/*
* Добавьте один направо и нижние стороны, поскольку the
* координаты извлеченные GetClientRect нет
* включите значительно левые и lowermost пиксели.
*/

ptClientLR.x = rcClient.right + 1;
ptClientLR.y = rcClient.bottom + 1;

ClientToScreen(hwndMain, &ptClientUL);
ClientToScreen(hwndMain, &ptClientLR);

/*
* Скопируйте координаты клиента области клиента
* в структуру rcClient. Ограничьте курсор мыши
* в область клиента передавая структуру rcClient
* в функцию ClipCursor.
*/

SetRect(&rcClient, ptClientUL.x, ptClientUL.y, ptClientLR.x, ptClientLR.y);

ClipCursor(&rcClient);

/*
* Преобразовайте координаты курсора в ТОЧКИ
* структура, которая определяет начальную точку the
* линия сделанная в течение сообщения WM_MOUSEMOVE.
*/

ptsBegin = MAKEPOINTS(lParam);
возврат 0;

случай WM_MOUSEMOVE:

/*
* При перемещении мыши, потребитель должен придержать
* левая кнопка мыши должна сделать линиями.

*/

если (wParam & MK_LBUTTON) {

/*
* Извлеките контекст устройства (DC) для клиента
* область.
*/

hdc = GetDC(hwndMain);

/*
* Следующее функции гарантирует, что пиксели
* прежде сделанная линия установлена на белый и
* те новой линии установлены на черный.
*/


SetROP2(hdc, R2_NOTXORPEN);

/*
* Если линия была сделана в течение более ранний
* сообщение WM_MOUSEMOVE, делает над этим. Это стирается
* линия устанавливая цвет своих пикселей, чтобы
* белый.
*/

если (fPrevLine) { MoveToEx(hdc, ptsBegin.x, ptsBegin.y, (LPPOINT) НЕДЕЙСТВИТЕЛЬНЫЙ);
LineTo(hdc, ptsPrevEnd.x, ptsPrevEnd.y);

}

/*
* Преобразовайте текущие координаты курсора в a
* СТРУКТУРА ТОЧЕК, затем делает новой линией.
*/

ptsEnd = MAKEPOINTS(lParam);
MoveToEx(hdc, ptsBegin.x, ptsBegin.y, (LPPOINT) НЕДЕЙСТВИТЕЛЬНЫЙ);
LineTo(hdc, ptsEnd.x, ptsEnd.y);

/*
* Установите предшествующий флаг линии, сохраняйте окончание

* укажите новую линию, затем выпускайте DC.
*/

fPrevLine = ИСТИНА;
ptsPrevEnd = ptsEnd;
ReleaseDC(hwndMain, hdc);
}
прерывание;

случай WM_LBUTTONUP:

/*
* Потребитель завершил разграничивать. Восстановите the
* предшествующий флаг линии, выпускает курсор мыши, и
* выпустите сбор мыши.

*/

fPrevLine = ЛОЖЬ;
ClipCursor(НЕДЕЙСТВИТЕЛЬНЫЙ);
ReleaseCapture();
возврат 0;

случай WM_DESTROY: PostQuitMessage(0);
прерывание;

.
. /* Обработайте другой messages. */
.



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