Главная » Просмотр файлов » Wiley.Symbian.OS.C.plus.plus.for.Mobile.Phones.Aug.2007

Wiley.Symbian.OS.C.plus.plus.for.Mobile.Phones.Aug.2007 (779890), страница 80

Файл №779890 Wiley.Symbian.OS.C.plus.plus.for.Mobile.Phones.Aug.2007 (Symbian Books) 80 страницаWiley.Symbian.OS.C.plus.plus.for.Mobile.Phones.Aug.2007 (779890) страница 802018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 80)

These include:• discarding any pointer-down events on invisible controls• implementing pointer grab• ignoring pointer events until the next pointer-up event (which isinitiated by calling the control’s IgnoreEventsUntilNextPointerUp() function, normally after handling a pointer-down event)442CONTROLS• reporting, but then discarding, any pointer-down events on dimmedcontrols• reporting any pointer-down event on an unfocused control that iscapable of taking focus• reporting, if necessary, and after calling HandlePointerEventL(),the need to transfer focus to this control.The three possible reporting options are discussed in Section 15.5.15.5Observing a ControlIt is frequently useful for a control to be able to notify some other classof significant events. The standard mechanism for doing this is to use anobserver interface.The control framework defines the MCoeControlObserver interfaceclass with a single member function, HandleControlEventL(), toprovide the mechanism for receiving and processing notifications of arange of common control events.

Any class that derives from this interfaceis known as a control observer. A control’s observer is frequently, but notnecessarily, the control’s container.A control’s observer can be set using the control’s SetObserver()function and subsequently referenced via the Observer() function.A control wishing to report an event to its observer should callReportEventL(), passing one of the enumerated event types listedbelow. ReportEventL() will report the event only if the control’sobserver has previously been set by means of a call to SetObserver().There are three general-purpose events that your control may report.• EEventStateChanged: a control should use this event to reportthat some significant piece of internal data has changed.

The container control of a dialog responds to a report of this event from oneof its component controls by calling the dialog’s HandleControlStateChangeL(). You should implement this function to make theappropriate changes to any other controls that are affected by thechange of state. The event is not used elsewhere.• EEventRequestExit: the intended use of this event is to indicatethe successful completion of an operation, for example selecting anitem from a choice list.

The control framework does not use this event.• EEventRequestCancel: this event should be used to indicate thatan operation has been cancelled, for example backing out of a choicelist, leaving the original choice unchanged. The control frameworkdoes not use this event.OBSERVING A CONTROL443The control framework uses a further three events to handle the threereports made by ProcessPointerEventL().• EEventInteractionRefused: the control framework notifies thisevent when a pointer-down event occurs on a dimmed control. Adialog responds to this event by calling HandleInteractionRefused(), whose default behavior is to display a message informingthe user that the control is not available.• EEventPrepareFocusTransition: the control framework notifies this event when a pointer-down event occurs on a control thatdoes not yet have, but could get, focus.

An appropriate response,which is used in dialogs, would be to call the currently focused control’s PrepareForFocusLossL() function. This gives the controlan opportunity to ensure that it is in a suitable state to lose focus. If thecontrol is not in a suitable state, and cannot change itself into sucha state, its implementation of PrepareForFocusLossL() shouldleave, thereby aborting the attempted change in focus. In some cases,it might also be appropriate to call PrepareForFocusGainL() inthe control that is about to gain focus.

This function should also leaveif the control is not prepared to gain focus.• EEventRequestFocus: the control framework also notifies thisevent when a pointer-down event occurs on a control that does notyet have, but could get, focus. The event is notified after notificationof the EEventPrepareFocusTransition event, and after callingthe control’s HandlePointerEventL() function. The appropriateresponse is to transfer focus to the control in which the pointer-downevent occurred.In the Noughts and Crosses application, the tiles have the application’s view as their observer.

The view implements HandleControlEventL() as follows:void COandXAppView::HandleControlEventL(CCoeControl* aControl,TCoeEvent aEventType){switch (aEventType){case EEventRequestFocus:SwitchFocus(IdOfFocusControl(), aControl);break;default:break;}}None of the tiles is ever dimmed, and the tiles are never in a state thatwould prevent them losing focus. In consequence, of the three pointerrelated events that the application’s view could receive, it needs to handle444CONTROLSonly EEventRequestFocus. When EEventRequestFocus event isreceived, the corresponding tile is focused via the SwitchFocus()function.void COandXAppView::SwitchFocus(TInt aFromIndex, CCoeControl* aToControl){ComponentControl(aFromIndex)->SetFocus(EFalse, EDrawNow);aToControl->SetFocus(ETrue, EDrawNow);}15.6Drawing a ControlThe HelloBlank example application introduced in Section 15.2 justuses a blank control for its view, but most applications use customizedcontrols.The standard way of customizing how a control draws its content is toimplement a Draw() function, so the class definition of the simple blankcontrol is changed as follows:class CBlankAppView : public CCoeControl{public:CBlankAppView();∼CBlankAppView();void ConstructL(const TRect& aRect);private:void Draw(const TRect& aRect) const;};As we want to draw the control explicitly, we remove the call toSetBlank() from ConstructL().void CHelloBlankAppView::ConstructL(const TRect& aRect){CreateWindowL(); // Create a window for this controlSetRect(aRect);// Set the control’s sizeActivateL();// Activate control, making it ready to be drawn}The Draw() function must be capable of drawing to every pixelwithin the rectangular area occupied by the control.

This is a simpleimplementation for a blank window-owning control:void CHelloBlankAppView::Draw(const TRect& /*aRect*/) const{CWindowGc& gc = SystemGc(); // Get the standard graphics contextgc.Clear();// Clear the whole window}DRAWING A CONTROL445Drawing requires a graphics context; the appropriate one for drawingto a window, an instance of CWindowGc, is found by calling CCoeControl::SystemGc().A Draw() function is free to ignore the rectangular region passed asa parameter, provided it does not draw outside its own rectangle.

Analternative version of Draw() that respects the passed parameter woulduse a different overload of the graphics context’s Clear() function.void CHelloBlankAppView::Draw(const TRect& aRect) const{CWindowGc& gc = SystemGc(); // Get the standard graphics contextgc.Clear(aRect);// Clear only the specified rectangle}This is effectively the code that the default implementation of Draw()uses to draw a blank window.Whether or not to ignore the passed rectangle depends on what thecontrol needs to draw, and considerations such as whether it is moreefficient in terms of time and/or memory usage to do one rather than theother.

In the current example, as is commonly the case, drawing is simpleand fast, so there is no great advantage in restricting the drawing to thepassed rectangle.The Draw() function is discussed in more detail below.Drawing and the Window ServerThis section introduces some of the concepts involved in Symbian OSgraphics, to aid in understanding the practical issues of drawing a control.The mechanisms that Symbian OS uses to support drawing are coveredin detail in Chapter 17.It is virtually axiomatic that all window-owning controls must createthe window they own, and this is normally done from the control’sConstructL() function. Most controls use a standard window, of typeRWindow, created with the CreateWindowL() function, as in the earlierexample.

In addition to creating the client-side RWindow resource, thefunction also creates a corresponding resource in the window server. Thisrecords little more than the window’s position and size, together withthe region of the window that is visible and any region that needs to beredrawn (the invalid region). Once the window is created, the controlcan access it via the Window() function.Drawing a control may be initiated either by the control itself, forexample if the application modifies the data displayed by the control, orby the window server, for example when a previously hidden part of awindow is exposed. Drawing initiated by the window server is known asa redraw operation, to distinguish it from application-initiated drawing,but the mechanisms are similar.446CONTROLSTo draw to its window, a control uses a window-specific graphicscontext, an instance of CWindowGc, derived from the generic CGraphicsContext.

The control’s drawing code makes calls to CWindowGcfunctions to set the required values for attributes such as pen color and linewidth or font style and size, and to draw lines, shapes or text. The graphics context issues a corresponding sequence of commands to a buffer,whose content is subsequently transferred to the window server. Bufferingthe commands greatly reduces the number of inter-process communications between the application and the window server, thereby improvingperformance.Before such a drawing sequence, the control must perform a littlehousekeeping to ensure that both the application and the window serverare in the correct state for drawing to start.

This includes informing thewindow server, by means of a call to its Invalidate() function, whichregion of the window has content that is no longer valid, and activatingthe standard graphics context (owned by the UI control framework).This activation prepares the graphics context for drawing to the control’swindow and ensures that all its settings have their default values. At thispoint, the application’s drawing code can be called, with the graphicscontext in a known state, independent of any previous drawing operation.On completion of the application’s drawing code, further housekeeping is required, to inform the window server that the drawing sequenceis complete and to free the graphics context so that it is available to beused with another window.RedrawingWhen the window server knows that a region of a window is invalid, forexample when an overlying window is removed, it sends a redraw event tothe application owning the window.

The application framework calls thewindow server to determine which window needs to be redrawn and thebounding rectangle of the invalid region, and then calls the appropriatewindow-owning control’s HandleRedrawEvent() function, which youshould never need to override.HandleRedrawEvent() makes a call to the control’s Draw() function and, if necessary, the Draw() functions of any component controlsthat intersect with the rectangular region to be redrawn. In addition, itperforms all the housekeeping mentioned in the previous section.Application-initiated drawingAs mentioned earlier, an application does not make direct calls toDraw().

Характеристики

Тип файла
PDF-файл
Размер
6,45 Mb
Материал
Тип материала
Высшее учебное заведение

Список файлов книги

Свежие статьи
Популярно сейчас
Почему делать на заказ в разы дороже, чем купить готовую учебную работу на СтудИзбе? Наши учебные работы продаются каждый год, тогда как большинство заказов выполняются с нуля. Найдите подходящий учебный материал на СтудИзбе!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
6353
Авторов
на СтудИзбе
311
Средний доход
с одного платного файла
Обучение Подробнее