Create a Visual C++ Wizard for Visual Studio 2005

If you often create VC++ projects that are very similar, such as DLLs that follow some guidelines or rules for common integration in an application (like a plug-in based application), you might get tired of creating a default VC++ project and then doing the same changes to it over and over again. In that case, perhaps it's time for you to write a VC++ wizard that automatically generates all that you need to start doing work.

In this article, I'll show you how to create a simple wizard for a Win32 console-based application. This project template will have several particularities:

  • Uses precompiled headers, so stdafx.h and stdafx.cpp will be generated
  • Contains files for a dummy class that the user chooses to name; the name of the files will be the same as the class. These files will be placed inside a subfolder called 'src' that will be added to the Additional Include Directories property
  • Includes comments at the beginning of each file containing the author and the date of creation
  • Includes a file called main.cpp containing the main() function that will instantiate an object of the created class
  • In addition, a readme.txt text file should be generated, but not added to the list of project files

Creating the Project

To create a new wizard project, go to File > New > Project and select Visual C++, and then from the list of available templates customwiz. Let's call this project "DummyWin32Wizard", because after all, that's exactly what it is. You will be asked to select the settings for this project. First, put "DummyWin32Wizard" in the "Wizard Friendly Name" edit, check the "User Interface" checkbox, and set the number of pages of the wizard to 1, because that's all what we'll need.

When the project is created, it will have several created files that you can see in the following picture. The most important ones are described here:

  • Default.html: The file containing the HTML code for the wizard's interface pages
  • Default.js: The file containing the JScript code called by the framework when the wizard is run
  • Default.vcproj is a VC++ project file containing the minimum information for a project, such as project type, platforms, and list of configurations
  • DummyWin32Wizard.ico: The icon associated with the template in the list of VisualC++ templates
  • DummyWin32Wizard.vsz: The start point of the wizard. Itcontains information about the wizard project, such as name, path (either absolute or relative), or LCID. This file basically names a COM component that Visual Studio can use to create an item, and lists the parameters the component receives. You can read more about the file in MSDN. Default content of the file is:
    VSWIZARD 7.0
    Wizard=VsWizard.VsWizardEngine.8.0
    
    Param="WIZARD_NAME = DummyWin32Wizard"
    Param="ABSOLUTE_PATH = D:\Cilu\VC++\codeguru\articles\
                           wizard\DummyWin32Wizard"
    Param="FALLBACK_LCID = 1033"
    
  • DummyWin32Wizard.vsdir: lists all the items and their properties that are displayed in the selection dialog and the corresponding .vsz file; the default content of the file is listed below:

    DummyWin32Wizard.vsz| |DummyWin32Wizard|1|
       TODO: Wizard Description.| |6777| |DummyWin32Wizard
    

    The information listed in this file is:

    • DummyWin32Wizard.vsz: The relative path to the .vsz file
    • Optional GUID: A component that contains resources (not specified in the about string)
    • DummyWin32Wizard: The name of the template displayed in the list of available templates
    • 1: The sort priority for displaying the items in the list of available templates; items with lower numbers are displayed at the beginning of the list
    • TODO: Wizard Description: A string describing the wizard, shown in the status field
    • Optional GUID or path of a DLL: Contains the icon to be with the item in the list (not specified in the about string)
    • 6777: The resource ID of the icon in the component
    • Optional additional flags (not specified in the about string)
    • DummyWin32Wizard: The suggested base name for the item. A number is inserted before the extension of the item, if one exists. If DummyWin32Wizard is replaced, for instance, with <DummyWin32Wizard>, the wizard will not suggest any name and the user is forced to enter a name for the item

When you create the custom wizard project, Visual Studio automatically copies the files DummyWin32Wizard.ico, DummyWin32Wizard.vsd, and DummyWin32Wizard.vsdir in the folder VC\vcprojects of the Visual Studio 8 installation folder. That means that if you go to File > New > Project and select VisualC++ you'll already be able to create a project with it.

I would suggest changing the content of the DummyWin32Wizard.vsdir file to

DummyWin32Wizard.vsz| |Dummy Win32 Wizard|1|Just a training
   purpose wizard| |6777| |<DummyWin32Wizard>

