Dela via


How to: Compile and Run a Complete Windows Forms Code Example Using Visual Studio

Windows Forms Help contains complete code examples that you can compile and run with minimal setup. A complete Windows Forms code example contains a class derived from Form and a Main method. With this class and the Main method, you have all the code you need to compile and run the example from the command line. However, to use the code with Visual Studio, you must avoid conflicts between the example code and code that Visual Studio generates.

When you create your own Windows Forms project or follow the steps of a procedure in Help, you typically start with a new Windows Application project in Visual Studio. This project type includes Form code and other startup code that duplicates the code in a complete code example. The following procedure describes how to avoid conflicts by starting with an empty Windows project for Visual Basic or Visual C#.

Note

The dialog boxes and menu commands you see might differ from those described in Help depending on your active settings or edition. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see Working with Settings.

To add a complete code example to a Visual Studio project

  1. In the Help topic that contains the complete code listing, click Copy Code.

  2. In Visual Studio, on the File menu, point to New, and then select Project.

    The New Project dialog box appears.

  3. In the Project Types pane, expand Visual Basic or Visual C#, and then select Windows.

  4. In the Templates pane, select Empty Project.

  5. Specify a name and location for the project and click OK.

    The new project opens in Visual Studio.

  6. In Solution Explorer, right-click your project, and then select Add Reference.

  7. In the Add Reference dialog box, select the assemblies required by the example and click OK.

    The assemblies are typically listed at the end of the Help topic that contains the complete code example.

  8. In Solution Explorer, right-click your project, point to Add, and then select Class.

  9. In the Add New Item dialog box, specify a name for the class and click Add.

    The new class opens in the code editor.

  10. Select the code in the new class file, and then replace it by pasting in the code from the Help topic.

  11. Press F5 to compile and run the example.

See Also

Tasks

How to: Create a New Windows Forms Application Project

How to: Create a Windows Forms Application from the Command Line

How to: Create a Project from Existing Code Files

Other Resources

Creating a New Windows Form

Getting Started with Windows Forms

Windows Forms Controls

How to: Find Topics with Sample Code