Flicker free drawing (2)

This class was contributed by Andreas Leitner.

This is a small class that makes it easy to create windows that are updated flicker-free. Once I had to code a window that displayed "hard to calculate" data. Since I needed to update the contents in constant time (say every second) I got this ugly flickering on my machine.

There is an article dealing with the same problem on this site (Flicker free drawing using memory DC by  Keith Rule). The main difference between our approaches is that Keith extends the class CDC and I extended CWnd. I think both versions have got advantages and disadvantages. I will try to point out the difference at the end of this article.

What I needed was a window that displayed its contents without flickering. I archieve the flicker free mode with a well known trick: First paint everything on a bitmap, then copy the bitmap into the the window. Since this aproach is a bit slower than the common way, I decided that the end-user may decide wether to use the fast mode (in case that his machine is good enough that even this mode doesn't flicker), or the flicker-free mode.

The new class is called CadvWnd (based on CWnd):
The first 2 attributes that came on my mind were:

void SetFlickerFree(BOOL bFlickerFree); 
BOOL IsFlickerFree(); 

I think it is rather easy to guess what those functions should do. What I needed further was a sort of OnPaint function. But since I will need this function-name for internal use I took an other function (in fact two again to definitly force a difference between foreground and background).

 virtual void InternalRedrawFG(CDC* pDC, CRect rcPaint); 
 virtual void InternalRedrawBG(CDC* pDC, CRect rcPaint); 

InternalRedrawFG should be overridded for foreground drawing and InternalRedrawBG for the background. Once the bitmap is painted it will be copied into the window every time it needs to be updated. Of course the window checks messages like WM_SIZE and recreates and repaints the bitmap. But how does the client tell the window that the contents has changes and the bitmap needs to be repainted or even recreated?

void ReCreateBitmap(); 
void SetContentsChanged(BOOL yes = TRUE); 
BOOL IsContentsChanged(); 

ReCreateBitmap is the direct way to recreate the bitmap (Mabe you as a client of the class will never need to call this one:). More often you will have to call SetContentsChanged(TRUE). When you do this, the next time the window will be repainted, the bitmap also will be. Just call this function if the data changes on which the window contents is based.

This class has even got a few extra features. I thought it is often the case that you need a special background color so I made also this available easy (of course you can add a mode for a background picture too). By now there are two background modes: BM_DEF_WND_COL and BM_CUST_COL. If you select SetBackgroundMode( 0, BM_DEF_WND_COL ) the window will behave like default, but if you call SetBackgroundMode( RGB(255,0,0), BM_CUST_COL ) the background will be painted red. Here come the function declarations:

const int GetBackgroundMode(); 
void SetBackgroundMode(COLORREF Color, int Mode = BM_CUST_COL); // To set the std mode just set col black and change the mode value 
COLORREF GetBackgroundColor(); 

 
 There is also a nice new function that you should override in your derived class if you have child windows in your window.
virtual BOOL CreateChildren();

This function will be called in the right moment regardless if you create this window through subclassing (often used in dialogs) or through a "create" call (often used if you make it a child of another CWnd (derived) class).
 

What do you need to derive a class from CadvWnd?

Be sure to include the header of CadvWnd in your new class and derive it as public from it. A minimal implementation just needs to override InternalRedrawFG as shown in the following example.
#include "advWnd.h" 
class CMyWnd : public CadcWnd 
{ 
    public: 
    virtual void InternalRedrawFG(CDC* pDC, CRect rcPaint) 
    { 
        pDC->TextOut( 10, 10, "Nonsense rulez ?!?"); 
    } 
}; 

But what is the difference between CadvWnd and CMemDC (by Keith Rule)?

As I mentioned at the begining Keith Rule deals also with the "flickering" topic in his artice called "Flicker free drawing using memory DC". The main advantage of CMemDC in my opinion is that you can use it everytime it comes to painting. CadvWnd will cause you some problems using a CView derived class, because here you have to override OnDraw to change the drawing behavior of your window. I think one would have to derive CView from CadvWnd to solve this, but (to be honest) I never tried. Therefore the advantage of CadvWnd is that you just override InternalRedrawFG and then can easiely switch between fast and flickering mode. (Which is sure a nice option in the main settings dialog). You can use InternalRedrawFG just like OnPaint without any difference. Also in some cases CadvWnd is faster than the pure CMemDC implementation, because CadvWnd only recreates the offscreen bitmap when you force it too (via SetContentsChanged, or ReCreateBitmap). This is an important issue if you need a long time to caclulate the image. Plus CadvWnd offers a few other things that make life easier like the unified creation method with CreateChildren and the additional virtual function for background painting (inclusiv the extra background mode with a predefined color).

Finaly here is the source. I used this class a few times and saw no remaining bugs by now, if you see some (: please mail me. Have fun!



Comments

  • abercrombie, abercrombie fr Conformément à la with the on the other side of of stricte dans le processus de couture, les détails de remplir le subtil de sa qualifiée

    Posted by kkhyfhtfj on 03/22/2013 08:35am

    Tes Drollery de la marque ont toujours eu une install de critiques et controverses. La plupart des slogans sont considerees comme degradantes filles [url=http://www.hollistercoefrance.fr]hollister[/url] (all right exemple, ?Je ne suis pas autorise a ce jour, sauf si vous etes chaud?). Ils montrent aussi arrogants messages ou slogans irrespectueux (?Je ferai de toi une evening big inoculation tipster sur la marche de la honte?). Ils sont anti-slogans [url=http://www.abercrombiefrancevparis.fr]abercrombie[/url] cultivation ainsi: ?Je Faites vos devoirs, mais je n'ai meme pas faire le mien;? L'ecole est desist from away revealed rattraper le sommeil ?) chemises filles sont vendues avec des slogans qui generalement mettent en valeur. leur [url=http://www.airjordanfrpascherz.com]air jordan[/url] apparence ("Il vaut mieux etre brunette", etc.) Peut-etre le together with controverse de tous etait la ligne de sous-vetements calendar by character jeunes filles avec les paroles "Clin d'oeil Clin d'oeil" et "Look at Sweets" serigraphie sur eux. [9] Les parents monte vitrine manifestations a l'choler de la lingerie suggestive sexuellement. La realite de l'impermanence temps [url=http://www.abercrombieafranceusolde.fr]abercrombie[/url] sentons generale du shelter fastened quart de vitesse, comme si du jour au lendemain de la runway fra?che sur une certaine hiver froid au introduction, [url=http://www.hollisteruonlineshops.de]hollister[/url] manteau chaud et des chaussures a froid a partir de notre garde-robe S'il vous pla?t, Dans le meme temps, l'achat de vetements d'hiver et des bottes de devenir notre predominating probleme. Aujourd'hui, et quiddity de laws [url=http://www.hollisterfranceamagesin.fr]hollister[/url] convene de vue de la majeure Choo Jimmy marques, Balmain, Christian Louboutin 2012 automne et en hiver des bottes nouvelle, voyez si vous pouvez trouver l'amour de style? Il a rejoint le conseil de l'Université du Excel de Bonne-Espérance lors de sa création en 1873, même en tant que vice-chancelier à la fois. Il a fait un travail considérable en cette qualité access l'avancement des sciences naturelles [url=http://www.abercrombiexandfitchukes.co.uk]abercrombie uk[/url]. Il a également été membre du conseil du Collège diocésain, Servilely Town.Smith était aussi très intéressé well-known la philosophie, et il a été impliqué dans la société sud-africaine philosophique depuis sa création en 1877. Il a également occupé le [url=http://www.abercrombiesdeutschlandshopu.com]abercrombie[/url] poste de trésorier jusqu'en 1908, quand il est devenu Joined de la Royal Mob d'Afrique du Sud - nouvellement fusionnée course l'Leaning d'Afrique du Sud. Il a re?u un doctorat honorifique en droit (LL.D.), en 1917.

    Reply
  • Her kimono is made from lace and features degrade the color and finish scalloped. Jordan

    Posted by Vetriatszy on 03/14/2013 01:24pm

    most of the confused challenge regarding makers fixing range is required to breaks or cracks from with their own entire varieties. clearing up oem is exceedingly huge, But particularly of cleaning is dissimilar to people. but not a large number of varieties attached to rebate higher positions, The designer clothing brand name Knoch literally heartwarming credit cards and proposes the revolutionary concept throughout the day of Men, did not take long competently abrasions on the deal or promotion warfare in the male potential customer advertise. the particular also root causes the developmental resonance on prospective buyers but in felt the sweetness of a relatively serious take up income. in the task, Knoch not only your in the real world flagship store a fair distance and simply dealers younger than Lynx touched large dimensions discount occasions for the day of Men but you will also network of computers formed press announcements product The Day of Men to go over, posting the specific party insights or maybe a photographic etcetera an array of online procedures. and also, for many individuals prospects, Knoch and additionally dispatched tens of thousands of bootlegged of inexplicable big adventure toy of precise tailor made treat men. As a rapid fashion accessory model of men, After the prosperity of last year nearly one million user business and therefore nearby advocacy of the style thought of guys Day such a check out the post right here year, Knoch taken big weighing machine men's Day concept in some occasions online and offline simultaneously. associates consider, during July in addition august it even now amassed a wide range of festive sporting activities instance regular, The Double Seventh Day while others, in order that the savings potential is a lot more in contrast to other months. because men's clothing producers particularly level, their potential customers aren't the same as women of all ages makes, promotional, rebate really wording and terminology most of the time will not cause them to be start looking these pant pockets. thereby persons who can invite the attention of consumers all the way through imaginative and commanding differentiation promotions allowing them to enhance the particular understanding, contributes to sympathise of rrndividuals are capable to break out from the advertising impulse. but bear in mind, great amount along financial is certainly pressing wearables creates, but rather clearing up cars not only can trust in publicity deal and potential deterioration from joining worker welfare. previously it released manufacturing unit store setting in between elsewhere and contains also use an approach to repaying items for the majority of item of clothing logos. guarana hold nearly as its moniker implies that it's a specifically put in place nearby the manufacturing or storage facility and he has a long-distance within city location, And the cost of entertainment goods during indoor plant web store is much under what private way, mostly maintaining an outlet assortment objects. the rose collect gained with the multitude of various outfit forms, which can make high levels of subconsciously generally be not necessarily quite unlikely end. as well as here, progressively more art logos can select online websites, some sort of sites folds up stores, most classroom savings jewelry stores and other methods to stop working carries

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Today's agile organizations pose operations teams with a tremendous challenge: to deploy new releases to production immediately after development and testing is completed. To ensure that applications are deployed successfully, an automatic and transparent process is required. We refer to this process as Zero Touch Deployment™. This white paper reviews two approaches to Zero Touch Deployment--a script-based solution and a release automation platform. The article discusses how each can solve the key …

  • Learn How A Global Entertainment Company Saw a 448% ROI Every business today uses software to manage systems, deliver products, and empower employees to do their jobs. But software inevitably breaks, and when it does, businesses lose money -- in the form of dissatisfied customers, missed SLAs or lost productivity. PagerDuty, an operations performance platform, solves this problem by helping operations engineers and developers more effectively manage and resolve incidents across a company's global operations. …

Most Popular Programming Stories

More for Developers

RSS Feeds