and copying it to the VC\vcprojects folder, so that the templates dialog shows what you want.

Create a Visual C++ Wizard for Visual Studio 2005

Customizing the Wizard's User Interface

If you selected a user interface of one HTML page as suggested earlier, Visual Studio will add some default controls to this unique page. It is shown in the picture below:

[page1.png]

Base of the requirements that we decided for the template in the beginning, the settings page should allow the users to select the name of a dummy class to create and the name of the user (that generates the project). Thus, we should customize the from to look like this:

[page2.png]

This will make the wizard's settings page look like this:

[wizardpage.png]

If you want to fill in some values—for instance, the name of the author—before the page is displayed, you should put the code in the InitDocument() function.

// This is an example of a function which initializes the page
//
function InitDocument(document)
{
   setDirection();

   if (window.external.FindSymbol('DOCUMENT_FIRST_LOAD'))
   {
      // This function sets the default symbols based
      // on the values specified in the SYMBOL tags above
      //
      window.external.SetDefaults(document);
   }

   // Load the document and initialize the controls
   // with the appropriate symbol values
   //
   window.external.Load(document);
}

Using Template Files

In the beginning of this article, you learned that the application folder should contain the following items:

  • Src:
    • <Classname>.h
    • <Classname>.cpp
  • Stdafx.h
  • Stdafx.cpp
  • Main.cpp
  • <Projectname>.vcproj
  • Readme.txt (not added to the project file)

You will use templates to generate these files. If you look in the Templates\1033 folder, you will see three files; one of them is called Templates.inf. This file contains a list of template file that will be parsed in the JScript code during the execution. In this folder, you will add the following files:

BaseSample.cpp

/************************************************
 * Author: [!output AUTHOR_NAME]
 * Date: [!output CURRENT_DATE]
 ************************************************/

#include "stdafx.h"
#include "[!output CLASS_NAME].h"

int _tmain(int argc, _TCHAR* argv[])
{
   [!output CLASS_NAME]* sample = new [!output CLASS_NAME];

   // do the stuff here

   delete sample;

   return 0;
}

SampleClass.h

/************************************************
 * Author: [!output AUTHOR_NAME]
 * Date: [!output CURRENT_DATE]
 ************************************************/

#pragma once

class [!output CLASS_NAME]
{
public:
   [!output CLASS_NAME](void);
   ~[!output CLASS_NAME](void);
};

SampleClass.cpp

/************************************************
 * Author: [!output AUTHOR_NAME]
 * Date: [!output CURRENT_DATE]
 ************************************************/

#include "StdAfx.h"
#include "[!output CLASS_NAME].h"

[!output CLASS_NAME]::[!output CLASS_NAME](void)
{
}

[!output CLASS_NAME]::~[!output CLASS_NAME](void)
{
}

Stdafx.h

/************************************************
 * Author: [!output AUTHOR_NAME]
 * Date: [!output CURRENT_DATE]
 ************************************************/

#pragma once

#define WIN32_LEAN_AND_MEAN    // Exclude rarely-used stuff from
                               // Windows headers
#include <stdio.h>
#include <tchar.h>

Stdafx.cpp

/************************************************
 * Author: [!output AUTHOR_NAME]
 * Date:   [!output CURRENT_DATE]
 ************************************************/

#include "stdafx.h"

// TODO: reference any additional headers you need in STDAFX.H
// and not in this file

Readme.txt

==================================================================
  CONSOLE APPLICATION : [!output PROJECT_NAME] Project Overview
==================================================================

Then, you will modify the content of the Templates.inf file to list all of them:

BaseSample.cpp
sampleclass.cpp
sampleclass.h
stdafx.cpp
stdafx.h
ReadMe.txt

You can see several tags in these files: [!output AUTHOR_NAME], [!output CURRENT_DATE], and [!output CLASS_NAME]. Visual Studio will replace these tags with the value of the symbols AUTHOR_NAME, CURRENT_DATE, and CLASS_NAME. So, if the name of the author is Marius Bancila, the date is 2006.10.17, and the class name Foo, then the sampleclass.h file would be generated like this:

/************************************************
 * Author: Marius Bancila
 * Date: 2006.10.17
 ************************************************/

#pragma once

class Foo
{
public:
   Foo(void);
   ~ Foo(void);
};

The complete list of template directives is provided in MSDN.

Create a Visual C++ Wizard for Visual Studio 2005

Writing the JScript

When the user clicks the Finish button, the wizard loads the default.js file into the Script Files folder in Solution Explorer. The file contains by default the following functions:

  • OnFinish: Called by the wizard when the Finish button is clicked; it adds files and filters, render templates and creates the configurations
  • CreateCustomProject: Creates the project at the specified location when the Finish button is pressed
  • AddFilters: Adds filters to the project
  • AddConfig: Adds configurations to the project
  • PchSettings: Sets the precompiled header settings
  • DelFile: Deletes the specified files
  • CreateCustomInfFile: Creates the project's Templates.inf file
  • GetTargetName: Gets the name of a specified file
  • AddFilesToCustomProj: Adds specified files to the project

In addition to these functions, you can add your own JScript function to Default.js. To access properties and methods in the wizard object model or the environment model from the JScript file, prepend the object model item with wizard and respective date.

OnFinish

This function is called when the Finish button in the dialog is pressed. This function calls most of the other functions mentioned above. In addition to the default provided code, you need to do three things:

  • Generate a symbol with the value of the current date to write in the files header
  • Add a symbol for each filter to add to the project
  • Call AddCommonConfig function to add the default Debug and Release configurations to the project

The code of the function is shown below:

function OnFinish(selProj, selObj)
{
   try
   {
      var strProjectPath = wizard.FindSymbol('PROJECT_PATH');
      var strProjectName = wizard.FindSymbol('PROJECT_NAME');

      // get the current date and add a symbol CURRENT_DATE
      var currentTime = new Date();
      var month       = currentTime.getMonth() + 1
      var day         = currentTime.getDate();
      var year        = currentTime.getFullYear();
      var today       = year + '.' + month + '.' + day;
      wizard.AddSymbol('CURRENT_DATE', today);

      // add symbols for the filters of the project
      wizard.AddSymbol('MY_SOURCE_FOLDER_NAME',   'Source Files');
      wizard.AddSymbol('MY_HEADER_FOLDER_NAME',   'Header Files');
      wizard.AddSymbol('MY_RESOURCE_FOLDER_NAME', 'Resource Files');

      selProj = CreateCustomProject(strProjectName, strProjectPath);
      AddCommonConfig(selProj, strProjectName);
      AddConfig(selProj, strProjectName);
      AddFilters(selProj);

      var InfFile = CreateCustomInfFile();
      AddFilesToCustomProj(selProj, strProjectName, strProjectPath,
                           InfFile);
      PchSettings(selProj);
      InfFile.Delete();

      selProj.Object.Save();
   }
   catch(e)
   {
      if (e.description.length != 0)
         SetErrorInfo(e);
      return e.number
   }
}

AddFilters

This function is called to create the filters for the project. Your project will have three filters:

  • Source Files: Contains files with the extensions .cpp, .cxx, .c
  • Header Files: Contains files with the extensions .h, .hpp
  • Resource Files: Contains files with the extensions .rc, .rc2, .bmp, .ico, .gif

In this function, you will retrieve the values of the symbols generated in OnFinish() to use as the filter names.

function AddFilters(proj)
{
   try
   {
      var group1 = proj.Object.AddFilter
                   (wizard.FindSymbol('MY_SOURCE_FOLDER_NAME'));
      group1.Filter = ".cpp;.cxx;.c";

      var group2 = proj.Object.AddFilter
                   (wizard.FindSymbol('MY_HEADER_FOLDER_NAME'));
      group2.Filter = ".h;.hpp";

      var group3 = proj.Object.AddFilter
                   (wizard.FindSymbol('MY_RESOURCE_FOLDER_NAME'));
      group3.Filter = '.rc;.rc2;.ico;.gif;.bmp;';
   }
   catch(e)
   {
      throw e;
   }
}

AddConfig

Use this function to set the various compiler and linker settings for the available configurations. You can access the configuration object in this manner:

var config = proj.Object.Configurations('Debug');

The members of the VCConfiguration interface are listed here. You can set properties such as the IntermediateDirectory, OutputDirectory, or ConfigurationType. An important property is Tools that gives the available tools for the configuration that include:

In the sample code, the compiler, linker, manifest, and browser tools are customized with different settings. The code is listed below:

function AddConfig(proj, strProjectName)
{
   try
   {
      // ----------------------------------------------------------
      // settings for the DEBUG configuration
      // ----------------------------------------------------------
      var config = proj.Object.Configurations('Debug');
      config.IntermediateDirectory = '.\\Debug';
      config.OutputDirectory = '.\\Debug';
      config.InheritedPropertySheets =
         '$(VCInstallDir)VCProjectDefaults\\UpgradeFromVC60.vsprops';
      config.ConfigurationType = ConfigurationTypes.typeApplication;

      var CLTool = config.Tools('VCCLCompilerTool');
      CLTool.AdditionalIncludeDirectories = './;./src/';
      CLTool.Detect64BitPortabilityProblems = false;
      CLTool.PreprocessorDefinitions = 'WIN32;_DEBUG;_CONSOLE';
      CLTool.UsePrecompiledHeader = pchOption.pchCreateUsingSpecific;
      CLTool.PrecompiledHeaderThrough = "StdAfx.h";
      CLTool.PrecompiledHeaderFile = '.\\Debug/' +
         strProjectName + '.pch';
      CLTool.AssemblerListingLocation = '.\\Debug/';
      CLTool.ObjectFile = '.\\Debug/';
      CLTool.ProgramDataBaseFileName = '.\\Debug/';

      var LinkTool = config.Tools('VCLinkerTool');
      LinkTool.OutputFile = '$(OutDir)\$(ProjectName).exe';
      LinkTool.GenerateManifest = false;
      LinkTool.ProgramDatabaseFile = '.\\Debug/' +
         strProjectName + 'D.pdb';
      LinkTool.SubSystem = subSystemOption.subSystemNotSet;
      LinkTool.ImportLibrary = '.\\Debug/' + strProjectName + 'D.lib';

      var ManifestTool = config.Tools('VCManifestTool');
      ManifestTool.EmbedManifest = false;
      ManifestTool.OutputManifestFile = '$(TargetPath).manifest';

      var BrowseTool = config.Tools('VCBscMakeTool');
      BrowseTool.OutputFile = '.\\Debug/' + strProjectName + 'D.bsc';

      // ----------------------------------------------------------
      // settings for the RELEASE configuration
      // ----------------------------------------------------------
      config = proj.Object.Configurations('Release');
      config.IntermediateDirectory = '.\\Release';
      config.OutputDirectory = '.\\Release';
      config.InheritedPropertySheets =
         '$(VCInstallDir)VCProjectDefaults\\UpgradeFromVC60.vsprops';
      config.ConfigurationType = ConfigurationTypes.typeApplication;

      var CLTool = config.Tools('VCCLCompilerTool');
      CLTool.AdditionalIncludeDirectories = './;./src/';
      CLTool.DebugInformationFormat = debugOption.debugDisabled;
      CLTool.Detect64BitPortabilityProblems = false;
      CLTool.InlineFunctionExpansion = expandOnlyInline;
      CLTool.WholeProgramOptimization = false;
      CLTool.PreprocessorDefinitions = 'WIN32;NDEBUG;_CONSOLE';
      CLTool.StringPooling = true;
      CLTool.EnableFunctionLevelLinking = true;
      CLTool.UsePrecompiledHeader = pchOption.pchCreateUsingSpecific;
      CLTool.PrecompiledHeaderThrough = "StdAfx.h";
      CLTool.PrecompiledHeaderFile = '.\\Release/' +
         strProjectName + '.pch';
      CLTool.AssemblerListingLocation = '.\\Release/';
      CLTool.ObjectFile = '.\\Release/';
      CLTool.ProgramDataBaseFileName = '.\\Release/';

      var LinkTool = config.Tools('VCLinkerTool');
      LinkTool.OutputFile = '$(OutDir)\$(ProjectName).exe';
      LinkTool.GenerateManifest = false;
      LinkTool.GenerateDebugInformation = false;
      LinkTool.ProgramDatabaseFile = '.\\Release/' +
         strProjectName + '.pdb';
      LinkTool.SubSystem = subSystemOption.subSystemNotSet;
      LinkTool.OptimizeReferences =
         optRefType.optReferencesDefault;
      LinkTool.EnableCOMDATFolding =
         optFoldingType.optFoldingDefault;
      LinkTool.LinkTimeCodeGeneration =
         LinkTimeCodeGenerationOption.
         LinkTimeCodeGenerationOptionDefault;

      var ManifestTool = config.Tools('VCManifestTool');
      ManifestTool.EmbedManifest = false;
      ManifestTool.OutputManifestFile = '$(TargetPath).manifest';

      var BrowseTool = config.Tools('VCBscMakeTool');
      BrowseTool.OutputFile = '.\\Release/' +
         strProjectName + 'D.bsc';
   }
   catch(e)
   {
      throw e;
   }
}

GetTargetName

This function gets called for every file listed in the Templates.inf file. You can use this method to change the name of the files or the path. That is exactly what we need to do to follow the requirements:

  • Sampleclass.h must be renamed to <CLASS_NAME>.h and put in the src subfolder
  • Sampleclass.cpp must be renamed to <CLASS_NAME>.h and put in the src subfolder
  • BaseSample.cpp must be renamed to main.cpp

All the other file names remain unchanged and they will be placed in the directly under the project folder.

function GetTargetName(strName, strProjectName)
{
   try
   {
      var strTarget = strName;
      // get the name of the class
      var strClassName = wizard.FindSymbol('CLASS_NAME');

      if (strName == 'sampleclass.h')
      {
         strTarget = 'src\\' + strClassName + '.h';
      }
      else if(strName == 'sampleclass.cpp')
      {
         strTarget = 'src\\' + strClassName + '.cpp';
      }
      else if(strName == 'BaseSample.cpp')
         strTarget = 'main.cpp';

      return strTarget;
   }
   catch(e)
   {
      throw e;
   }
}

AddFilesToCustomProj

This function parses the templates file and adds files to the project. For each file name, it calls GetTargetName() to get the name (and relative path) of the file in the project. In the templates, one of the files is ReadMe.txt, but you don't want this file to be added to the project file, only to be degenerated in the project folder. A custom function called KeepOutsideProject() takes the name of each file (the same name passed to GetTargetName, and not the name returned by this function) and returns true if the file should not be listed in the project file.

function KeepOutsideProject(strName)
{
   try
   {
      var add = false;

      if(strName == 'ReadMe.txt')
         add = true;

      return add;
   }
   catch(e)
   {
      throw e;
   }
}

Once a file is generated in the project folder, it is added to the project to one of the available filters, depending of the extension. Complete source code is listed below:

function AddFilesToCustomProj(proj, strProjectName, strProjectPath,
                              InfFile)
{
   try
   {
      var projItems = proj.ProjectItems

      // get references to the filters of the project
      var projFilters = proj.Object.Filters;
      var filterSrc =
         projFilters.Item(wizard.FindSymbol('MY_SOURCE_FOLDER_NAME'));
      var filterHdr =
         projFilters.Item(wizard.FindSymbol('MY_HEADER_FOLDER_NAME'));
      var filterRc =
         projFilters.Item(wizard.FindSymbol('MY_RESOURCE_FOLDER_NAME'));

      var strTemplatePath = wizard.FindSymbol('TEMPLATES_PATH');

      var strTpl  = '';
      var strName = '';

      var strTextStream = InfFile.OpenAsTextStream(1, -2);
      while (!strTextStream.AtEndOfStream)
      {
         strTpl = strTextStream.ReadLine();
         if (strTpl != '')
         {
            strName = strTpl;
            var strTarget = GetTargetName(strName, strProjectName);
            var strTemplate = strTemplatePath + '\\' + strTpl;
            var strFile = strProjectPath + '\\' + strTarget;

            var bCopyOnly = false;
            var strExt = strName.substr(strName.lastIndexOf("."));
            if(strExt==".bmp" || strExt==".ico" || strExt==".gif" ||
               strExt==".rtf" || strExt==".css")
               bCopyOnly = true;
            wizard.RenderTemplate(strTemplate, strFile, bCopyOnly);

            if(!KeepOutsideProject(strName))
            {
               if(strExt == '.cpp' || strExt == '.cxx' ||
                  strExt == '.c')
               {
                  filterSrc.AddFile(strTarget);
               }
               else if(strExt == '.hpp' || strExt == '.h')
               {
                  filterHdr.AddFile(strTarget);
               }
               else if(strExt == '.rc2' ||
                       strExt == '.ico' || strExt == '.gif' ||
                       strExt == '.bmp')
               {
                  filterRc.AddFile(strTarget);
               }
                  else if(strExt == '.rc')
                  {
                     filterRc.AddFile(strFile);
                  }
                  else
                     proj.Object.AddFile(strFile);
            }
         }
      }
      strTextStream.Close();
   }
   catch(e)
   {
      throw e;
  }
}

All the other functions in Default.js should remain unmodified for this sample project.

Create a Visual C++ Wizard for Visual Studio 2005

Deploying the VC++ Wizard

If you followed all the indications I have given in this article so far, the DummyWin32Wizard is completed. Because Visual Studio has copied the necessary entry files in its default folder for wizards, you now can create projects using it, wherever the project is located on your computer. However, I suggest you deploy it in the same location with the other VisualC++ templates. There are two folders:

  • {VS2005InstallationFolder}\VC\VCWizards: Hosts the wizard projects; you should deploy the wizard project in the AppWiz subfolder, either by simply copying the project here, or using an installation project (if you want to deploy it on more machines, not just yours);
  • {VS2005InstallationFolder}\VC\VCProjects: You have to deploy three files here (remember that on your machine you should already have these files in place):
    • DummyWin32Wizard.ico
    • DummyWin32Wizard.vsdir
    • DummyWin32Wizard.vsz

If you deploy the files here, you should change the path parameter in the DummyWin32Wizard.vsz file. The content of the file should change from:

VSWIZARD 7.0
Wizard=VsWizard.VsWizardEngine.8.0

Param="WIZARD_NAME = DummyWin32Wizard"
Param="ABSOLUTE_PATH =
   D:\Cilu\VC++\codeguru\articles\wizard\DummyWin32Wizard"
Param="FALLBACK_LCID = 1033"

to

VSWIZARD 7.0
Wizard=VsWizard.VsWizardEngine.8.0

Param="WIZARD_NAME   = DummyWin32Wizard"
Param="RELATIVE_PATH = VCWizards\AppWiz"
Param="FALLBACK_LCID = 1033"

Using DummyWin32Wizard

Having done that, your VC++ wizard is set in place and you can use it just like all the others wizards: go to File > New > Project, select the VisualC++ category, and then Dummy Win32 Wizard item in the templates list. When you select it, the wizard's settings page is shown:

[wizardpage.png]

If you generate a project called DummyTest and fill in Foo for the name class, and an author name, the generated files for the project are shown below:

[solution2.png]



About the Author

Marius Bancila

Marius Bancila is a Microsoft MVP for VC++. He works as a software developer for a Norwegian-based company. He is mainly focused on building desktop applications with MFC and VC#. He keeps a blog at www.mariusbancila.ro/blog, focused on Windows programming. He is the co-founder of codexpert.ro, a community for Romanian C++/VC++ programmers.

Downloads

Comments

  • There are no comments yet. Be the first to comment!

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

Top White Papers and Webcasts

  • Java developers know that testing code changes can be a huge pain, and waiting for an application to redeploy after a code fix can take an eternity. Wouldn't it be great if you could see your code changes immediately, fine-tune, debug, explore and deploy code without waiting for ages? In this white paper, find out how that's possible with a Java plugin that drastically changes the way you develop, test and run Java applications. Discover the advantages of this plugin, and the changes you can expect to see …

  • Packaged application development teams frequently operate with limited testing environments due to time and labor constraints. By virtualizing the entire application stack, packaged application development teams can deliver business results faster, at higher quality, and with lower risk.

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds