Search code examples
visual-c++visual-c++-2010

How do I show and hide forms in Visual C++?


Hey guys, I'm brand new to Visual C++, but not C++. I'm having issues trying to figure out how to show/hide forms.

Let's say I have a form Form1 and another form TestForm. In a button click function in Form1.h I have the code:

Form1::Hide();
TestForm^ form = gcnew TestForm();
form->Show();

And it works fine. I click the button, and Form1 disappears and TestForm appears. But if I do the same thing in TestForm.h (just changing which forms are set to appear/disappear) I get a plethora of compiler errors in both Form1.h (which used to work) and TestForm.h

  Form1.cpp
c:\users\alex\documents\visual studio 2010\projects\test\test\TestForm.h(86): error C2065: 'Form1' : undeclared identifier
c:\users\alex\documents\visual studio 2010\projects\test\test\TestForm.h(86): error C2065: 'form' : undeclared identifier
c:\users\alex\documents\visual studio 2010\projects\test\test\TestForm.h(86): error C2061: syntax error : identifier 'Form1'
c:\users\alex\documents\visual studio 2010\projects\test\test\TestForm.h(87): error C2065: 'form' : undeclared identifier
c:\users\alex\documents\visual studio 2010\projects\test\test\TestForm.h(87): error C2227: left of '->Show' must point to class/struct/union/generic type
          type is ''unknown-type''
  TestForm.cpp
c:\users\alex\documents\visual studio 2010\projects\test\test\Form1.h(103): error C2065: 'TestForm' : undeclared identifier
c:\users\alex\documents\visual studio 2010\projects\test\test\Form1.h(103): error C2065: 'form' : undeclared identifier
c:\users\alex\documents\visual studio 2010\projects\test\test\Form1.h(103): error C2061: syntax error : identifier 'TestForm'
c:\users\alex\documents\visual studio 2010\projects\test\test\Form1.h(104): error C2065: 'form' : undeclared identifier
c:\users\alex\documents\visual studio 2010\projects\test\test\Form1.h(104): error C2227: left of '->Show' must point to class/struct/union/generic type
          type is ''unknown-type''

Solution

  • The problem is most likely due to the order in which you're including the headers into the .cpp files. In the original case, when you were working in Form1.cpp, "TestForm" was a known type before Form1.h was included. As soon as you switch the header files will your method calls, this isn't the case anymore.

    I recommend moving your event handlers (the button click functions) to your .cpp files. Your .cpp files can both include both headers, and the compiler will find the form definitions, with their methods, appropriately, no matter what order you include the headers.