Multiple Views Using SDI

There are many advantages to using a CView derived class over a dialog based application. Many times however there is more information than screen space or the program just needs logical seperation of elements. MDI ( Multiple Document Interface) is the standard method of achiving this but many designers do not care for it. It tends to get messy quickly. Most of the time what is needed is a generalized easy way to have a SDI ( Single Document Interface) framework and the ability to switch the active view when needed. This article describes such a method.

In order for this method to work correctly you need to make one simple change in the header of your CView derived classes. The default constructor for the view needs to be have the protected storage class changed to public ( See code sample below). This is due to the fact that we will be constructing the view on the fly when it is switched to the active view. We could create all the views at one time and have them available but that is wasteful of memory and resources and is not really needed. If you wish to do so, however the code can easily be changed to achive this.



class CMainView : public CFormView
{
protected: 	// create from serialization only   Change this to
public: 	// create from serialization only     this in all CView derived classes

 CMainView();
 DECLARE_DYNCREATE(CMainView)


The actual function that will swap the views is located in your CFrame derived class. This is the logical place to put it because in the SDI architecture the frame class controls the view class. It also allows us to centralize message handling for switching views in/out. As far as MFC member functions go it is pretty simple. It simply disconnects the old view and destroys it , creates a new CView derived class and attaches the document to it, sets a few flags, shows the view and we are in business. here it is.



void CMainFrame::SwitchToForm(int nForm)
{
 CView* pOldActiveView = GetActiveView();	// save old view
 CView* pNewActiveView = (CView*)GetDlgItem(nForm);  // get new view

 if (pNewActiveView == NULL)
 {
  switch(nForm) // these IDs are the dialog IDs of the view but can use anything
  {
   case IDD_MULTISCREEN_FORM:
    pNewActiveView = (CView*)new CMainView;
    break;

   case IDD_MULTISCREEN_FORM2:
    pNewActiveView = (CView*)new CView2;
    break;

   case IDD_MULTISCREEN_FORM3:
    pNewActiveView = (CView*)new CView3;
    break;

   case IDD_MULTISCREEN_FORM4:
    pNewActiveView = (CView*)new CView4;
    break;
  }

  CCreateContext context;       // attach the document to the new view
  context.m_pCurrentDoc = pOldActiveView->GetDocument();
  pNewActiveView->Create(NULL, NULL, 0L, CFrameWnd::rectDefault, // and the frame
   this, nForm, &context);
  pNewActiveView->OnInitialUpdate();
 }

 SetActiveView(pNewActiveView);		// change the active view
 pNewActiveView->ShowWindow(SW_SHOW);	// show the new window
 pOldActiveView->ShowWindow(SW_HIDE);	// hide the old


 ::SetWindowWord(pNewActiveView->m_hWnd, GWL_ID, AFX_IDW_PANE_FIRST);  // gotta have it
 RecalcLayout();		//	adjust frame
 delete	pOldActiveView;	//	kill old view
}


Now all we need to do is attach some menu options and handle the users requests to switch views. This is easily done using Class wizard to create the blank functions and message handlers. Below is the code demonstrating a call to switch screens.

void CMainFrame::OnForm1()
{
 SwitchToForm(IDD_MULTISCREEN_FORM);
}


Also as a UI issue it would be nice if the menu option gave a clue as to what screen we were on and to prevent the user from attempting to switch to the current screen. This is easily accomplished by the code below.

void CMainFrame::OnUpdateForm1(CCmdUI* pCmdUI)
{
 pCmdUI->Enable(GetActiveView()->GetRuntimeClass()!=RUNTIME_CLASS(CMainView));
}



I have a small demo project that shows illustrates the principals talked about in this article. It shows a SDI with 4 screens and allows one to switch views via a popup menu or a frame menu.

Download demo project - 26 KB



About the Author

Richard Stringer

C C++ ASM are my currrent languages of choice. Currently writing MFC apps for insurance companies

Comments

  • Sigue tu mujer feliz con planchas GHD!

    Posted by hanmeihm on 05/30/2013 10:32am

    [url=http://www.ghdchheapoutlet.moonfruit.com/]Planchas ghd[/url] Si usted no sabe el equipo m¢s eficaz en las modernas planchas condominio da, usted necesita para hacer frente a la alta calidad Identificacin del problema. Si usted no aprende cmo elegir el m¢s ajustado a su pelo, por lo tanto, la alternativa es GHD Mini Design. Realmente es diseo de peinado innumerables y empresas de equipos de estilo bien conocidos. La mirada y la divisin existente planeta peinado reconocido fuertemente deseada, con varias funciones superiores para presumir. [url=http://www.planchasespanaghdtop.net/]Planchas GHD[/url] Sujete el pelo m¢s cercano a la raz de los alisadores. A medida que comience a tirar de los alisadores de pelo que una introduccin a alisadores de pelo GHD, rotarlos alrededor del 50% de un tirn y luego tirar las planchas entre s a travs del resto de la duracin de cabello. El calor en el exterior de las planchas ser¢ suficiente m¢s que suficiente para rizar el cabello y mantenerlo en su puesto. Cuanto m¢s lento se mueve la plancha, como resultado de su cabello ghd nz pelo, m¢s firme ser¢ el rizo. Adem¢s, don preocuparse acerca de cualquier vapor que se poda ver que viene de su cabello, slo la evaporacin de los elementos de seguridad de calor. [url=http://www.planchasghdbaratasonline.com/]planchas de pelo ghd[/url] Utilizando todos los desenrollado interior de su pelo muy rizado causa daos a los productos. Luego, cuando en primer lugar, que se mueve brushing cerraduras uso de una cerradura muy eficaces das o semanas straigntener cabello para ayudar a alargar el programa, una vez m¢s, es posible que enviando bloqueos en movimiento con el fin a las excelentes temperaturas en ningn caso, simplemente porque sin embargo, una vez m¢s! Tendr¢s la capacidad de puesta en cerraduras sueros sobre su pelo muy rizado para ayudar a mantener el dao de calor, slo asegrese de determinar el cabello Ghd plancha enderezar GHDs baratas que probablemente Barato GHDs prueba fluye orgenes del pelo con el fin de operar regularmente seca, que produce encrespado y tal vez-puntas abiertas.

    Reply
  • GHD nÃ¥r det er sagt problem fremragende attributter for god hÃ¥r dage

    Posted by motherdhmm on 05/30/2013 09:23am

    [url=http://www.buy-beatsdrdre.com/]beats by dre australia[/url] Mange tror at det er nemt nok at vælge et ghd glattejern. Altså når man først har besluttet sig for at man vil have et ghd glattejern og ikke et af de andre mærker inden for glattejern. Men der findes flere forskellige modeller inden for ghd glattejern. Hvilket ghd glattejern du skal vælge afhænger af hvad krav du stiller til det og hvad type hår du har. Har du langt krøllet hår og glatter det ofte, måske endda dagligt, så kan du med fordel vælge en af de brede ghd glattejern der findes. [url=http://www.blog.cheapbeatsbydre.co.nz/monster-headphone]monster beats headphone[/url] hovedsagelig langt bedre. [url=http://www.buy-beatsdrdre.com/]beats by dre headphones[/url] Spil i en travl dags arbejde, den første ting, vi ønsker at prøve at slappe af, så varmt vandbad er den bedste måde at låse en dag træt. Når du vasker dit hår ingen måde til straks at slippe af med, så du brug for hjælp med en hårtørrer til at tørre dit hår. Nej hårtørrer, så er du nødt til at vente på håret til at tørre langsomt. På denne måde, et spild af tid ikke kan lide at tørre hår, hvordan man skal gøre, hvis du fange op med arrangementer. Så du skal du bruge en ghd hårtørrer. Hårtørreren, så længe du køber vores ghd håret, kan du nemt få. Vores ghd glat hår med en hårtørrer tilbehør, kort, smukke spejl, og ghd fladjern så specielt pakker, faciliteter, ikke alene kan spare dig for en pose, kan blæse dit hår tørre, og derefter bruge ghd glattejern til at oprette en ny frisure . Virkelig tjene to formål.

    Reply
  • Nike Current Max 1 FB press, father a eager color texture, the new shoes

    Posted by Geozyoceada on 04/21/2013 08:38am

    In the summer in a pane backing bowels the serene sprite seems to be a good fitting, but if the sprite "feet"? Resolution also fork out you a frisk, take a slaking nourishment! This summer, Nike and Sprite [url=http://markwarren.org.uk/goodbuy.cfm]nike free run[/url] and his sneakers to a blend of outstanding example snow spread of callow, white and indecent color blueprint in the undying Nike Arrogance Max 1 shoes let slip a drinks chill scent.[url=http://northernroofing.co.uk/roofins.cfm]nike free uk[/url] Summer is the yet to pick a cleanly shoe, shoes should be a good choice. Qualifying series Nike Freshen Max HomeTurf city recently at the end of the day comes up, this series in the classic Melody Max shoes to London, Paris and Milan the three paid encomium to the iconic megalopolis of Europe, combined with the characteristics of the three cities, Like Max 1 HYP,Allied Max 90 HYP,Air Max 1 and shoes such as Air Max 95, combined [url=http://northernroofing.co.uk/roofins.cfm]nike free uk[/url] with the Hyperfuse, as kindly as a heterogeneity of materials, such as suede, Whether you crave functioning or retro-everything.

    Reply
  • Alother Stupid Fuck

    Posted by Liquid Snake on 01/04/2013 06:24pm

    Hello, Wow, Just cant figure out why people post half ass garbage. This code does switch the View however the View has been created with the wrong styles so when activated it never gets any proper size and the frame window just shows whatever pixels are in the desktop background because the view is active but has no size. Liquid Snake

    • You're an idiot

      Posted by me on 07/26/2013 08:47am

      Get a life.

      Reply
    Reply
  • Thank you!

    Posted by Peter on 03/31/2012 12:04pm

    Thanks for this amazing piece of code. I had spent last few hours trying to figure out how to switch views in my database app, with no results, until I came here. Anyway, you've just made my day :)

    Reply
  • DEMO WORKS WITH POSTED BUG FIX - MULTIPLE DOCS ??

    Posted by Mike Pliam on 11/09/2010 02:00pm

    This code appears to work when the bug fix posted by Marko Shade is substituted for the original CMainFrame::SwitchToForm. But all of the views here use a CDocument derived Doc. What I need is a method of handling views such as CView and CRichEditView that require differing Doc derivations.. This demo comes so close to a solution to that problem, but I do not understand how to link the Docs and the Views. Any ideas greatly appreciated. : )

    Reply
  • Multiple Views Using SDI -- problem

    Posted by pradeep556 on 08/07/2008 09:12am

    download demo project is not working properly, it not able to switch one view to another view, pls check the demo project code and provide the correct the solution .

    Reply
  • WARNING: DO NOT USE THIS CODE

    Posted by souldog on 03/25/2004 04:39pm

    This code does not work. Do not use it. If you want to see the proper way to do this look at the collections sample on MSDN

    • ?

      Posted by DanYELL on 06/21/2006 06:16pm

      Is there any specific code you can recommend? I like the idea of a multiple view like this for a SDI interface.

      Reply
    Reply
  • Urgent: Need to retain the changes on each view

    Posted by Legacy on 12/11/2003 12:00am

    Originally posted by: Musa

    Hi,

    Every time I switch views, it creates new View. I don't want to do that way. I want to retain the changes made to earlier view.

    Please help.
    Thanks in advance.
    Musa

    Reply
  • Multiple simultaneous views?

    Posted by Legacy on 06/10/2003 12:00am

    Originally posted by: david aberdeen

    How can this model be extended to allow multiple views at the same time? My app needs to have one main view of a 3d model, and then many other views for data entry, or 2d display of different components of the model. I've currently build the application around non-CView dialog boxes, (with only one open at a time to remove data synchronisation issues), but it's getting many views, and getting messy, whereas a multiple view MDI solution would be much neater.

    Any help would be appreciated.

    Reply
  • Loading, Please Wait ...

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

Top White Papers and Webcasts

  • Live Event Date: November 20, 2014 @ 2:00 p.m. ET / 11:00 a.m. PT Are you wanting to target two or more platforms such as iOS, Android, and/or Windows? You are not alone. 90% of enterprises today are targeting two or more platforms. Attend this eSeminar to discover how mobile app developers can rely on one IDE to create applications across platforms and approaches (web, native, and/or hybrid), saving time, money, and effort and introducing apps to market faster. You'll learn the trade-offs for gaining long …

  • IBM Worklight is a mobile application development platform that lets you extend your business to mobile devices. It is designed to provide an open, comprehensive platform to build, run and manage HTML5, hybrid and native mobile apps.

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds