How to Create a CHILD OpenGL Window in a Dialog

Environment: VC6 Win 2000

For a while, I've been using glut (which is great) to create all of my OpenGL projects. This was fine for a while until I had to do some "crazy" things with subwindows. I figured if I just used MFC instead, all my problems would be solved. The only down side was trying to get a child opengl window in my dialog. I've seen a lot of examples using MDI and SDI, but I just would have felt cheated if I couldn't get it to work for a dialog. Through a little trial and error and a couple of passes through the MSDN, I offer you this quick and dirty example of how to do it.

The first thing you do is create a dialog based application. Next you can use the Class Wizard (by right clicking on the dialog form you see in your resource tab) to create a new class derived from a generic CWnd (I named mine COpenGL... quite original). After you've created your new class, use the class wizard to Set up the functions that handle the WM_CREATE and WM_PAINT messages. You can add other messages if you wish, but these are all we'll need for now.

Inside the generated dialog class header file (in my example it's called fastDlg.h), you'll want to add a pointer to your new class.

class CFastDlg : public CDialog
{
// Construction
public:
  ~CFastDlg(void);
  CFastDlg(CWnd* pParent = NULL);  // standard constructor

  COpenGL *m_pDisplay;  //<-- here he is!

.
.
.

Don't forget to add the header file at the top. You'll find the generated message handlers inside OpenGL.cpp. On creation of the window, I set its device context so it can handle opengl commands.

class CFastDlg : public CDialog
{
int COpenGL::OnCreate(LPCREATESTRUCT lpCreateStruct) 
{
  if (CWnd::OnCreate(lpCreateStruct) == -1)
    return -1;
  
  // TODO: Add your specialized creation code here
  MySetPixelFormat(::GetDC(m_hWnd));

  return 0;
}

The code for MySetPixelFormat(...) was found in the MSDN. Inside OnPaint, I make the device context current, do my opengl commands, and make my dievice context non-current. I'm sure there are several different ways to do this, and you should do as much error checking as possible. But like I said before, this is a quick and dirty example ;)

void COpenGL::OnPaint() 
{
  CPaintDC dc(this); // device context for painting
  
  // TODO: Add your message handler code here
  HDC hdc = ::GetDC(m_hWnd);
  HGLRC hglrc;

  // TODO: Add your message handler code here
  glClearColor(0,0,0,0);
  glColor3f(1, 1, 1);

  if (hglrc = wglCreateContext(hdc))
  { 
    // try to make it the thread's current rendering context
    if(wglMakeCurrent(hdc, hglrc))
    {
      //render here
      glClear(GL_COLOR_BUFFER_BIT);
      glBegin(GL_TRIANGLES);
      glColor3f(1, 0, 0);
      glVertex3f(.5, 0, 0);
      glColor3f(0, 1, 0);
      glVertex3f(0, .5, 0);
      glColor3f(0, 0, 1);
      glVertex3f(-.5, 0, 0);
      glEnd();
      SwapBuffers(hdc);
    } 
  }

  wglMakeCurrent(NULL, NULL) ; 
  ::ReleaseDC (m_hWnd, hdc) ; 
  wglDeleteContext(hglrc); 

  // Do not call CWnd::OnPaint() for painting messages
}

The last important thing that you'll need to do is create the window in the OnInitDialog function.

BOOL CFastDlg::OnInitDialog()
{
  CDialog::OnInitDialog();

  // Set the icon for this dialog.  
  // The framework does this automatically when 
  // the application's main window is not a dialog
  SetIcon(m_hIcon, TRUE);  // Set big icon
  SetIcon(m_hIcon, FALSE); // Set small icon
  
  CRect rect(7, 7, 300, 300);

  // TODO: Add extra initialization here
  m_pDisplay->Create( NULL,  //CWnd default
     NULL,   //has no name
     WS_CHILD|WS_CLIPSIBLINGS|WS_CLIPCHILDREN|WS_VISIBLE,
     rect,
     this,   //this is the parent
     0);     //this should really be a different 
             //  number... check resource.h

  return TRUE;  // return TRUE  unless you set 
                //    the focus to a control
}

I really hope this helps. I know I couldn't find a tutorial on creating a child window in a dialog, and I tried several other approaches before hitting this one. I'd also like to thank CodeGuru.com... there articles (and the people who submitted them) have helped out quite often.

Downloads

Download demo project - 494 Kb


Comments

  • Si quieres mas información puedes vistar esta pagina Espero haberte ayudado

    Posted by gwnoua054 on 07/17/2013 06:57pm

    EE.UU. Altid tiltrækker Vores opmærksomhed, vi kan lide Smukke ting, ting Mennesker eller. Så enhver kvinde ønsker al eje mera charmerende og Smukke. Dette kræver, por lo vi hele tiden Gore dig forandring. --- Hver dag vi skifter Toj og kan BAERE forskellige Toj. Dette er kun udseendet af ændringen, kan vi OGSA læse flere Boger. Skift indefra dig selv. Det hår. Sådan Gor du hår. Dette er OGSA en masa af skønhed spørgsmål. Før Begge er ændret. Hombres hvordan hombre Gor den første tipo. Vi El Vendedor ghd glattejern, hår er et godt konverteringsværktøj, kan det konstant ændre hår dit, los hombres ved din egen parte, ikke kun para Barber Shop kan repuesto dig tid, gennem konstant forandring kan du findes para ejer mera hår. [url=http://comprarghd.webgarden.com/]ghd baratas[/url] Ahora estoy pensando en comprar uno, porque a pesar de que BaByliss es justo, y yo me hará sentir relajado, no pierda demasiado tiempo y pelo de la onda, quiero comprar oro clásico, esta es mi tienda de barbero pelo en este usted puede encontrar si quieres una edición limitada de la caja es de alrededor de € 199, pero están en línea, usted puede encontrar bastante barato ... Sin embargo, tenga cuidado, porque hay un montón de imitación, usted puede vender el precio falso deficiencia de la hormona del crecimiento. [url=http://ghdplanchasprec.ucoz.com/]planchas ghd baratas[/url] ghd sitios de venta en línea, disfrutar del pelo GHD barato para lograr los mejores resultados, ofrecemos el envío libre en Dinamarca, luchando para encontrar ghd le da la magia ahora, como planchas ghd populares, la ghd unos accesorios para el cabello perfectamente liso no sólo le da la oportunidad de? utilizando la vasta, sino también para ahorrar tid.Vi están preocupados por sus estrellas favoritas, no sólo una mayor comprensión de lo que dicen, van a degustar más preocupado por el vestido, retro-moda hoy en día sigue siendo cero loco, pelo rizado señora de pelo lacio tan popular diseño y más pelo volumen no es difícil ver lo que usted elija plancha ghd y tiene las habilidades, por lo que ha dado hoy una plancha de pelo pind.ghd diseño más elegante, el uso del campo hoy en día los aparatos negros más populares, una chica enamorada de uno de los varios colores, el mango es de color negro brillante, el color variado, a mano diseñado, antideslizante fácil de entender, difícil deslizar, mejor agarre, diseño del interruptor en el parte frontal del mango, fácil de operar.

    Reply
  • dream from clarisonic model

    Posted by iouwanzi on 06/06/2013 11:02am

    [url=http://www.australiaclarisonic.com/clarisonic-pro]clarisonic pro[/url] Mon conjoint et moi posséder prolongée (pratique pour vous aider mes coudes personnels) mince, okay, colorés mais aussi soulignée, nui chevelure. Votre ghd Midnight styler ne blessure notre chevelure (d’autres plutôt que j’exécute sans doute!)#) en quelque sorte. Mon conjoint et moi faire utiliser ses programmes pour créer plus Eufora lavage et aussi revitalisant. Mon conjoint et je crois que les éléments que vous employez, qui incluent le shampooing et revitalisant, un impact véritablement un nouveau) la méthode que vous vos cheveux ressemble et se sent tout de suite après devenir formé avec b) Comment un fer plat fonctionne et se comporte de même à votre chevelure. [url=http://www.miaclarisonicaustralia.org/]clarisonic mia online[/url] Mon conjoint et j’ai très certainement besoin personne se produit et en outre choisir de me donner personnellement un Styler F HI-DEF en ce qui concerne la période des fêtes… donc si il l’homme devrions vraiment besoin pour gagner me réjoui, mon conjoint et moi obtenir la connexion pointe GHD Gold Styler et Document a parlé du fait que le Styler juste est au prix de 179 kilos, ainsi que la boîte proverbiale coûte 215 euros nuit gamme. (Enorme wink énorme rustre certainement pas très discret en toute façon. [url=http://www.miaclarisonicaustralia.org/]clarisonic mia[/url] Le courant autres avantages est la taxe avec la hausse des températures internationales. Les secondes (optimales avec 10!) après que commutation autour de la conception et de style, du sculpter va à son pouvoir alerte aux États-Unis qu’il est prêt à devenir employé. C’est vraiment un gain de temps grave de souche, même si professionnellement j’ai réellement en aucune façon utilisent mon fer plat personnel chaque fois que je suis rempli à l’intérieur.

    Reply
  • thank you!

    Posted by halciber on 04/28/2006 12:16pm

    This was just thing I needed for work. You saved me a lot of trial and error. Like you, I've used GLUT windows; but I've never done OpenGL on MFC dialogs before. So seeing this has made my job easier. I really appreciate your help. Mike Goldweber

    Reply
  • Problems to open new dialogs

    Posted by Danseven on 03/22/2006 02:41pm

    I put a button to open a new dialog but the application crash after I click , this only because opengl, i cant open new dialogs becaus this, why?

    Reply
  • pb with keydown events

    Posted by gemyny on 07/28/2005 03:09am

    I got difficulties using OnKeydown events for the OpenGl window, do you have idea about the pb ? Thx a lot Regards GeMyNy

    Reply
  • thanks

    Posted by zygsq on 04/30/2005 11:46am

    it is great.i need such guiding too much.i met the similar problem in doing mu graduate thesis.thanks

    Reply
  • And GDI ?

    Posted by Legacy on 01/11/2004 12:00am

    Originally posted by: sebseb

    Hi, it's not really a comment, but more a question... how to do the same, but without MFC ? just as a normal win32 app with a WinMain and a WindowProc ?

    Thank you in advance

    Reply
  • Question - two GL windows in one Dlg - possible?

    Posted by Legacy on 01/07/2004 12:00am

    Originally posted by: Greg K

    Is it possible to have two ( or more ) GL windows in one DLG? Like:


    COpenGL* m_p_win1, m_p_win2;


    BOOL CFastDlg::OnInitDialog()
    {
    CDialog::OnInitDialog();

    m_p_win1->Create( NULL, //CWnd default
    NULL, //has no name
    WS_CHILD|WS_CLIPSIBLINGS|WS_CLIPCHILDREN|WS_VISIBLE ,rect1,
    this, //this is the parent 0); //this should really be a different number... check resource.h

    // second gl window

    m_p_win2->Create (

    .
    .
    )

    }


    But they ( pointers ) refer to the same stucture, so the contents of both windows are equal, how can this be solved?

    Adding new funtion to the structure? But this is not very good in case you have a lot of GL windows

    Wanted to thank you - Cool! Fast and simple!

    Reply
  • Full screen in opengl

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

    Originally posted by: Luis Guerrero

    I'm an ghj draw before the main window, an dialog?. Thanx.gg

    Reply
  • Very nice, and thanks

    Posted by Legacy on 08/13/2003 12:00am

    Originally posted by: Amr Turk

    I was working on a project that need an opengl window in a dialog box,and this would help. but mine is some how different.
    I really would like to thank u very much for your effort.

    Amr Turk

    • Developer

      Posted by Neel on 10/09/2014 01:37am

      Works like a charm. Thanks

      Reply
    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: October 29, 2014 @ 11:00 a.m. ET / 8:00 a.m. PT Are you interested in building a cognitive application using the power of IBM Watson? Need a platform that provides speed and ease for rapidly deploying this application? Join Chris Madison, Watson Solution Architect, as he walks through the process of building a Watson powered application on IBM Bluemix. Chris will talk about the new Watson Services just released on IBM bluemix, but more importantly he will do a step by step cognitive …

  • In support of their business continuity and disaster recovery plans, many midsized companies endeavor to avoid putting all their eggs in one basket. Understanding the critical role of last-mile connectivity and always available Internet access for their enterprises, savvy firms utilize redundant connections from multiple service providers. Despite the good intentions, their Internet connectivity risk may still be in a single basket. That is because internet service providers (ISPs) and competitive local …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds