100% found this document useful (1 vote)
687 views1,028 pages

Visual Studio Manual

Visual studio manual with examples

Uploaded by

exeri0n
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
687 views1,028 pages

Visual Studio Manual

Visual studio manual with examples

Uploaded by

exeri0n
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1028

Contents

Visual Studio IDE


Visual Studio IDE
Optimize Visual Studio Startup Time
Move Around in the IDE
Finding and Using Visual Studio Extensions
Get Started Developing with Visual Studio
Get Started Developing with Visual Studio
Getting Started with Visual C# and Visual Basic
Getting Started with Visual C# and Visual Basic
Create a Simple Application
Tutorial 1 - Create a Picture Viewer
Tutorial 1 - Create a Picture Viewer
Step 1 - Create a Windows Forms Application Project
Step 2 - Run Your Program
Step 3 - Set Your Form Properties
Step 4 - Lay Out Your Form with a TableLayoutPanel Control
Step 5 - Add Controls to Your Form
Step 6 - Name Your Button Controls
Step 7 - Add Dialog Components to Your Form
Step 8 - Write Code for the Show a Picture Button Event Handler
Step 9 - Review, Comment, and Test Your Code
Step 10 - Write Code for Additional Buttons and a Check Box
Step 11 - Run Your Program and Try Other Features
Tutorial 2 - Create a Timed Math Quiz
Tutorial 2 - Create a Timed Math Quiz
Step 1 - Create a Project and Add Labels to Your Form
Step 2 - Create a Random Addition Problem
Step 3 - Add a Countdown Timer
Step 4 - Add the CheckTheAnswer() Method
Step 5 - Add Enter Event Handlers for the NumericUpDown Controls
Step 6 - Add a Subtraction Problem
Step 7 - Add Multiplication and Division Problems
Step 8 - Customize the Quiz
Tutorial 3 - Create a Matching Game
Tutorial 3 - Create a Matching Game
Step 1 - Create a Project and Add a Table to Your Form
Step 2 - Add a Random Object and a List of Icons
Step 3 - Assign a Random Icon to Each Label
Step 4 - Add a Click Event Handler to Each Label
Step 5 - Add Label References
Step 6 - Add a Timer
Step 7 - Keep Pairs Visible
Step 8 - Add a Method to Verify Whether the Player Won
Step 9 - Try Other Features
Getting Started with C++
Getting Started with Debugging in Visual Studio 2015
Solutions and Projects
Creating Solutions and Projects
Adding and Removing Project Items
Managing Project and Solution Properties
Managing references in a project
Managing references in a project
Add or Remove References By Using the Reference Manager
Adding References Using NuGet Versus an Extension SDK
Add or Remove Imported Namespaces (Visual Basic)
Troubleshooting Broken References
Application Properties
Managing Application Resources (.NET)
Managing Application Settings (.NET)
Managing Assembly and Manifest Signing
Managing Assembly and Manifest Signing
Sign Application and Deployment Manifests
Specify an Application Icon (Visual Basic, C#)
Targeting a Specific .NET Framework Version
Targeting a Specific .NET Framework Version
Visual Studio Multi-Targeting Overview
Target a Version of the .NET Framework
Creating Project and Item Templates
Creating Project and Item Templates
Create Project Templates
Create Multi-Project Templates
Create Item Templates
Create Multi-file Item Templates
Manually Create Web Templates
Create Starter Kits
Locate and Organize Templates
Customizing Templates
Customizing Templates
Update Existing Templates
Substitute Parameters in a Template
Troubleshoot Templates
Visual Studio Template Reference
Visual Studio Template Reference
Template Parameters
Writing Code
Writing Code
Finding and Replacing Text
Finding and Replacing Text
Using Regular Expressions in Visual Studio
Find/Command Box
Find in Files
Replace in Files
Encodings and Line Breaks
Outlining
Refactoring
Productivity Tips
Productivity Tips
Tips and Tricks
Identifying and Customizing Keyboard Shortcuts
Identifying and Customizing Keyboard Shortcuts
Default Keyboard Shortcuts for Frequently Used Commands
Default Keyboard Shortcuts
Using IntelliSense
Using IntelliSense
Visual Basic-Specific IntelliSense
Visual Basic-Specific IntelliSense
Filtered Completion Lists in Visual Basic
Visual C# IntelliSense
Test-First Support with the Generate From Usage Feature
JavaScript IntelliSense
JavaScript IntelliSense
Create JSDoc Comments
Create XML Documentation Comments
Extending JavaScript IntelliSense
Statement Completion for Identifiers
Customizing IntelliSense for RequireJS
XML Documentation Comments
XML Documentation Comments
\<deprecated>
\<field>
\<loc>
\<param>
\<returns>
\<signature>
\<summary>
\<value>
\<var>
Visual C++ Intellisense
Supplying XML Code Comments
Customizing the Editor
Customizing the Editor
Change Text Case in the Editor
Manage Editor Modes
Manage Editor Windows
Track Your Code by Customizing the Scrollbar
View and Edit Code by Using Peek Definition (Alt+F12)
Perform quick actions with light bulbs
Code Snippets
Code Snippets
Creating a Code Snippet
Distribute Code Snippets
Visual C# Code Snippets
Visual C++ Code Snippets
Code Snippet Functions
Restore C# Refactoring Snippets
Use Surround-with Code Snippets
Best Practices for Using Code Snippets
Troubleshooting Snippets
Code Snippets Schema Reference
Using the Toolbox
Viewing the Structure of Code
Viewing the Structure of Code
Class View and Object Browser Icons
Designing and Viewing Classes and Types
Designing and Viewing Classes and Types
Working with Classes and Other Types (Class Designer)
Working with Classes and Other Types (Class Designer)
Working with Class Diagrams (Class Designer)
Designing Classes and Types (Class Designer)
Viewing Types and Relationships (Class Designer)
Refactoring Classes and Types (Class Designer)
Working with Visual C++ Code (Class Designer)
Additional Information About Class Designer Errors
Setting Bookmarks in Code
Using the Task List
Find code changes and other history
Find code changes and other history
CodeIndex Command
Using the Visual Studio Development Environment for C#
Using the Visual Studio Development Environment for C#
Add an Application Configuration File to a C# Project
Metadata as Source
Refactoring (C#)
Refactoring (C#)
Extract Method Refactoring (C#)
Rename Refactoring (C#)
Encapsulate Field Refactoring (C#)
Extract Interface Refactoring (C#)
Remove Parameters Refactoring (C#)
Reorder Parameters Refactoring (C#)
Debugging in Visual Studio
Profiling
Improve Code Quality
Designing User Interfaces
Analyzing and Modeling Architecture
Compiling and Building
Compiling and Building
Building an Application
Building and Cleaning Projects and Solutions in Visual Studio
Building and Cleaning Projects and Solutions in Visual Studio
Change the Build Output Directory
Build to a Common Output Directory
Specifying Custom Build Events in Visual Studio
Set Multiple Startup Projects
Create and Remove Project Dependencies
View, Save, and Configure Build Log Files
Exclude Projects from a Build
Suppress Compiler Warnings
Understanding Build Configurations
Understanding Build Configurations
Create and Edit Configurations
Manage Configurations with Visual Basic Developer Settings Applied
Build Multiple Configurations Simultaneously
Understanding Build Platforms
Understanding Build Platforms
Configure Projects to Target Platforms
Configure Projects to Target Multiple Platforms
Specify Build Events (Visual Basic)
Specify Build Events (C#)
Configuring Warnings in Visual Basic
Disable the Hosting Process
Disable the Hosting Process
Hosting Process (vshost.exe)
Creating a Multiple-Computer Build Environment
Deploying Applications, Services, and Components
Visual Studio IDE 64-Bit Support
Visual Studio Samples
User Accounts and Updates
User Accounts and Updates
Signing in to Visual Studio
Work with multiple user accounts
How to Unlock Visual Studio
Notifications
Personalizing the IDE
Personalizing the IDE
Change Fonts and Colors
Customize Menus and Toolbars
Customizing window layouts
Customizing the Start Page
Managing External Tools
Synchronized Settings
Security
Security
Securing Applications
Maintaining Security
User Permissions
Security Bibliography
Visual Studio Samples
Microsoft Help Viewer
Microsoft Help Viewer
Microsoft Help Viewer Installation
Help Viewer Administrator Guide
Help Viewer Administrator Guide
Command-Line Arguments for the Help Content Manager
Help Content Manager Overrides
Install and Manage Local Content
Locate Information
Locate Information
Find Topics in the Index
Find Topics in the Index
Index Search Tips
Find Topics in the Table of Contents
Search for Topics
Search for Topics
Full-Text Search Tips
Logical Operators in Search Expressions
Advanced Search Operators in Search Expressions
Customize Search Results
Manage the Help Viewer Window
Retain Topics for Later Use
Customize the Help Viewer
Troubleshooting the Help Viewer
Accessibility Features of the Help Viewer
Accessibility Features of the Help Viewer
Shortcut Keys (Help Viewer)
Globalizing and Localizing Applications
Globalizing and Localizing Applications
Introduction to International Applications Based on the .NET Framework
Localizing Applications
Localizing Applications
Hierarchical Organization of Resources for Localization
Security and Localized Satellite Assemblies
Version Numbers for Main and Localized Satellite Assemblies
Neutral Resources Languages for Localization
Globalizing Applications
Globalizing Applications
Culture-Specific Classes for Global Windows Forms and Web Forms
Creating Applications in Bi-directional Languages
Creating Applications in Bi-directional Languages
Save and Open Files with Encoding
Adding Visual Studio editor support for other languages
Reference
General User Interface Elements (Visual Studio)
General User Interface Elements (Visual Studio)
Call Hierarchy
Choose Toolbox Items, WPF Components
Code Snippet Picker
Command Window
Convert Dialog Box
Error List Window
File Properties, JavaScript
Go To Line
Immediate Window
Miscellaneous Files
Options Dialog Box
Environment Options Dialog Box
Environment Options Dialog Box
General, Environment, Options Dialog Box
AutoRecover, Environment, Options Dialog Box
Documents, Environment, Options Dialog Box
Extensions and Updates, Environment, Options Dialog Box
Find and Replace, Environment, Options Dialog Box
Fonts and Colors, Environment, Options Dialog Box
Import and Export Settings, Environment, Options Dialog Box
International Settings, Environment, Options Dialog Box
Keyboard, Environment, Options Dialog Box
Notifications, Environment, Options Dialog Box
Quick Launch, Environment, Options Dialog Box
Startup, Environment, Options Dialog Box
Synchronized Settings, Environment, Options Dialog Box
Tabs and Windows, Environment, Options Dialog Box
Task List, Environment, Options Dialog Box
Web Browser, Environment, Options Dialog Box
Options Page, Environment Node Properties
Text Editor Options Dialog Box
Text Editor Options Dialog Box
Change Fonts and Colors in the Editor
Manage Word Wrap in the Editor
Display Line Numbers in the Editor
Display URLs as Links in the Editor
Setting Language-Specific Editor Options
Options, Text Editor, General
Options, Text Editor, File Extension
Options, Text Editor, All Languages
Options, Text Editor, All Languages, Tabs
Options, Text Editor, Basic (Visual Basic)
Options, Text Editor, C/C++, Formatting
Options, Text Editor, C/C++, Advanced
Options, Text Editor, C/C++, Experimental
Options, Text Editor, C#, Formatting
Options, Text Editor, C#, Advanced
Options, Text Editor, C#, IntelliSense
Options, Text Editor, JavaScript, Formatting
Options, Text Editor, JavaScript, IntelliSense
Options, Text Editor, XAML, Formatting
Options Page, Fonts and Colors Node Properties
Options Page, Text Editor Node Properties
Options Page, Debugging Node Properties
Output Window
Project Properties Reference
Project Properties Reference
Application Page, Project Designer (Visual Basic)
Application Page, Project Designer (Visual Basic)
Assembly Information Dialog Box
Application Page, Project Designer (C#)
Build Events Page, Project Designer (C#)
Build Events Page, Project Designer (C#)
Pre-build Event/Post-build Event Command Line Dialog Box
Build Page, Project Designer (C#)
Build Page, Project Designer (C#)
Advanced Build Settings Dialog Box (C#)
Code Analysis, Project Designer
Compile Page, Project Designer (Visual Basic)
Compile Page, Project Designer (Visual Basic)
Advanced Compiler Settings Dialog Box (Visual Basic)
Build Events Dialog Box (Visual Basic)
Debug Page, Project Designer
My Extensions Page, Project Designer
Publish Page, Project Designer
Publish Page, Project Designer
Prerequisites Dialog Box
References Page, Project Designer (Visual Basic)
Security Page, Project Designer
Security Page, Project Designer
Advanced Security Settings Dialog Box
Services Page, Project Designer
Services Page, Project Designer
Advanced Settings for Services Dialog Box
Signing Page, Project Designer
Visual Basic Defaults, Projects, Options Dialog Box
VC++ Project Settings, Projects and Solutions, Options Dialog Box
Project and Solution File Types
Projects and Solutions, Options Dialog Box
Projects and Solutions, Options Dialog Box
Options Dialog Box, Projects and Solutions, Build and Run
Options Dialog Box, Projects and Solutions, Web Projects
Property Pages, JavaScript
Properties Window
Toolbox
Toolbox
Toolbox, Components Tab
Toolbox, Data Tab
Toolbox, HTML Tab
Devenv Command Line Switches
Devenv Command Line Switches
/?
/Build
/Clean
/Command
/DebugExe
/Deploy
/Diff
/Edit
/LCID
/Log
/Out
/Project
/ProjectConfig
/Rebuild
/ResetAddin
/InstallVSTemplates
/ResetSettings
/ResetSkipPkgs
/Run
/Runexit
/SafeMode
/Setup
/Updateconfiguration
/Upgrade
/UseEnv
Visual Studio Commands
Visual Studio Commands
Visual Studio Command Aliases
Add Existing Item Command
Add Existing Project Command
Add New Item Command
Alias Command
Evaluate Statement Command
Find Command
Find in Files Command
Go To Command
Import and Export Settings Command
List Call Stack Command
List Disassembly Command
List Memory Command
List Modules Command
List Registers Command
List Source Command
List Threads Command
Log Command Window Output Command
New File Command
Open File Command
Open Project Command
Open Solution Command
Print Command
Quick Watch Command
Replace Command
Replace In Files Command
Set Current Process
Set Current Stack Frame Command
Set Current Thread Command
Set Radix Command
Shell Command
ShowWebBrowser Command
Start Command
Symbol Path Command
Toggle Breakpoint Command
Watch Command
XML Tools
Visual Studio for Applications Reference
MSBuild
Resources for Troubleshooting IDE Errors
Accessibility for People with Disabilities
Accessibility for People with Disabilities
Accessibility Features of Visual Studio
Accessibility Features of Visual Studio
Set IDE Accessibility Options
Use the Keyboard Exclusively
Accessibility Tips and Tricks
Accessibility Products and Services from Microsoft
Resources for Designing Accessible Applications
Proxy Authorization Required
Visual Studio IDE
10/16/2020 • 16 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version
selector at the top left. We recommend upgrading to Visual Studio 2019. Download it here

Microsoft Visual Studio 2015 is a suite of tools for creating software, from the planning phase through UI design,
coding, testing, debugging, analyzing code quality and performance, deploying to customers, and gathering
telemetry on usage. These tools are designed to work together as seamlessly as possible, and are all exposed
through the Visual Studio Integrated Development Environment (IDE).
You can use Visual Studio to create many kinds of applications, from simple store apps and games for mobile
clients, to large, complex systems that power enterprises and data centers. You can create:
Apps and games that run not only on Windows, but also Android and iOS.
Websites and web services based on ASP.NET, JQuery, AngularJS, and other popular frameworks.
Applications for platforms and devices as diverse as Azure, Office, Sharepoint, Hololens, Kinect, and Internet
of Things, to name just a few examples.
Games and graphics-intensive applications for a variety of Windows devices, including Xbox, using DirectX.
Visual Studio by default provides support for C#, C and C++, JavaScript, F#, and Visual Basic. Visual Studio works
and integrates well with third-party applications like Unity through the Visual Studio Tools for Unity extension and
Apache Cordova through Visual Studio Tools for Apache Cordova. You can extend Visual Studio yourself by
creating custom tools that perform specialized tasks.
If you’ve never used Visual Studio before, learn the basics with our Get Started Developing with Visual Studio
tutorials and walkthroughs.
If you want to find out about new features in Visual Studio 2015, see What's New in Visual Studio 2015.

Visual Studio Setup


You can find out which edition of Visual Studio is right for you at Visual Studio Editions.
You can install Visual Studio 2015 by downloading it from Visual Studio Downloads. If you need to know more
about the installation process, see Installing Visual Studio 2015.

IDE Basics
The following image shows the Visual Studio IDE with an open project, and the Solution Explorer window for
navigating in the project files, and the Team Explorer window for navigating source control and work item
tracking. The features in the title bar that are called out are explained below in more detail.
Signing in
When you start Visual Studio for the first time, you can sign in using your Microsoft account, or your work or
school account. Being signed in allows you to synchronize your settings, such as window layouts, across multiple
devices and connect automatically to the services you might need, such as Azure subscriptions and Visual Studio
Team Services. If you have a subscription-based license, you'll need to sign in to Visual Studio on a regular basis in
order to keep your license token fresh. If you have a product key license, you don't have to sign in, but doing so
makes it more convenient to connect to Visual Studio Team Services and your accounts with Azure, Office 365,
Salesforce.com. For more information, see Signing in to Visual Studio.
If you have multiple Visual Studio Team Services accounts, Azure accounts or MSDN subscriptions, you can link
them and access resources and services in all your accounts with a single sign-in. For more information, see Work
with multiple user accounts.
Staying up to date
The notification icon in the upper right of the title bar tells you when updates are available for Visual Studio or any
related components that you have installed. You can choose whether to dismiss or act on these notifications. For
more information, see Visual Studio Notifications.
Finding things and getting help
The Quick Launch window shown below is a fast way to find Visual Studio commands, tools, features, and so on
when you don't know the keyboard shortcut or menu location. Just type what you are looking for and Quick
Launch will give you a link to it.
MSDN is the Microsoft web site for technical documentation; you are reading this page on MSDN right now! In
Visual Studio, you can press F1 to go to the MSDN help page for the active window. You can also press F1 in the
code editor to go to the MSDN help page for the API or keyword at the current caret position. For example, in a C#
file, place the caret somewhere in or just at the end of a System.String declaration, and press F1 to go to the
MSDN help page for String.
Giving feedback
It's easy to give us feedback on Visual Studio whenever you like. Click the feedback icon in the title bar next to
QuickLaunch and then click on Repor t a Problem or Provide a Suggestion . Pre-release editions of Visual
Studio also have a Rate this Product option. We look at all these comments and use them to improve the
product. For more information, see Talk to Us.
Personalizing the IDE
You can customize the window layout to fit your development style. You can dock, float or hide any window at any
time, and you also can run the editor in full-screen mode. You can create and save multiple custom window
layouts that show only the windows you need for specific contexts. For example, you can create a full-screen
layout so that all you see is the code editor. And you can create different layouts for debugging and for team
operations. For more information, see Customizing window layouts.
You can customize Visual Studio in many other ways, and roam your settings if you work on multiple machines.
For more information, see Personalizing the IDE.
There are keyboard shortcuts for almost everything, and you can customize them as well. To create new shortcuts,
type "Keyboard" in Quick Launch to open the Keyboard dialog box. From there, you can press F1 to go to the
MSDN help page if you need more information about the options. For more information, see Default Keyboard
Shortcuts in Visual Studio.

Connecting to Visual Studio Team Services and Team Foundation


Server
Visual Studio Team Services (VSTS) is a cloud-based service for hosting software projects and enabling
collaboration in teams. VSTS supports both Git and Team Foundation Source Control systems, as well as Scrum,
CMMI and Agile development methodologies. Team Foundation Version Control (TFVC) uses a single, centralized
server repository to track and version files. Local changes are always checked in to the central server where other
developers can get the latest changes. Team Foundation Server (TFS) 2015 is the application lifecycle management
hub for Visual Studio. It enables everyone involved with the development process to participate using a single
solution. TFS is useful for managing heterogeneous teams and projects, too.
If you have a Visual Studio Team Services account or a Team Foundation Server on your network, you connect to it
through the Team Explorer window. From this window you can check code into or out of source control, manage
work items, start builds, and access team rooms and workspaces. You can open Team Explorer from Quick
Launch or on the main menu from View | Team Explorer or from Team | Manage Connections . For more
information about Visual Studio Team Services, see www.visualstudio.com. For more information about Team
Foundation Server, see Team Foundation Server.
The following image shows the Team Explorer pane for a solution that is hosted in VSTS:

Creating solutions and projects


Although you can use Visual Studio to browse individual code files, more commonly you will be working in a
project. A Visual Studio project is a collection of files and resources that are compiled to a single binary executable
file for applications (for example, an .exe, DLL, or appx). For non-ASP.NET websites, no executable is produced and
the project contains only the HTML, JavaScript files, and images. Because sometimes you might need to create
multiple binaries or websites that are closely related, Visual Studio has the concept of the Solution, which can
contain multiple projects or websites. When you create a project, you are actually creating a project-in-a-solution,
and you can add more projects to that solution later if you need to. For example, if you have a DLL project, you can
add an .exe project to the solution that loads and consumes the DLL.
A project template is a collection of pre-populated code files and configuration settings that get you set up quickly
to create a specific kind of application. Visual Studio comes with many project templates to choose from, and if
none of the default templates work for you, you can create your own. After you create a project with a template,
you can start writing your own code in it, either in the files provided or in new files you add. For more information,
see Solutions and Projects. The following illustration shows the New Project dialog with the project templates that
are available for ASP.NET applications.
Designing the user interface
A designer is an intuitive tool that enables you to create a user interface without writing code. You can drag UI
controls such as list boxes, calendars, and buttons from the Toolbox window onto a design surface that represents
the window or dialog box. You can resize and rearrange the elements without writing any code. Designers are
included for any project type that has a user interface.
If your project has a XAML-based user interface, the default designer is Blend for Visual Studio, a sophisticated
graphics tool that works seamlessly with Visual Studio.

IM A GE DESC RIP T IO N

Design view Displays the visual design of your document. In


this view, you can draw or modify objects on the design
surface.
IM A GE DESC RIP T IO N

Breadcrumb Quickly move between template-editing mode,


style-editing mode, and object-editing scope for a selected
object.

Zoom Use to zoom the design surface or objects on the


design surface.

Design surface controls Use these controls (Show snap


grid , Snap to gridlines and Turn on or off snapping to
snaplines ) to set snapping options. Snapping is useful for
lining objects up to each other or to evenly-spaced lines on
the design surface.

Code editor Edit your XAML, C#, C++ or Visual Basic code
manually in the Code editor.

For more information, see Designing XAML in Visual Studio and Blend for Visual Studio.

Writing, navigating and understanding code


If you are a developer, the editor window is where you will probably spend most of your time. Visual Studio
includes editors for C#, C++, Visual Basic, JavaScript, XML, HTML, CSS, and F#, and third parties offer plug-in
editors (and compilers) for many other languages.
You can edit individual files in the text editor by clicking File | Open | File. To edit files in an open project, click on
the file name in Solution Explorer. The code is colorized, and you can personalize the color scheme by typing
“Colors” in Quick Launch. You can have lots of text editor tabbed windows open at once. You can split each window
independently. You can also run the text editor in full-screen mode.

The text editor is highly interactive (if you want it to be) with many productivity features that help you write better
code faster. The features vary by language, and you don’t have to use any of them (Type "Editor" in Quick Launch)
to turn features on or off: Some of the common productivity features are:
1. Refactoring includes operations such as intelligent renaming of variables, moving selected lines of code
into a separate function, moving code to other locations, redordering function parameters, and more.
2. IntelliSense is an umbrella term for a set of popular features that display type information about your code
directly in the editor and, in some cases, write small bits of code for you. It’s like having basic
documentation inline in the editor, which saves you from having to look up type information in a separate
help window. IntelliSense features vary by language. For more information, see Visual C# IntelliSense,
Visual C++ Intellisense, JavaScript IntelliSense, Visual Basic-Specific IntelliSense. The following illustration
shows some IntelliSense features at work:
3. Squiggles alert you to errors or potential problems in your code in real time as you type, which enables
you to fix them immediately without waiting for the error to be discovered during compilation or run time.
If you hover over the squiggle, you see additional information about the error. A light bulb may also appear
in the left margin with suggestions for how to fix the error. For more information, see Perform quick actions
with light bulbs.

4. Bookmarks enable you to navigate quickly to specific lines in files that you are actively working on.
5. The Call Hierarchy window can be invoked in the text editor context menu to show the methods that call,
and are called by, the method under the caret.
6. Code Lens enables you to find references and changes to your code, linked bugs, work items, code
reviews, and unit tests, all without leaving the editor. For more information, see Find code changes and
other history.
7. The Peek to Definition window shows a method or type definition inline, without navigating away from
your current context. This window now works for XAML, too.
8. The Go To Definition context menu option takes you directly to the place where the function or object is
defined. Other navigation commands are also available by right-clicking in the editor.
9. A related tool, the Object Browser, enables you to inspect .NET or Windows Runtime assemblies on your
system to see what types they contain and what methods and properties those types contain.
Most of the items on the Edit menu and View menu relate to the code editor in some way. For more
information about the editor, see Writing Code and Editing Your Code.

Compiling and building your code


To build a project means to compile the source code and perform whatever steps are necessary to produce the
executable. Different languages have different build operations, and regular websites don't build at all. Regardless
of the project type, the Build menu is the standard location for these commands. To compile and run your code
with a single keystroke, press F5. Every compiler is completely configurable through the IDE. The Build toolbar
enables you to specify whether to build a debug version of your program, with symbols and extra error checking
enabled to support breakpoints and single stepping in the debugger, or a release build, which is what you will
ultimately give to customers. You can configure more build settings and many other settings on the property page
for a project. Right-click on the project node in Solution Explorer and choose Properties. You can also run builds
from the command line.
The output from the build, including an error or success messages, appear in the Output window. The Error List
shows detailed information on build errors.

Debugging your code


Visual Studio’s state-of-the-art debugger enables you to debug code running in your local project, on a remote
device, or on an emulator such as the ones for Android or Windows Phone. You can step through code one
statement at a time and inspect variables as you go, you can step through multi-threaded applications, and you
can set breakpoints that are only hit when a specified condition is true. All of this can be configured in the code
editor itself, so that you don't have to leave the context of your code.

The debugger itself has multiple windows that enable you to view and manipulate local variables, the call stack,
and other aspects of the runtime environment. You can find these windows on the Debug menu.
The Immediate Window enables you to type in an expression and see its result immediately.
The IntelliTrace window records each method call and other events in a running .NET program and can help you to
quickly locate where a problem originates.
For more information, see Debugging in Visual Studio.

Testing your code


Visual Studio includes a unit test framework for managed code (.NET) and one for native C++. To create unit tests,
simply add a Test Project to your solution, write your tests, and then run them from the Test Explorer window. For
more information, see Unit Test Your Code.

Analyzing code quality and performance


Visual Studio includes powerful tools for static and runtime analysis. The static analysis tools help you identify
potential errors in design, globalization, interoperability, performance, security, and other categories. Performance
testing, or profiling, involves measuring how your program runs. You access these tools from the Analyze menu.
For more information, see Improving Quality with Visual Studio Diagnostic Tools.

Connecting to cloud services and databases


The Server Explorer window in Visual Studio shows the resources in all the accounts managed under your
personalization account (the one you logged in with), including SQL Server instances, Azure, Salesforce.com,
Office 365, and websites.

Visual Studio includes Microsoft SQL Server Data Tools (SSDT), which enable you to build, debug, maintain, and
refactor databases. You can work with a database project, or directly with a connected database instance on- or
off-premises.
The SQL Server Object Explorer in Visual Studio offers a view of your database objects similar to SQL Server
Management Studio. SQL Server Object Explorer allows you to do light-duty database administration and design
work, including editing table data, comparing schemas, and executing queries by using contextual menus right
from the SQL Server Object Explorer. SSDT also includes special project types and tools for developing SQL Server
2012 Analysis Services, Reporting Services, and Integration Services Business Intelligence (BI) solutions (formerly
known as Business Intelligence Development Studio).

Deploying your finished application


When your application is ready to deploy to customers, Visual Studio provides the tools to do that, whether you’re
deploying to the Windows Store, to a SharePoint site, or with InstallShield or Windows Installer technologies. It's
all accessible via the IDE. For more information, see Deploying Applications, Services, and Components.

Architecture and modeling tools (Enterprise only)


You can use Visual Studio architecture and modeling tools to design and model your app. These tools help you to
visualize the code's structure, behavior, and relationships. You can create models at different levels of detail
throughout the application lifecycle as part of your development process. You can track requirements, tasks, test
cases, bugs, and other work associated with your models by linking model elements to Team Foundation Server
work items and your development plan. For more information, see Design and model your app.

Extending Visual Studio through the Visual Studio SDK


Visual Studio is an extensible platform. A Visual Studio extension is a custom tool that integrates with the IDE. You
can add third-party extensions or create your own. For more information, see Developing Visual Studio
Extensions.
The Visual Studio User Experience Guidelines are an essential reference for anyone writing extensions for Visual
Studio. These platform-specific guidelines include information on dialog design, fonts, colors, icons, common
controls, and other interaction patterns that will make your new feature integrate seamlessly with Visual Studio.

In this Guide
User Accounts and Updates
Personalizing the IDE
How to: Move Around in the IDE
Get Started Developing with Visual Studio
Finding and Using Visual Studio Extensions
Solutions and Projects
Writing Code
Debugging in Visual Studio
Profiling Tools
Improve Code Quality
Designing User Interfaces
Analyzing and Modeling Architecture
Compiling and Building
Deploying Applications, Services, and Components
Visual Studio IDE 64-Bit Support
Security
Visual Studio Samples
Microsoft Help Viewer
Globalizing and Localizing Applications
UI Reference

See Also
Installing Visual Studio 2015
Editing Your Code
What's New in Visual Studio 2015
Porting, Migrating, and Upgrading Visual Studio Projects
Talk to Us
Optimize Visual Studio Startup Time
10/18/2019 • 2 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version selector
at the top left. We recommend upgrading to Visual Studio 2019. Download it here

Ideally, Visual Studio should always start up as quickly as possible. However, Visual Studio extensions and open tool
windows can adversely affect startup time because they load automatically at startup. The Manage Visual Studio
Performance window enables you to not only see which extensions and features affect Visual Studio startup time,
but also lets you determine their loading behavior so you have more control over how quickly Visual Studio starts
up.

Control startup behavior


To avoid extending startup time, Visual Studio 2017 and later avoid loading extensions during startup, using an on-
demand-load approach. This means that extensions don't open immediately after Visual Studio starts, but rather
open asynchronously on an as-needed basis after startup. Also, because tool windows left open in a prior Visual
Studio session can slow startup time, Visual Studio opens tool windows in a more intelligent way to avoid
impacting startup time.
If Visual Studio detects slow startup, a pop-up message appears, alerting you to the extension or tool window that's
causing the slowdown. The message also provides a link to the Manage Visual Studio Performance dialog box,
which lists the extensions and tools windows that are affecting startup performance. This dialog box enables you to
change extension and tool window settings to improve startup performance.

The Manage Visual Studio Performance dialog box has two categories: Extensions and Tool Windows .
Control extensions
If an extension is slowing down Visual Studio startup, the extension appears in the Manage Visual Studio
Performance dialog box when you choose one of the extension types. If the impact on startup time (which is
listed under the Impact section) is unacceptably high, you can choose to always disable the extension at startup by
choosing the Disable button. You can re-enable the extension for future sessions by using the Extension Manager
or the Manage Visual Studio Performance dialog box.
In addition to startup extensions, you can also disable extensions that load when solutions load, or when a user
types. Just choose the scenario to see a list of the associated extensions.
Control tool windows
If a tool window is slowing down Visual Studio startup, you can choose to leave it at its default behavior (giving you
no benefit in startup speed), or you can override its behavior by choosing one of two behaviors:
Do not show window at star tup: If you choose this option, the specified tool window will always be closed
when you open Visual Studio, even if left open in a previous session. You can open the tool window from the
menu.
Auto hide window at star tup: If a tool window was left open in a previous session, choosing this option will
collapse the tool window's group at startup to avoid initializing the tool window. This is a good choice if you use
a tool window often, because the tool window is still available, but no longer negatively affects Visual Studio
startup time.

If you later change your mind, you can revert any of these options in the Manage Visual Studio Performance
dialog box. To open the Manage Visual Studio Performance dialog box, on the menu bar, choose Help ,
Manage Visual Studio Performance .
How to: Move Around in the Visual Studio IDE
10/18/2019 • 4 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version selector
at the top left. We recommend upgrading to Visual Studio 2019. Download it here

The integrated development environment (IDE) has been designed to allow you to move from window to window
and file to file in several different ways, depending on your preference or project requirements. You can choose to
cycle through open files in the editor, or cycle through all active tool windows in the IDE. You also can switch
directly to any file open in the editor, regardless of the order in which it was last accessed. These features can help
increase your productivity when working in the IDE.

NOTE
The options available in dialog boxes, and the names and locations of menu commands you see, might differ from what is
described in Help depending on your active settings or edition. This Help page was written with General Development
Settings in mind. To change your settings, choose Impor t and Expor t Settings on the Tools menu. For more
information, see Customizing Development Settings in Visual Studio.

Keyboard Shortcuts
Almost every menu command in Visual Studio has a keyboard shortcut. You can also create your own custom
shortcuts. For more information, see Identifying and Customizing Keyboard Shortcuts.

Navigating Among Files in the Editor


You can use several methods to move through the files open in the editor. You can move among files based on the
order in which you access them, use the IDE Navigator to quickly find any file currently open, or pin favorite files to
the tab well so that they are always visible.
Navigate Backward and Navigate Forward cycle through the open files in the editor based on the order in which
they were accessed, much like Back and Forward do for your viewing history in Microsoft Internet Explorer.
To move through open files in order of use
To activate open documents in the order they were most recently touched, press CTRL + MINUS SIGN.
To activate open documents in the reverse order, press CTRL + SHIFT + MINUS SIGN.

NOTE
Navigate Backward and Navigate For ward also can be found on the View menu.

You also can switch to a specific file open in the editor, regardless of when you last accessed the file, using
the IDE Navigator , the Active Files list in the editor, or the Windows dialog box.
The IDE Navigator works much like the Windows application switcher. It is not available from menus and
can be accessed only using shortcut keys. You can use either of two commands to access the IDE
Navigator (shown below) to cycle through files, depending on the order in which you want to cycle
through.

Window.PreviousDocumentWindowNavallows you to move to the file most recently accessed and


Window.NextDocumentWindowNav allows you to move in the reverse order. General Development Settings
assigns CTRL + SHIFT + TAB to Window.PreviousDocumentWindowNav and CTRL + TAB to
Window.NextDocumentWindowNav .

NOTE
If the settings combination you are using does not already have a shortcut key combination assigned to this command, you
can assign your own custom command using the Keyboard page of the Options dialog box. For more information, see
Identifying and Customizing Keyboard Shortcuts.

To switch to specific files in the editor


Press CTRL + TAB to display the IDE Navigator . Hold down the CTRL key and press TAB repeatedly until
you select the file you intend to switch to.

TIP
To reverse the order in which you go through the Active Files list, hold down the CTRL + SHIFT keys and press TAB.

- or -
In the upper right corner of the editor, choose the Active Files button, and then select a file from the list to
switch to.
- or -
On the menu bar, choose Window , Windows .
In the list, select the file you want to view and then choose Activate .

Navigating Among Tool Windows in the IDE


The IDE Navigator also lets you cycle through the tool windows you have open in the IDE. You can use either of
two commands to access the IDE Navigator to cycle through tool windows, depending on the order in which you
want to cycle through. Window.PreviousToolWindowNav allows you to move to the file most recently accessed and
Window.NextToolWindowNav allows you to move in the reverse order. General Development Settings assigns SHIFT +
ALT + F7 to Window.PreviousDocumentWindowNav and ALT + F7 to Window.NextDocumentWindowNav .
NOTE
If the settings combination you are using does not already have a shortcut key combination assigned to this command, you
can assign your own custom command using the Keyboard page of the Options dialog box. For more information, see
Identifying and Customizing Keyboard Shortcuts.

To switch to a specific tool window in the IDE


Press ALT+F7 to display the IDE Navigator . Hold down the ALT key and press F7 repeatedly until you select
the window you intend to switch to.

TIP
To reverse the order in which you go through the Active Tool Windows list, hold down the SHIFT + ALT keys and
press F7.

See Also
Customizing window layouts Default Keyboard Shortcuts
Finding and Using Visual Studio Extensions
10/18/2019 • 5 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version selector
at the top left. We recommend upgrading to Visual Studio 2019. Download it here

Visual Studio extensions are code packages that run inside Visual Studio and provide new or improved Visual
Studio features. You can find more information about Visual Studio extensions here: Visual Studio SDK.
You can use the Extensions and Updates dialog box to install Visual Studio extensions and samples from
websites and other locations, and then enable, disable, update, or uninstall them. (Tools / Extensions and
Updates , or type Extensions in the Quick Launch window). The dialog box also shows updates for installed
samples and extensions. You can also download extensions from websites, or get them from other developers.

NOTE
Starting in Visual Studio 2015, extensions hosted on the Visual Studio Gallery will be automatically updated. You can change
this setting through the Extensions and Updates dialog. See the section on Automatic Extension Updates below for
details.

Finding Visual Studio Extensions


You can install extensions from the Visual Studio Marketplace or the Sample Gallery on the Microsoft website.
Extensions may be controls, samples, templates, tools, or other components that add functionality to Visual Studio.
Visual Studio supports extensions in the VSIX package format—these include project templates, item templates,
Toolbox items, Managed Extension Framework (MEF) components, and VSPackages. You can also download and
install MSI-based extensions, but the Extensions and Updates dialog box can't enable or disable them. The
Visual Studio Gallery contains both VSIX and MSI extensions.

Installing or Uninstalling Visual Studio Extensions


In the Extensions and Updates , find the extension you want to install. (If you know the name or part of the name
of the extension, you can search in the Search Visual Studio Galler y window.) Click Download , then Install .
You must restart Visual Studio in order to load the extension.
If you try to install an extension that has dependencies, the installer verifies whether they're already installed. If
they aren't installed, the Extensions and Updates dialog box lists the dependencies that must be installed before
you can install the extension.
If you want to stop using an extension, you can either disable it or uninstall it. Disabling an extension keeps it
installed but unloaded. You can disable only VSIX extensions; extensions that were installed using an MSI can only
be uninstalled. Find the extension and click Uninstall or Disable . You must restart Visual Studio in order to unload
a disabled extension.

Per-User and Administrative Extensions


Most extensions are per-user extensions and are installed in the %LocalAppData%\Microsoft\VisualStudio\
<Visual Studio version>\Extensions\ folder. A few extensions are administrative extensions, and are installed
in the <Visual Studio installation folder>\Common7\IDE\Extensions\ folder.
To protect your system against extensions that may contain errors or malicious code, you can restrict per-user
extensions to load only when Visual Studio is run with normal user permissions. This means that per-user
extensions are disabled when Visual Studio is run with administrative user permissions. To do this, go to the
Extensions and Updates options page (Tools / Options , Environment , Extensions and Updates , or just type
Extension in the Quick Launch window). Clear the Load per user extensions when running as
administrator check box, then restart Visual Studio.

Automatic Extension Updates


Per-user extensions are automatically updated when a new version is available on the Visual Studio Gallery. The
new version of the extension is detected and installed in the background and on the next restart of Visual Studio,
the new version of the extension will be running.
Only per-user extensions can be automatically updated. Administrative extensions which are installed for all users
will not be updated and you still manually install new versions through the Extensions and Updates dialog
Updates node. You can see which extensions will be automatically updated in the extension’s details pane of
Extensions and Updates dialog.
If you wish to disable automatic updates, you can disable the feature for all extensions or only specific extensions.
To disable automatic updates for all extensions, click the Change your Extensions and Updates settings
link on the Extensions and Updates dialog and uncheck Automatically update extensions .
To disable automatic updates for a specific extension, uncheck the Automatically update this extension
option in the extension’s details pane on the right side of the Extensions and Updates dialog.

NOTE
Starting in Visual Studio 2015 Update 2, you can specify (in Tools / Options / Environment / Extensions and
Updates ) whether you want automatic updates for per-user extensions, all user extensions or both (the default setting).

Sample Master Copies and Working Copies


When you install an online sample, the solution is stored in two locations:
A working copy is stored in the location that you specified in the New Project dialog box.
A separate master copy is stored on your computer.
You can use the Extensions and Updates dialog box to perform these samples-related tasks:
List the master copies of samples that you have installed.
Disable or uninstall the master copy of a sample.
Install Sample Packs, which are collections of samples that relate to a technology or feature.
Install individual online samples. (You can also do this in the New Project dialog box.)
View update notifications when source code changes are published for installed samples.
Update the master copy of an installed sample when there is an update notification.

Installing Without Using the Extensions and Updates Dialog Box


Extensions that have been packaged in .vsix files may be available in locations other than the Visual Studio Gallery.
The Extensions and Updates dialog box can't detect these files, but you can install a .vsix file by double-clicking
the file, or selecting the file and pressing the ENTER key. After that, just follow the instructions. When the extension
is installed, you can use the Extensions and Updates dialog box to enable it, disable it, or uninstall it.

Extension Types Not Supported by the Extensions and Updates Dialog


Box
Visual Studio continues to support extensions that are installed by the Microsoft Installer (MSI) but not through the
Extensions and Updates dialog box without modification.

TIP
If an MSI-based extension includes an extension.vsixmanifest file, the extension will appear in the Extensions and Updates
dialog box.
Get Started Developing with Visual Studio
10/16/2020 • 2 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version
selector at the top left. We recommend upgrading to Visual Studio 2019. Download it here

Welcome to Visual Studio! After you have downloaded the product, these pages will help you get started coding.
Make web apps : Tools to create and deploy modern web applications.
Do a tutorial | Browse the docs | Watch a video
Make cross-platform mobile apps in HTML/Javascript (Apache Cordova) : Apache Cordova is an
open-source cross-platform environment that is based on HTML/CSS/Javascript. Your Javascript code
executes in a wrapper that targets a specific platform and enables access to all the hardware capabilities of
the device. Develop apps for the Apple Store, the Android store, and the Windows Store.
Load a sample | Do a tutorial | Browse the docs | Watch a video
Make cross-platform mobile apps in C# or Visual Basic (Xamarin) : Get started using Visual Studio
and Tools for Xamarin to create mobile apps that run on Android, iOS, and the Universal Windows Platform
from a shared code base.
Load a sample: TaskyPortable (native UI) or Xamarin Forms Todo sample (Xamarin.Forms shared UI) | Do a
tutorial | Browse the docs | Watch a video
Make native cross-platform apps and libraries in C++ Go here to get started creating C++ apps and
libraries that run on Android, iOS, and the Universal Windows Platform.
Load a sample | Do a tutorial | Browse the docs | Watch a video
Make games with DirectX : Get started creating Universal Windows Platform games using DirectX.
Load a sample | Do a tutorial | Browse the docs | Watch a video
Make games with Unity : Get started creating cross-platform games using Unity framework.
Load a sample | Do a tutorial | Browse the docs | Watch a video
Make Universal Windows Platform apps : Get started creating apps that run on the Universal Windows
Platform (XBox, PCs, tablets, Windows Phone, Surface Hub, and Internet of Things).
Load a sample | Do a tutorial | Browse the docs | Watch a video
Make desktop applications : Go here to get started creating traditional desktop applications that run on
Windows PCs.
Load a sample | Do a tutorial | Browse the docs
Make Office applications : Get started creating Office applications that extend and customize Word,
Excel, Outlook and PowerPoint with Office 365 services.
Load a sample | Do a tutorial | Browse the docs | Watch a video
Tour Visual Studio Team Ser vices and Team Foundation Ser ver Learn more about Visual Studio
Team Services and Team Foundation Server.

In this section
T IT L E DESC RIP T IO N

Getting Started with Visual C# and Visual Basic Writing JavaScript Code

Visual C++ for Cross-Platform Mobile Development Introduction to Functional Programming with F#

Getting Started with C++ Getting Started with Debugging in Visual Studio 2015
Getting Started with Visual C# and Visual Basic
10/18/2019 • 2 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version selector
at the top left. We recommend upgrading to Visual Studio 2019. Download it here

Whether you are new to Visual C# or Microsoft Visual Basic, this is the place to start. Getting Started Help is a
series of sequential lessons that introduces you to Visual C# and Visual Basic. Have fun, and write some great
software.
To learn about Visual C++, see Visual C++ resources.

In This Section
Walkthrough: Create a Simple Application Identify the basic windows in the Visual Studio IDE, optimize your
development experience by configuring a setting, and then build a simple program.
Tutorial 1: Create a Picture Viewer Build a program that loads a picture from a file and displays it in a window.
Learn how to drag controls like buttons and picture boxes on your form, set their properties, and use containers to
smoothly resize the form. Get started writing code.
Tutorial 2: Create a Timed Math Quiz Build a timed math quiz game, where the player must answer four random
arithmetic problems within a specified time. Learn how to generate random numbers using the Random class,
trigger events using a Timer control, control program flow using if else statements, and perform basic
arithmetic operations.
Tutorial 3: Create a Matching Game Build a matching game, where the player must match pairs of hidden icons.
Learn how to hold objects using a List object, use a foreach loop, keep track of a form's state using reference
variables, build an event handler that you can use with multiple objects, and make a timer fire exactly once when
started.
Walkthrough: Create a Simple Application with Visual
C# or Visual Basic
11/21/2019 • 12 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version
selector at the top left. We recommend upgrading to Visual Studio 2019. Download it here

By completing this walkthrough, you’ll become familiar with many of the tools, dialog boxes, and designers that
you can use when you develop applications with Visual Studio. You’ll create a simple “Hello, World”-style
application, design the UI, add code, and debug errors, while you learn more about working in the integrated
development environment (IDE).
This topic contains the following sections:
Configure the IDE
Create a simple application
Debug and test the application

NOTE
This walkthrough is based on Visual Studio Professional, which offers the WPF Application template on which you'll build the
project for this walkthrough. Visual Studio Express for Windows Desktop also offers that template, but Visual Studio Express
for Windows and Visual Studio Express for Web don't. For introductory information about how to use Visual Studio Express
for Windows, see the Developer Center for Windows Store apps. For introductory information about how to use Visual
Studio Express for Web, see Get Started with ASP.NET. In addition, your edition of Visual Studio and the settings that you use
determine the names and locations of some elements of the user interface. See Customizing Development Settings in Visual
Studio.

Configure the IDE


When you start Visual Studio for the first time, Visual Studio prompts you to sign in with a Microsoft Service
Account (MSA), Sign into Visual Studio. You do not need to sign in and can do that later.
On your Visual Studio launch, you next must choose a settings combination that applies a set of pre-defined
customizations to the IDE. Each settings combination has been designed to make it easier for you to develop
applications.
This walkthrough assume you applied General Development Settings , which applies the least amount of
customization to the IDE. If you have already chosen C# or Visual Basic (both are good choices), you don’t have to
change your settings. If you want to change your settings, you can use the Impor t and Expor t Settings Wizard .
See Customizing Development Settings in Visual Studio.
After you open Visual Studio, you can identify the tool windows, the menus and toolbars, and the main window
space. Tool windows are docked on the left and right sides of the application window, with Quick Launch , the
menu bar, and the standard toolbar at the top. In the center of the application window is the Star t Page . When
you load a solution or project, editors and designers appear in the space where the Star t Page is. When you
develop an application, you’ll spend most of your time in this central area.
Figure 2: Visual Studio IDE

You can make additional customizations to Visual Studio, such as changing the font face and size of the text in the
editor or the color theme of the IDE, by using the Options dialog box. Depending on the settings combination that
you’ve applied, some items in that dialog box might not appear automatically. You can make sure that all possible
options appear by choosing the Show all settings check box.
Figure 3: Options dialog box

In this example, you’ll change the color theme of the IDE from light to dark. You can skip ahead to create a project
if you like.
To change the color theme of the IDE
1. Open the Options dialog box by choosing the Tools menu at the top and then the Options … item.
2. Change the Color theme to Dark , then click OK .

The colors in Visual Studio should match the following image:

The color theme used for pictures in the rest of this walkthrough is the light theme. For more information
about customizing the IDE, see Customizing Development Settings in Visual Studio.

Create a simple application


Create the project
When you create an application in Visual Studio, you first create a project and a solution. For this example, you’ll
create a Windows Presentation Foundation (WPF) project.
To c r e a t e t h e W P F p r o j e c t

1. Create a new project. On the menu bar, choose File , New , Project… .

You can also type New Project in the Quick Launch box to do the same thing.

2. Choose the Visual Basic or the Visual C# WPF Application template by choosing in the left pane Installed ,
Templates , Visual C# , Windows , for example, and then choosing WPF Application in the middle pane.
Name the project HelloWPFApp at the bottom of the New Project dialog.

OR
Visual Studio creates the HelloWPFApp project and solution, and the Solution Explorer shows the various
files. The WPF Designer shows a design view and an XAML view of MainWindow.xaml in a split view. You
can slide the splitter to show more or less of either view. You can choose to see only the visual view or only
the XAML view. (For more information, see WPF Designer for Windows Forms Developers). The following
items appear in Solution Explorer :
Figure 5: Project items

After you create the project, you can customize it. By using the Proper ties window (found on the View
menu), you can display and change options for project items, controls, and other items in an application. By
using the project properties and property pages, you can display and change options for projects and
solutions.
To c h a n g e t h e n a m e o f M a i n W i n d o w .x a m l

1. In the following procedure, you’ll give MainWindow a more specific name. In Solution Explorer , select
MainWindow.xaml. You should see the Proper ties window, but if you don’t, choose the View menu and
the Proper ty Window item. Change the File Name property to Greetings.xaml .
Solution Explorer shows that the name of the file is now Greetings.xaml, and if you expand the
MainWindow.xaml node (by putting focus in the node and pressing the rightarrow key), you see the name
of MainWindow.xaml.vb or MainWindow.xaml.cs is now Greetings.xaml.vb or Greetings.xaml.cs. This code
file is nested under the .xaml file node to show they are very closely related to each other.

WARNING
This change causes an error that you will learn how to debug and fix in a later step.

2. In Solution Explorer , open Greetings.xaml in the Designer view (by pressing the Enter key while the node
has focus) and select the title bar of the window by using the mouse.
3. In the Proper ties window, change the value of the Title property to Greetings .
The title bar for MainWindow.xaml now reads Greetings.
Design the user interface (UI )
We will add three types of controls to this application: a TextBlock control, two RadioButton controls, and a Button
control.
To a d d a Te x t B l o c k c o n t r o l

1. Open the Toolbox window by choosing the View menu and the Toolbox item.
2. In the Toolbox , search for the TextBlock control.

3. Add a TextBlock control to the design surface by choosing the TextBlock item and dragging it to the window
on the design surface. Center the control near the top of the window.
Your window should resemble the following illustration:
Figure 7: Greetings window with TextBlock control
The XAML markup should look something like the following:

<TextBlock HorizontalAlignment="Center" TextWrapping="Wrap" VerticalAlignment="Center"


RenderTransformOrigin="4.08,2.312" Margin="237,57,221,238"><Run Text="TextBlock"/><InlineUIContainer>
<TextBlock TextWrapping="Wrap" Text="TextBlock"/>

To c u st o m i z e t h e t e x t i n t h e t e x t b l o c k

1. In the XAML view, locate the markup for TextBlock and change the Text attribute:
Text=”Select a message option and then choose the Display button.”

2. If the TextBlock does not expand to fit the In the Design view, enlarge the TextBlock control (using the grab
handles on the edges) so that it displays all the text.
3. Save your changes by pressing Ctrl-s or using the File menu item.
Next, you’ll add two RadioButton controls to the form.
To a d d r a d i o b u t t o n s

1. In the Toolbox , search for the RadioButton control.

2. Add two RadioButton controls to the design surface by choosing the RadioButton item and dragging it to
the window on the design surface twice, and move the buttons (by selecting them and using the arrow
keys) so that the buttons appear side by side under the TextBlock control.
Your window should look like this:
Figure 8: RadioButtons in the Greetings window.
3. In the Proper ties window for the left RadioButton control, change the Name property (the property at the
top of the Proper ties window) to RadioButton1 . Make sure you have selected the RadioButton and not the
background Grid on the form; the Type field of the Property Window under the Name field should say
RadioButton.
4. In the Proper ties window for the right RadioButton control, change the Name property to RadioButton2 ,
and then save your changes by pressing Ctrl-s or using the File menu item. Make sure you selected the
RadioButton before changing and saving.
You can now add display text for each RadioButton control. The following procedure updates the Content
property for a RadioButton control.
To a d d d i sp l a y t e x t fo r e a c h r a d i o b u t t o n

1. On the design surface, open the shortcut menu for RadioButton1 by pressing the right mouse button while
selecting RadioButton1, choose Edit Text , and then enter Hello .
2. Open the shortcut menu for RadioButton2 by pressing the right mouse button while selecting
RadioButton2, choose Edit Text , and then enter Goodbye .
The final UI element that you’ll add is a Button control.
To a d d t h e b u t t o n c o n t r o l

1. In the Toolbox , search for the Button control, and then add it to the design surface under the RadioButton
controls by selecting Button and dragging it to the form in the design view.
2. In the XAML view, change the value of Content for the Button control from Content=”Button” to
Content=”Display” , and then save the changes (Ctrl-s or use the File menu).

The markup should resemble the following example:


<Button Content="Display" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75"
Margin="215,204,0,0"/>

Your window should resemble the following illustration.


Figure 9: Final Greetings UI
Add code to the Display Button
When this application runs, a message box appears after a user first chooses a radio button and then chooses the
Display button. One message box will appear for Hello, and another will appear for Goodbye. To create this
behavior, you’ll add code to the Button_Click event in Greetings.xaml.vb or Greetings.xaml.cs.
A d d c o d e t o d i sp l a y m e ssa g e b o x e s

1. On the design surface, double-click the Display button.


Greetings.xaml.vb or Greetings.xaml.cs opens, with the cursor in the Button_Click event. You can also add a
click event handler as follows (if the pasted code has a red squiggle under any names, then you probably
did not select the RadioButton controls on the design surface and rename them):
For Visual Basic, the event handler should look like this:

Private Sub Button_Click_1(sender As Object, e As RoutedEventArgs)

End Sub

For Visual C#, the event handler should look like this:

private void Button_Click_1(object sender, RoutedEventArgs e)


{

2. For Visual Basic, enter the following code:

If RadioButton1.IsChecked = True Then


MessageBox.Show("Hello.")
Else RadioButton2.IsChecked = True
MessageBox.Show("Goodbye.")
End If

For Visual C#, enter the following code:


if (RadioButton1.IsChecked == true)
{
MessageBox.Show("Hello.");
}
else
{
RadioButton2.IsChecked = true;
MessageBox.Show("Goodbye.");
}

3. Save the application.

Debug and test the application


Next, you’ll debug the application to look for errors and test that both message boxes appear correctly. The
following instructions tell you how to build and launch the debugger, but later you might read Building a WPF
Application (WPF) and Debugging WPF for more information.
Find and fix errors
In this step, you’ll find the error that we caused earlier by changing the name of the main window XAML file.
To st a r t d e b u g g i n g a n d fi n d t h e e r r o r

1. Start the debugger by selecting Debug , then Star t Debugging .

A dialog box appears, indicating that an IOException has occurred: Cannot locate resource
‘mainwindow.xaml’.
2. Choose the OK button, and then stop the debugger.

We renamed Mainwindow.xaml to Greetings.xaml at the start of this walkthrough, but the code still refers to
Mainwindow.xaml as the startup URI for the application, so the project can't start.
To sp e c i fy G r e e t i n g s.x a m l a s t h e st a r t u p U R I

1. In Solution Explorer , open the App.xaml file (in the C# project) or the Application.xaml file (in the Visual
Basic project) in the XAML view (it cannot be opened in the Design view) by selecting the file and pressing
Enter or by double clicking it.
2. Change StartupUri="MainWindow.xaml" to StartupUri="Greetings.xaml" , and then save the changes with
Ctrl-s.
Start the debugger again (press F5). You should see the Greetings window of the application.
To debug with breakpoints
By adding some breakpoints, you can test the code during debugging. You can add breakpoints by choosing
Debug on the main menu, then Toggle Breakpoint or by clicking in the left margin of the editor next to the line
of code where you want the break to occur.
To a d d b r e a k p o i n t s

1. Open Greetings.xaml.vb or Greetings.xaml.cs, and select the following line: MessageBox.Show("Hello.")

2. Add a breakpoint from the menu by selecting Debug , then Toggle Breakpoint .

A red circle appears next to the line of code in the far left margin of the editor window.
3. Select the following line: MessageBox.Show("Goodbye.") .
4. Press the F9 key to add a breakpoint, and then press the F5 key to start debugging.
5. In the Greetings window, choose the Hello radio button, and then choose the Display button.
The line MessageBox.Show("Hello.") is highlighted in yellow. At the bottom of the IDE, the Autos, Locals, and
Watch windows are docked together on the left side, and the Call Stack, Breakpoints, Command, Immediate,
and Output windows are docked together on the right side.
6. On the menu bar, choose Debug , Step Out .
The application resumes execution, and a message box with the word “Hello” appears.
7. Choose the OK button on the message box to close it.
8. In the Greetings window, choose the Goodbye radio button, and then choose the Display button.
The line MessageBox.Show("Goodbye.") is highlighted in yellow.
9. Choose the F5 key to continue debugging. When the message box appears, choose the OK button on the
message box to close it.
10. Press the SHIFT + F5 keys (press shift first, and while holding it down, press F5) to stop debugging.
11. On the menu bar, choose Debug , Disable All Breakpoints .
Build a release version of the application
Now that you’ve verified that everything works, you can prepare a release build of the application.
To c l e a n t h e so l u t i o n fi l e s a n d b u i l d a r e l e a se v e r si o n

1. On the main menu, select Build , then Clean solution to delete intermediate files and output files that were
created during previous builds. This is not necessary, but it cleans up the debug build outputs.

2. Change the build configuration for HelloWPFApp from Debug to Release by using the dropdown control
on the toolbar (it says “Debug” currently).

3. Build the solution by choosing Build , then Build Solution or press the F6 key.

Congratulations on completing this walkthrough! You can find the .exe you built under your solution and
project directory (…\HelloWPFApp\HelloWPFApp\bin\Release\). If you want to explore more examples, see
Visual Studio Samples.

See Also
What's New in Visual Studio 2015 Get Started Developing with Visual Studio Productivity Tips
Tutorial 1: Create a Picture Viewer
1/10/2020 • 2 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version selector
at the top left. We recommend upgrading to Visual Studio 2019. Download it here

In this tutorial, you build a program that loads a picture from a file and displays it in a window. You learn how to
drag controls like buttons and picture boxes on your form, set their properties, and use containers to smoothly
resize the form. You also get started writing code. You learn how to:
Create a new project.
Test (debug) an application.
Add basic controls like check boxes and buttons to a form.
Position controls on a form using layouts.
Add Open File and Color dialog boxes to a form.
Write code using IntelliSense and code snippets.
Write event handler methods.
When you finish, your program will look like the following picture.

Picture that you create in


this tutorial
For a video version of this topic, see How Do I: Create a Picture Viewer in Visual Basic? or How Do I:
Create a Picture Viewer in C#?.
NOTE
These videos use an earlier version of Visual Studio, so there are slight differences in some menu commands and other user
interface elements. However, the concepts and procedures work similarly in the current version of Visual Studio. Visual C#
and Visual Basic are both covered in this tutorial, so focus on information specific to the programming language that you're
using.
To see code for Visual Basic, choose the VB tab at the top of code blocks, and to see code for Visual C#, choose the C# tab. If
you're interested in learning about Visual C++, see Getting Started and C++ Language Tutorial.
If you're interested in learning how to write Visual C# or Visual Basic apps for the Windows Store, see Create your first
Windows Store app using C# or Visual Basic. For information about creating JavaScript apps for the Windows Store, see
Create your first Windows Store app using JavaScript.

Related Topics
T IT L E DESC RIP T IO N

Step 1: Create a Windows Forms Application Project Begin by creating a Windows Forms application project.

Step 2: Run Your Program Run the Windows Forms application program that you created
in the previous step.

Step 3: Set Your Form Properties Change the way your form looks using the Proper ties
window.

Step 4: Lay Out Your Form with a TableLayoutPanel Control Add a TableLayoutPanel control to your form.

Step 5: Add Controls to Your Form Add controls, such as a PictureBox control and a
CheckBox control, to your form. Add buttons to your form.

Step 6: Name Your Button Controls Rename your buttons to something more meaningful.

Step 7: Add Dialog Components to Your Form Add an OpenFileDialog component and a ColorDialog
component to your form.

Step 8: Write Code for the Show a Picture Button Event Write code using the IntelliSense tool.
Handler

Step 9: Review, Comment, and Test Your Code Review and test your code. Add comments as needed.

Step 10: Write Code for Additional Buttons and a Check Box Write code to make other buttons and a check box work using
IntelliSense.

Step 11: Run Your Program and Try Other Features Run your program and set the background color. Try other
features, such as changing colors, fonts, and borders.
Step 1: Create a Windows Forms Application Project
1/10/2020 • 3 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version selector
at the top left. We recommend upgrading to Visual Studio 2019. Download it here

When you create a picture viewer, the first step is to create a Windows Forms Application project.
For a video version of this topic, see Tutorial 1: Create a Picture Viewer in Visual Basic - Video 1 or Tutorial 1:
Create a Picture Viewer in C# - Video 1. These videos use an earlier version of Visual Studio, so there are slight
differences in some menu commands and other user interface elements. However, the concepts and procedures
work similarly in the current version of Visual Studio.
To create a Windows Forms Application project
1. On the menu bar, choose File , New , Project . The dialog box should look like this.

New
project dialog box
2. Choose either Visual C# or Visual Basic in the Installed Templates list.
3. In the templates list, choose the Windows Forms Application icon. Name the new form PictureViewer ,
and then choose the OK button.
Visual Studio creates a solution for your program. A solution acts as a container for all of the projects and
files needed by your program. These terms will be explained in more detail later in this tutorial.
4. The following illustration shows what you should now see in the Visual Studio interface.
NOTE
Your window layout may not look exactly like this illustration. The precise window layout depends on the version of
Visual Studio, the programming language you are using, and other factors. However, you should verify that all three
windows appear.

IDE window
The interface contains three windows: a main window, Solution Explorer , and the Proper ties window.
If any of these windows are missing, restore the default window layout by, on the menu bar, choosing
Window , Reset Window Layout . You can also display windows by using menu commands. On the menu
bar, choose View , Proper ties Window or Solution Explorer . If any other windows are open, close them
by choosing the Close (x) button in their upper-right corners.
5. The illustration shows the following windows (going clockwise from the upper-left corner):
Main window In this window, you'll do most of your work, such as working with forms and editing
code. In the illustration, the window shows a form in the Form Editor. At the top of the window, the
Star t Page tab and the Form1.cs [Design] tab appear. (In Visual Basic, the tab name ends with .vb
instead of .cs.)
Solution Explorer window In this window, you can view and navigate to all items in your solution.
If you choose a file, the contents of the Proper ties window changes. If you open a code file (which
ends in .cs in Visual C# and .vb in Visual Basic), the code file or a designer for the code file appears. A
designer is a visual surface onto which you can add controls such as buttons and lists. For Visual
Studio forms, the designer is called the Windows Forms Designer.
Proper ties window In this window, you can change the properties of items that you choose in the
other windows. For example, if you choose Form1, you can change its title by setting the Text
property, and you can change the background color by setting the Backcolor property.

NOTE
The top line in Solution Explorer shows Solution 'PictureViewer' (1 project) , which means that Visual Studio
created a solution for you. A solution can contain more than one project, but for now, you'll work with solutions that
contain only one project.

6. On the menu bar, choose File , Save All .


As an alternative, choose the Save All button on the toolbar, which the following illustration shows.
Save All toolbar button
Visual Studio automatically fills in the folder name and the project name and then saves the project in your
projects folder.
To continue or review
To go to the next tutorial step, see Step 2: Run Your Program.
To return to the overview topic, see Tutorial 1: Create a Picture Viewer.
Step 2: Run Your Program
1/10/2020 • 2 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version
selector at the top left. We recommend upgrading to Visual Studio 2019. Download it here

When you created a new solution, you actually built a program that runs. It doesn't do much yet—it just displays
an empty window that shows Form1 in the title bar. But it does run, as you're about to find out.
For a video version of this topic, see Tutorial 1: Create a Picture Viewer in Visual Basic - Video 1 or Tutorial 1:
Create a Picture Viewer in C# - Video 1. These videos use an earlier version of Visual Studio, so there are slight
differences in some menu commands and other user interface elements. However, the concepts and procedures
work similarly in the current version of Visual Studio.
To run your program
1. Use one of the following methods to run your program.
Choose the F5 key.
On the menu bar, choose Debug , Star t Debugging .
On the toolbar, choose the Star t Debugging button, which appears as follows.
Start Debugging toolbar button
2. Visual Studio runs your program, and a window called Form1 appears. The following diagram shows the
program you just built. The program is running, and you will soon add to it.

Windows Form Application program running


3. Go back to the Visual Studio integrated development environment (IDE), and look at the new toolbar.
Additional buttons appear on the toolbar when you run a program. These buttons let you do things like stop
and start your program, and help you track down any errors (bugs) it may have. For this example, we're just
using it to start and stop the program.

Debugging toolbar
4. Use one of the following methods to stop your program.
On the toolbar, choose the Stop Debugging button.
On the menu bar, choose Debug , Stop Debugging .
Choose the X button in the upper corner of the Form1 window.
NOTE
When you run your program from inside the IDE, it's called debugging because you typically do it to locate and fix
bugs (errors) in the program. Although this program is small and doesn't really do anything yet, it's still a real
program. You follow the same procedure to run and debug other programs. To learn more about debugging, see
Debugger Basics.

To continue or review
To go to the next tutorial step, see Step 3: Set Your Form Properties.
To return to the previous tutorial step, see Step 1: Create a Windows Forms Application Project.
Step 3: Set Your Form Properties
1/10/2020 • 3 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version
selector at the top left. We recommend upgrading to Visual Studio 2019. Download it here

Next, you use the Proper ties window to change the way your form looks.
For a video version of this topic, see Tutorial 1: Create a Picture Viewer in Visual Basic - Video 1 or Tutorial 1:
Create a Picture Viewer in C# - Video 1. These videos use an earlier version of Visual Studio, so there are slight
differences in some menu commands and other user interface elements. However, the concepts and procedures
work similarly in the current version of Visual Studio.
To set your form properties
1. Be sure you're looking at Windows Forms Designer. In the Visual Studio integrated development
environment (IDE), choose the Form1.cs [Design] tab (or the Form1.vb [Design] tab in Visual Basic).
2. Choose anywhere inside the form Form1 to select it. Look at the Proper ties window, which should now be
showing the properties for the form. Forms have various properties. For example, you can set the
foreground and background color, title text that appears at the top of the form, size of the form, and other
properties.

NOTE
If the Proper ties window doesn't appear, stop your program by choosing the square Stop Debugging button on
the toolbar, or just close the window. If the program is stopped and you still don't see the Proper ties window, on
the menu bar, choose View , Proper ties Window .

3. After the form is selected, find the Text property in the Proper ties window. Depending on how the list is
sorted, you might need to scroll down. Choose Text , type Picture Viewer , and then choose ENTER. Your
form should now have the text Picture Viewer in its title bar, and the Proper ties window should look
similar to the following picture.

Properties window
NOTE
Properties can be ordered by a Categorized or Alphabetical view. You can switch between these two views by using
the buttons on the Proper ties window. In this tutorial, it's easier to find properties through the Alphabetical view.

4. Go back to Windows Forms Designer. Choose the form's lower-right drag handle, which is the small white
square in the lower-right of the form and appears as follows.

Drag handle
Drag the handle to resize the form so the form is wider and a bit taller.
5. Look at the Proper ties window, and notice that the Size property has changed. The Size property changes
each time you resize the form. Try dragging the form's handle to resize it to a form size of approximately
550, 350 (no need to be exact), which should work well for this project. As an alternative, you can enter the
values directly in the Size property and then choose the ENTER key.
6. Run your program again. Remember, you can use any of the following methods to run your program.
Choose the F5 key.
On the menu bar, choose Debug , Star t Debugging .
On the toolbar, choose the Star t Debugging button, which appears as follows.
Start Debugging toolbar button
Just like before, the IDE builds and runs your program, and a window appears.
7. Before going to the next step, stop your program, because the IDE won't let you change your program while
it's running. Remember, you can use any of the following methods to stop your program.
On the toolbar, choose the Stop Debugging button.
On the menu bar, choose Debug , Stop Debugging .
Choose the X button in the upper corner of the Form1 window.
To continue or review
To go to the next tutorial step, see Step 4: Lay Out Your Form with a TableLayoutPanel Control.
To return to the previous tutorial step, see Step 2: Run Your Program.
Step 4: Lay Out Your Form with a TableLayoutPanel
Control
1/10/2020 • 4 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version
selector at the top left. We recommend upgrading to Visual Studio 2019. Download it here

In this step, you add a TableLayoutPanel control to your form. The TableLayoutPanel helps properly align controls
in the form that you will add later.
For a video version of this topic, see Tutorial 1: Create a Picture Viewer in Visual Basic - Video 2 or Tutorial 1:
Create a Picture Viewer in C# - Video 2. These videos use an earlier version of Visual Studio, so there are slight
differences in some menu commands and other user interface elements. However, the concepts and procedures
work similarly in the current version of Visual Studio.
To lay out your form with a TableLayoutPanel control
1. On the left side of the Visual Studio IDE, locate the Toolbox tab. Choose the Toolbox tab, and the Toolbox
appears. (Or, on the menu bar, choose View , Toolbox .)
2. Choose the small triangle symbol next to the Containers group to open it, as shown in the following
picture.

Containers group
3. You can add controls like buttons, check boxes, and labels to your form. Double-click the TableLayoutPanel
control in the Toolbox. (Or, you can drag the control from the toolbox onto the form.) When you do this, the
IDE adds a TableLayoutPanel control to your form, as shown in the following picture.
TableLayoutPanel
control

NOTE
After you add your TableLayoutPanel, if a window appears inside your form with the title TableLayoutPanel Tasks ,
choose anywhere inside the form to close it. You will learn more about this window later in the tutorial.

Notice how the Toolbox expands to cover your form when you choose its tab, and closes after you choose
anywhere outside of it. That's the IDE auto-hide feature. You can turn it on or off for any of the windows by
choosing the pushpin icon in the upper-right corner of the window to toggle auto-hide and lock it in place.
The pushpin icon appears as follows.
Pushpin icon
4. Be sure TableLayoutPanel is selected by choosing it. You can verify what control is selected by looking at
the drop-down list at the top of the Proper ties window, as shown in the following picture.

Properties window showing TableLayoutPanel control


5. Choose the Alphabetical button on the toolbar in the Proper ties window. This causes the list of
properties in the Proper ties window to display in alphabetical order, which will make it easier to locate
properties in this tutorial.
6. The control selector is a drop-down list at the top of the Proper ties window. In this example, it shows that a
control called tableLayoutPanel1 is selected. You can select controls either by choosing an area in Windows
Forms Designer or by choosing from the control selector. Now that TableLayoutPanel is selected, find the
Dock property and choose Dock , which should be set to None . Notice that a drop-down arrow appears
next to the value. Choose the arrow, and then select the Fill button (the large button in the middle), as
shown in the following picture.
Properties window with Fill selected
Docking in Visual Studio refers to when a window is attached to another window or area in the IDE. For
example, the Properties window can be undocked – that is, unattached and free-floating within Visual
Studio – or it can be docked against Solution Explorer .
7. After you set the TableLayoutPanel Dock property to Fill , the panel fills the entire form. If you resize the
form again, the TableLayoutPanel stays docked, and resizes itself to fit.

NOTE
A TableLayoutPanel works like a table in Microsoft Office Word: It has rows and columns, and an individual cell can
span multiple rows and columns. Each cell can hold one control (like a button, a check box, or a label). Your
TableLayoutPanel will have a PictureBox control spanning its entire top row, a CheckBox control in its lower-left
cell, and four Button controls in its lower-right cell.

8. Currently, the TableLayoutPanel has two equal-size rows and two equal-size columns. You need to resize
them so the top row and right column are both much bigger. In Windows Forms Designer, select the
TableLayoutPanel. In the upper-right corner, there is a small black triangle button, which appears as follows.
Triangle button
This button indicates that the control has tasks that help you set its properties automatically.
9. Choose the triangle to display the control's task list, as shown in the following picture.

TableLayoutPanel tasks
10. Choose the Edit Rows and Columns task to display the Column and Row Styles window. Choose
Column1 , and set its size to 15 percent by being sure the Percent button is selected and entering 15 in
the Percent box. (That's a NumericUpDown control, which you will use in a later tutorial.) Choose Column2
and set it to 85 percent. Don't choose the OK button yet, because the window will close. (But if you do, you
can reopen it using the task list.)

TableLayoutPanel column and row styles


11. From the Show drop-down list at the top of the window, choose Rows . Set Row1 to 90 percent and Row2
to 10 percent.
12. Choose the OK button. Your TableLayoutPanel should now have a large top row, a small bottom row, a small
left column, and a large right column. You can resize the rows and columns in the TableLayoutPanel by
choosing tableLayoutPanel1 in the form and then dragging its row and column borders.

Form1 with resized


TableLayoutPanel
To continue or review
To go to the next tutorial step, see Step 5: Add Controls to Your Form.
To return to the previous tutorial step, see Step 3: Set Your Form Properties.
Step 5: Add Controls to Your Form
1/10/2020 • 6 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version
selector at the top left. We recommend upgrading to Visual Studio 2019. Download it here

In this step, you add controls, such as a PictureBox control and a CheckBox control, to your form. You then add
buttons to your form.
For a video version of this topic, see Tutorial 1: Create a Picture Viewer in Visual Basic - Video 2 or Tutorial 1:
Create a Picture Viewer in C# - Video 2. These videos use an earlier version of Visual Studio, so there are slight
differences in some menu commands and other user interface elements. However, the concepts and procedures
work similarly in the current version of Visual Studio.
To add controls to your form
1. Go to the Toolbox tab (located on the left side of the Visual Studio IDE) and expand the Common Controls
group. This shows the most common controls that you see on forms.
2. Choose the TableLayoutPanel control on the form. To verify that the TableLayoutPanel is selected, make sure
that its name appears in the dropdown list box at the top of the Proper ties window. You can also choose
form controls by using the dropdown list box at the top of the Proper ties window. Choosing a control this
way can often be easier than choosing a tiny control with a mouse.
3. Double-click the PictureBox item to add a PictureBox control to your form. Because the TableLayoutPanel is
docked to fill your form, the IDE adds the PictureBox control to the first empty cell (the upper left corner).
4. Choose the new PictureBox control to select it, and then choose the black triangle on the new PictureBox
control to display its task list, as shown in the following picture.

PictureBox tasks

NOTE
If you accidentally add the wrong type of control to your TableLayoutPanel, you can delete it. Right-click the control,
and then choose Delete on its context menu. You can also remove controls from the form by using the menu bar.
On the menu bar, choose Edit , Undo , or Edit , Delete .

5. Choose the Dock in parent container link. This automatically sets the PictureBox Dock property to Fill .
To see this, choose the PictureBox control to select it, go to the Proper ties window, and be sure that the
Dock property is set to Fill .
6. Make the PictureBox span both columns by changing its ColumnSpan property. Choose the PictureBox
control and set its ColumnSpan property to 2 . Also, when the PictureBox is empty, you want to show an
empty frame. Set its BorderStyle property to Fixed3D .
NOTE
If you don't see a ColumnSpan property for your PictureBox, then it's likely that the PictureBox was added to the
form rather than the TableLayoutPanel. To fix this, choose the PictureBox, delete it, choose the TableLayoutPanel, and
then add a new PictureBox.

7. Choose the TableLayoutPanel on the form and then add a CheckBox control to the form. Double-click the
CheckBox item in the Toolbox to add a new CheckBox control to the next free cell in your table. Because a
PictureBox takes up the first two cells in the TableLayoutPanel, the CheckBox control is added to the lower-
left cell. Choose the Text property and type in the word Stretch , as shown in the following picture.

TextBox control with Stretch property


8. Choose the TableLayoutPanel on the form, and then go to the Containers group in the Toolbox (where you
got your TableLayoutPanel control) and double-click the FlowLayoutPanel item to add a new control to the
last cell in the PictureBox (bottom right). Then dock the FlowLayoutPanel in the TableLayoutPanel (either by
choosing Dock in parent container on the FlowLayoutPanel's black triangle task list, or by setting the
FlowLayoutPanel's Dock property to Fill ).

NOTE
A FlowLayoutPanel is a container that arranges other controls in neat rows in order. When you resize a
FlowLayoutPanel, if it has room to lay out all of its controls in a single row, it does that. Otherwise, it arranges them
in lines, one on top of the other. You will use a FlowLayoutPanel to hold four buttons. If the buttons arrange one on
top another when added, be sure that the FlowLayoutPanel is selected before adding the buttons. Although it was
stated earlier that each cell can hold only one control, the lower-right cell of the TableLayoutPanel has four button
controls. This is because you can put a control in a cell that holds other controls. That kind of control is called a
container, and the FlowLayoutPanel is a container.

To add buttons
1. Choose the new FlowLayoutPanel that you added. Go to Common Controls in the Toolbox and double-
click the Button item to add a button control called button1 to your FlowLayoutPanel. Repeat to add
another button. The IDE determines that there's already a button called button1 and calls the next one
button2 .
2. Typically, you add the other buttons using the Toolbox. This time, choose button2 , and then on the menu
bar, choose Edit , Copy (or press Ctrl+C). On the menu bar, choose Edit , Paste (or press Ctrl+V) to paste a
copy of your button. Now paste it again. The IDE has now added button3 and button4 to the
FlowLayoutPanel.

NOTE
You can copy and paste any control. The IDE names and places the new controls in a logical manner. If you paste a
control into a container, the IDE chooses the next logical space for placement.
3. Choose the first button and set its Text property to Show a picture . Then set the Text properties of the
next three buttons to Clear the picture , Set the background color , and Close .
4. The next step is to size the buttons and arrange them so they align to the right side of the panel. Choose the
FlowLayoutPanel and look at its FlowDirection property. Change it so it's set to RightToLeft . As soon as
you do, the buttons should align themselves to the right side of the cell, and reverse their order so that the
Show a picture button is on the right.

NOTE
If the buttons are still in the wrong order, you can drag the buttons around the FlowLayoutPanel to rearrange them
in any order. You can choose a button and drag it left or right.

5. Choose the Close button to select it. Hold down the CTRL key and choose the other three buttons, so that
they are all selected. While all the buttons are selected, go to the Proper ties window and scroll up to the
AutoSize property. This property tells the button to automatically resize itself to fit all of its text. Set it to
true . Your buttons should now be sized properly and be in the right order. (As long as all four buttons are
selected, you can change all four AutoSize properties at the same time.) The following picture shows the
four buttons.

Picture Viewer with four


buttons
6. Now run your program again to see your newly laid out form. Choosing the buttons and the check box
doesn't do anything yet, but it will work soon.
To continue or review
To go to the next tutorial step, see Step 6: Name Your Button Controls.
To return to the previous tutorial step, see Step 4: Lay Out Your Form with a TableLayoutPanel Control.
Step 6: Name Your Button Controls
1/10/2020 • 5 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version
selector at the top left. We recommend upgrading to Visual Studio 2019. Download it here

There's only one PictureBox on your form. When you added it, the IDE automatically named it pictureBox1 .
There's only one CheckBox, which is named checkBox1 . Soon, you will write some code, and that code will refer to
the CheckBox and PictureBox. Because there's only one of each of these controls, you will know what it means
when you see pictureBox1 or checkBox1 in your code.

NOTE
In Visual Basic, the default first letter of any control name is initial cap, so the names are PictureBox1 , CheckBox1 , and so
on.

There are four buttons on your form, and the IDE named them button1 , button2 , button3 , and button4 . By just
looking at their current names, you don't know which button is the Close button and which one is the Show a
picture button. That's why giving your button controls more informative names is helpful.
For a video version of this topic, see Tutorial 1: Create a Picture Viewer in Visual Basic - Video 3 or Tutorial 1:
Create a Picture Viewer in C# - Video 3. These videos use an earlier version of Visual Studio, so there are slight
differences in some menu commands and other user interface elements. However, the concepts and procedures
work similarly in the current version of Visual Studio.
To name your button controls
1. On the form, choose the Close button. (If you still have all the buttons selected, choose the ESC key to
cancel the selection.) Scroll in the Proper ties window until you see the (Name) property. (The (Name)
property is near the top when the properties are alphabetical.) Change the name to closeButton , as shown
in the following picture.

Properties window with closeButton name


NOTE
If you try changing the name of your button to closeButton , with a space between the words close and Button, the
IDE displays an error message: "Property value is not valid." Spaces (and a few other characters) are not allowed in
control names.

2. Rename the other three buttons to backgroundButton , clearButton , and showButton . You can verify the
names by choosing the control selector drop-down list in the Proper ties window. The new button names
appear.
3. Double-click the Show a picture button on the form. As an alternative, choose the Show a picture button
on the form, and then choose the ENTER key. When you do, the IDE opens an additional tab in the main
window called Form1.cs (Form1.vb if you're using Visual Basic). This tab shows the code file behind the
form, as shown in the following picture.

Form1.cs tab
with Visual C# code
4. Focus on this part of the code. (Choose the VB tab below if you're using Visual Basic to view the Visual Basic
version of the code.)

private void showButton_Click(object sender, EventArgs e)


{
}

Private Sub showButton_Click() Handles showButton.Click

End Sub

You are looking at code called showButton_Click() . The IDE added this to the form's code when you opened
the code file for the showButton button. At design-time, when you open the code file for a control in a
form, code is generated for the control if it doesn't already exist. This code, known as a method, runs when
you run your program and choose the control - in this case, the Show a picture button.
NOTE
In this tutorial, the Visual Basic code that's automatically generated has been simplified by removing everything
between the parentheses, (). Whenever this occurs, you can remove the same code. Your program will work either
way. For the remainder of the tutorials, any automatically generated code is simplified whenever possible.

5. Choose the Windows Forms Designer tab again (Form1.cs [Design] in Visual C#, Form1.vb [Design] in
Visual Basic) and then open the code file for the Clear the picture button to create a method for it in the
form's code. Repeat this for the remaining two buttons. Each time, the IDE adds a new method to the form's
code file.
6. To add one more method, open the code file for the CheckBox control in Windows Forms Designer to make
the IDE add a checkBox1_CheckedChanged() method. That method is called whenever the user selects or
clears the check box.

NOTE
When working on a program, you often move between the code editor and Windows Forms Designer. The IDE
makes it easy to navigate in your project. Use Solution Explorer to open Windows Forms Designer by double-
clicking Form1.cs in Visual C# or Form1.vb in Visual Basic, or on the menu bar, choose View , Designer .

The following shows the new code that you see in the code editor.

private void clearButton_Click(object sender, EventArgs e)


{
}

private void backgroundButton_Click(object sender, EventArgs e)


{
}

private void closeButton_Click(object sender, EventArgs e)


{
}

private void checkBox1_CheckedChanged(object sender, EventArgs e)


{
}

Private Sub clearButton_Click() Handles clearButton.Click

End Sub

Private Sub backgroundButton_Click() Handles backgroundButton.Click

End Sub

Private Sub closeButton_Click() Handles closeButton.Click

End Sub

Private Sub CheckBox1_CheckedChanged() Handles CheckBox1.CheckedChanged

End Sub

The five methods that you added are called event handlers, because your program calls them whenever an
event (like a user choosing a button or selecting a box) happens.
When you view the code for a control in the IDE at design time, Visual Studio adds an event handler method
for the control if one isn't there. For example, when you double-click a button, the IDE adds an event handler
for its Click event (which is called whenever the user chooses the button). When you double-click a check
box, the IDE adds an event handler for its CheckedChanged event (which is called whenever the user selects
or clears the box).
After you add an event handler for a control, you can return to it at any time from Windows Forms Designer
by double-clicking the control, or on the menu bar, choosing View , Code .
Names are important when you build programs, and methods (including event handlers) can have any
name that you want. When you add an event handler with the IDE, it creates a name based on the control's
name and the event being handled. For example, the Click event for a button named showButton is called
the showButton_Click() event handler method. Also, opening and closing parentheses () are usually added
after the method name to indicate that methods are being discussed. If you decide you want to change a
code variable name, right-click the variable in the code and then choose Refactor , Rename . All instances of
that variable in the code are renamed. See Rename Refactoring (C#) or Refactoring and Rename Dialog Box
for more information.
To continue or review
To go to the next tutorial step, see Step 7: Add Dialog Components to Your Form.
To return to the previous tutorial step, see Step 5: Add Controls to Your Form.
Step 7: Add Dialog Components to Your Form
1/10/2020 • 2 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version
selector at the top left. We recommend upgrading to Visual Studio 2019. Download it here

To enable your program to open picture files and choose a background color, in this step, you add an
OpenFileDialog component and a ColorDialog component to your form.
A component is like a control in some ways. You use the Toolbox to add a component to your form, and you set its
properties using the Proper ties window. But unlike a control, adding a component to your form doesn't add a
visible item that the user can see on the form. Instead, it provides certain behaviors that you can trigger with code.
It's a component that opens an Open File dialog box.
For a video version of this topic, see Tutorial 1: Create a Picture Viewer in Visual Basic - Video 3 or Tutorial 1:
Create a Picture Viewer in C# - Video 3. These videos use an earlier version of Visual Studio, so there are slight
differences in some menu commands and other user interface elements. However, the concepts and procedures
work similarly in the current version of Visual Studio.
To add dialog components to your form
1. Choose the Windows Forms Designer (Form1.cs [Design] or Form1.vb [Design]) and then open the Dialogs
group in the Toolbox.

NOTE
The Dialogs group in the Toolbox has components that open many useful dialog boxes for you, which can be used
for opening and saving files, browsing folders, and choosing fonts and colors. You use two dialog components in this
project: OpenFileDialog and ColorDialog .

2. To add a component called openFileDialog1 to your form, double-click OpenFileDialog . To add a


component called colorDialog1 to your form, double-click ColorDialog in the Toolbox. (You use that one
in the next tutorial step.) You should see an area at the bottom of Windows Forms Designer (beneath the
Picture Viewer form) that has an icon for each of the two dialog components that you added, as shown in
the following picture.

Dialog components
3. Choose the openFileDialog1 icon in the area at the bottom of the Windows Forms Designer. Set two
properties:
Set the Filter property to the following (you can copy and paste it):

JPEG Files (*.jpg)|*.jpg|PNG Files (*.png)|*.png|BMP Files (*.bmp)|*.bmp|All files (*.*)|*.*

Set the Title property to the following: Select a picture file


The Filter property settings specify the kinds of file types that will display in the Select a picture
file dialog box.
NOTE
To see an example of the Open File dialog box in a different application, open Notepad or Paint, and on the menu
bar, choose File , Open . Notice how there's a Files of type drop-down list at the bottom. You just used the Filter
property in the OpenFileDialog component to set that up. Also, notice how the Title and Filter properties are
bold in the Proper ties window. The IDE does that to show you any properties that have been changed from their
default values.

To continue or review
To go to the next tutorial step, see Step 8: Write Code for the Show a Picture Button Event Handler.
To return to the previous tutorial step, see Step 6: Name Your Button Controls.
Step 8: Write Code for the Show a Picture Button
Event Handler
1/10/2020 • 5 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version
selector at the top left. We recommend upgrading to Visual Studio 2019. Download it here

In this step, you make the Show a picture button work like this:
When a user chooses that button, the program opens an Open File dialog box.
If a user opens a picture file, the program shows that picture in the PictureBox.
The IDE has a powerful tool called IntelliSense that helps you write code. As you enter code, the IDE opens a
box with suggested completions for partial words that you enter. It tries to determine what you want to do
next, and automatically jumps to the last item you choose from the list. You can use the up or down arrows
to move in the list, or you can keep typing letters to narrow the choices. When you see the choice you want,
choose the TAB key to select it. Or, you can ignore the suggestions, if not needed.
For a video version of this topic, see Tutorial 1: Create a Picture Viewer in Visual Basic - Video 4 or
Tutorial 1: Create a Picture Viewer in C# - Video 4. These videos use an earlier version of Visual Studio, so
there are slight differences in some menu commands and other user interface elements. However, the
concepts and procedures work similarly in the current version of Visual Studio.
To write code for the Show a picture button event handler
1. Go to Windows Forms Designer and double-click the Show a picture button. The IDE immediately goes to
the code designer and moves your cursor so it's inside the showButton_Click() method that you added
previously.
2. Type an i on the empty line between the two braces { }. (In Visual Basic, type on the empty line between
Private Sub… and End Sub.) An IntelliSense window opens, as shown in the following picture.

IntelliSense with Visual C# code


3. The IntelliSense window should be highlighting the word if . (If not, enter a lowercase f , and it will.)
Notice how a little tooltip box next to the IntelliSense window appears with the description, Code snippet
for if statement . (In Visual Basic, the tooltip also states that this is a snippet, but with slightly different
wording.) You want to use that snippet, so choose the TAB key to insert if into your code. Then choose the
TAB key again to use the if snippet. (If you chose somewhere else and your IntelliSense window
disappeared, backspace over the i and retype it, and the IntelliSense window opens again.)

Visual C# code
4. Next, you use IntelliSense to enter more code to open an Open File dialog box. If the user chose the OK
button, the PictureBox loads the file that the user selected. The following steps show how to enter the code,
and although it's numerous steps, it's just a few keystrokes:
a. Start with the selected text true in the snippet. Type op to overwrite it. (In Visual Basic, you start
with an initial cap, so type Op .)
b. The IntelliSense window opens and displays openFileDialog1 . Choose the TAB key to select it. (In
Visual Basic, it starts with an initial cap, so you see OpenFileDialog1 . Ensure that
OpenFileDialog1 is selected.)
To learn more about OpenFileDialog , see OpenFileDialog.
c. Type a period ( . ) (Many programmers call this a dot.) Because you typed a dot right after
openFileDialog1 , an IntelliSense window opens, filled in with all of the OpenFileDialog
component's properties and methods. These are the same properties that appear in the Proper ties
window when you choose it in Windows Forms Designer. You can also choose methods that tell the
component to do things (like open a dialog box).

NOTE
The IntelliSense window can show you both properties and methods. To determine what is being shown,
look at the icon on the left side of each item in the IntelliSense window. You see a picture of a block next to
each method, and a picture of a wrench (or spanner) next to each property. There's also a lightning bolt icon
next to each event. These pictures display as follows.

Method icon
Property icon
Event icon
d. Start to type ShowDialog (capitalization is unimportant to IntelliSense). The ShowDialog() method
will show the Open File dialog box. After the window has highlighted ShowDialog , choose the TAB
key. You can also highlight “ShowDialog” and choose the F1 key to get help for it.
To learn more about the ShowDialog() method, see ShowDialog Method.
e. When you use a method on a control or a component (referred to as calling a method), you need to
add parentheses. So enter opening and closing parentheses immediately after the "g" in ShowDialog :
() It should now look like "openFileDialog1.ShowDialog()".
NOTE
Methods are an important part of any program, and this tutorial has shown several ways to use methods.
You can call a component's method to tell it to do something, like how you called the OpenFileDialog
component's ShowDialog() method. You can create your own methods to make your program do things,
like the one you're building now, called the showButton_Click() method, which opens a dialog box and a
picture when a user chooses a button.

f. For Visual C#, add a space, and then add two equal signs ( == ). For Visual Basic, add a space, and
then use a single equal sign ( = ). (Visual C# and Visual Basic use different equality operators.)
g. Add another space. As soon as you do, another IntelliSense window opens. Start to type
DialogResult and choose the TAB key to add it.

NOTE
When you write code to call a method, sometimes it returns a value. In this case, the OpenFileDialog
component's ShowDialog() method returns a DialogResult value. DialogResult is a special value that tells
you what happened in a dialog box. An OpenFileDialog component can result in the user choosing OK or
Cancel, so its ShowDialog() method returns either DialogResult.OK or DialogResult.Cancel.

h. Type a dot to open the DialogResult value IntelliSense window. Enter the letter O and choose the
TAB key to insert OK .
To learn more about DialogResult , see DialogResult.

NOTE
The first line of code should be complete. For Visual C#, it should be the following.
if (openFileDialog1.ShowDialog() == DialogResult.OK)

For Visual Basic, it should be the following.


If OpenFileDialog1.ShowDialog() = DialogResult.OK Then

i. Now add one more line of code. You can type it (or copy and paste it), but consider using IntelliSense
to add it. The more familiar you are with IntelliSense, the more quickly you can write your own code.
Your final showButton_Click() method looks like the following. (Choose the VB tab to view the Visual
Basic version of the code.)

private void showButton_Click(object sender, EventArgs e)


{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
pictureBox1.Load(openFileDialog1.FileName);
}
}

Private Sub showButton_Click() Handles showButton.Click


If OpenFileDialog1.ShowDialog() = DialogResult.OK Then
PictureBox1.Load(OpenFileDialog1.FileName)
End If

End Sub
To continue or review
To go to the next tutorial step, see Step 9: Review, Comment, and Test Your Code.
To return to the previous tutorial step, see Step 7: Add Dialog Components to Your Form.
Step 9: Review, Comment, and Test Your Code
1/10/2020 • 5 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version
selector at the top left. We recommend upgrading to Visual Studio 2019. Download it here

You next add a comment to your code. A comment is a note that doesn't change the way the program behaves. It
makes it easier for someone who is reading your code to understand what it does. Adding comments to your code
is a good habit to get into. In Visual C#, two forward slashes (//) mark a line as a comment. In Visual Basic, a single
quotation mark (') is used to mark a line as a comment. After you add a comment, you test your program. It's good
practice to run and test your code frequently while you're working on your projects, so you can catch and fix any
problems early, before the code gets more complicated. This is called iterative testing.
You just built something that works, and although it's not done yet, it can already load a picture. Before you add a
comment to your code and test it, take time to review the code concepts, because you will use these concepts
frequently:
When you double-clicked the Show a picture button in Windows Forms Designer, the IDE automatically
added a method to your program's code.
Methods are how you organize your code: It's how your code is grouped together.
Most of the time, a method does a small number of things in a specific order, like how your
showButton_Click() method shows a dialog box and then loads a picture.

A method is made up of code statements, or lines of code. Think of a method as a way to bundle code
statements together.
When a method is executed, or called, the statements in the method are executed in order, one after another,
starting with the first one.
The following is an example of a statement.

pictureBox1.Load(openFileDialog1.FileName);

pictureBox1.Load(openFileDialog1.FileName)

Statements are what make your programs do things. In Visual C#, a statement always ends in a semicolon.
In Visual Basic, the end of a line is the end of a statement. (No semicolon is needed in Visual Basic.) The
preceding statement tells your PictureBox control to load the file that the user selected with the
OpenFileDialog component.
For a video version of this topic, see Tutorial 1: Create a Picture Viewer in Visual Basic - Video 5 or
Tutorial 1: Create a Picture Viewer in C# - Video 5. These videos use an earlier version of Visual Studio, so
there are slight differences in some menu commands and other user interface elements. However, the
concepts and procedures work similarly in the current version of Visual Studio.
To add comments
1. Add the following comment to your code.

private void showButton_Click(object sender, EventArgs e)


{
// Show the Open File dialog. If the user clicks OK, load the
// picture that the user chose.
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
pictureBox1.Load(openFileDialog1.FileName);
}
}

Private Sub showButton_Click() Handles showButton.Click

' Show the Open File dialog. If the user clicks OK, load the
' picture that the user chose.
If OpenFileDialog1.ShowDialog() = DialogResult.OK Then
PictureBox1.Load(OpenFileDialog1.FileName)
End If

End Sub

NOTE
Your showButton button's Click event handler is now finished, and it works. You have started writing code, starting
with an if statement. An if statement is how you tell your program, "Check this one thing, and if it's true, do
these actions." In this case, you tell your program to open the Open File dialog box, and if the user selects a file and
chooses the OK button, load that file in the PictureBox.

TIP
The IDE is built to make it easy for you to write code, and code snippets are one way it does that. A snippet is a
shortcut that gets expanded into a small block of code.
You can see all of the snippets available. On the menu bar, choose Tools , Code Snippets Manager . For Visual C#,
the if snippet is in Visual C# . For Visual Basic, the if snippets are in Conditionals and Loops , Code
Patterns . You can use this manager to browse existing snippets or add your own snippets.
To activate a snippet when typing code, type it and choose the TAB key. Many snippets appear in the IntelliSense
window, which is why you choose the TAB key twice: first to select the snippet from the IntelliSense window, and
then to tell the IDE to use the snippet. (IntelliSense supports the if snippet, but not the ifelse snippet.)

2. Before you run your program, save your program by choosing the Save All toolbar button, which appears
as follows.
Save All button
Alternatively, to save your program, on the menu bar, choose File , Save All . It's a best practice to save early
and often.
When it's running, your program should look like the following picture.
Picture Viewer
To test your program
1. Choose the F5 key or choose the Star t Debugging toolbar button.
2. Choose the Show a picture button to run the code you just wrote. First, the program opens an Open File
dialog box. Verify that your filters appear in the Files of type drop-down list at the bottom of the dialog
box. Then navigate to a picture and open it. You can usually find sample pictures that ship with the Windows
operating system in your My Documents folder, inside the My Pictures\Sample Pictures folder.

NOTE
If you don't see any images in the Select a picture file dialog box, be sure that the "All files (*.*)" filter is selected in
the drop-down list on the lower right side of the dialog box.

3. Load a picture, and it appears in your PictureBox. Then try resizing your form by dragging its borders.
Because you have your PictureBox docked inside a TableLayoutPanel, which itself is docked inside the form,
your picture area will resize itself so that it's as wide as the form, and fills the top 90 percent of the form.
That's why you used the TableLayoutPanel and FlowLayoutPanel containers: They keep your form sized
correctly when the user resizes it.
Right now, larger pictures go beyond the borders of your picture viewer. In the next step, you'll add code to
make pictures fit in the window.
To continue or review
To go to the next tutorial step, see Step 10: Write Code for Additional Buttons and a Check Box.
To return to the previous tutorial step, see Step 8: Write Code for the Show a Picture Button Event Handler.
Step 10: Write Code for Additional Buttons and a
Check Box
1/10/2020 • 2 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version
selector at the top left. We recommend upgrading to Visual Studio 2019. Download it here

Now you're ready to complete the other four methods. You could copy and paste this code, but if you want to learn
the most from this tutorial, type the code and use IntelliSense.
This code adds functionality to the buttons you added earlier. Without this code, the buttons don't do anything. The
buttons use code in their Click events (and the check box uses the CheckChanged event) to do different things
when you activate the controls. For example, the clearButton_Click event, which activates when you choose the
Clear the picture button, erases the current image by setting its Image property to null (or, nothing ). Each
event in the code includes comments that explain what the code does.
For a video version of this topic, see Tutorial 1: Create a Picture Viewer in Visual Basic - Video 5 or Tutorial 1:
Create a Picture Viewer in C# - Video 5. These videos use an earlier version of Visual Studio, so there are slight
differences in some menu commands and other user interface elements. However, the concepts and procedures
work similarly in the current version of Visual Studio.

NOTE
As a best practice: Always comment your code. Comments are information for a person to read, and it's worth the time to
make your code understandable. Everything on a comment line is ignored by the program. In Visual C#, you comment a line
by typing two forward slashes at the beginning (//), and in Visual Basic you comment a line by starting with a single
quotation mark (').

To write code for additional buttons and a check box


Add the following code to your Form1 code file (Form1.cs or Form1.vb). Choose the VB tab to view Visual
Basic code.
private void clearButton_Click(object sender, EventArgs e)
{
// Clear the picture.
pictureBox1.Image = null;
}

private void backgroundButton_Click(object sender, EventArgs e)


{
// Show the color dialog box. If the user clicks OK, change the
// PictureBox control's background to the color the user chose.
if (colorDialog1.ShowDialog() == DialogResult.OK)
pictureBox1.BackColor = colorDialog1.Color;
}

private void closeButton_Click(object sender, EventArgs e)


{
// Close the form.
this.Close();
}

private void checkBox1_CheckedChanged(object sender, EventArgs e)


{
// If the user selects the Stretch check box,
// change the PictureBox's
// SizeMode property to "Stretch". If the user clears
// the check box, change it to "Normal".
if (checkBox1.Checked)
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
else
pictureBox1.SizeMode = PictureBoxSizeMode.Normal;
}

Private Sub clearButton_Click() Handles clearButton.Click


' Clear the picture.
PictureBox1.Image = Nothing
End Sub

Private Sub backgroundButton_Click() Handles backgroundButton.Click


' Show the color dialog box. If the user clicks OK, change the
' PictureBox control's background to the color the user chose.
If ColorDialog1.ShowDialog() = DialogResult.OK Then
PictureBox1.BackColor = ColorDialog1.Color
End If
End Sub

Private Sub closeButton_Click() Handles closeButton.Click


' Close the form.
Close()
End Sub

Private Sub CheckBox1_CheckedChanged() Handles CheckBox1.CheckedChanged


' If the user selects the Stretch check box, change
' the PictureBox's SizeMode property to "Stretch". If the user
' clears the check box, change it to "Normal".
If CheckBox1.Checked Then
PictureBox1.SizeMode = PictureBoxSizeMode.StretchImage
Else
PictureBox1.SizeMode = PictureBoxSizeMode.Normal
End If
End Sub

To continue or review
To go to the next tutorial step, see Step 11: Run Your Program and Try Other Features.
To return to the previous tutorial step, see Step 9: Review, Comment, and Test Your Code.
Step 11: Run Your Program and Try Other Features
1/10/2020 • 2 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version selector
at the top left. We recommend upgrading to Visual Studio 2019. Download it here

Your program is finished and ready to run. You can run your program and set the background color of the
PictureBox. To learn more, try to improve the program by changing the color of the form, customizing the buttons
and check box, and changing the properties of the form.
For a video version of this topic, see Tutorial 1: Create a Picture Viewer in Visual Basic - Video 5 or Tutorial 1:
Create a Picture Viewer in C# - Video 5. These videos use an earlier version of Visual Studio, so there are slight
differences in some menu commands and other user interface elements. However, the concepts and procedures
work similarly in the current version of Visual Studio.
To run your program and set the background color
1. Choose F5, or on the menu bar, choose Debug , Star t Debugging .
2. Before you open a picture, choose the Set the background color button. The Color dialog box opens.

Color dialog box


3. Choose a color to set the PictureBox background color. Look closely at the backgroundButton_Click()
method to understand how it works.

NOTE
You can load a picture from the Internet by pasting its URL into the Open File dialog box. Try to find an image with
a transparent background, so your background color shows.

4. Choose the Clear the picture button to make sure it clears. Then, exit the program by choosing the Close
button.
To try other features
Change the color of the form and the buttons by using the BackColor property.
Customize your buttons and check box using the Font and ForeColor properties.
Change your form's FormBorderStyle and ControlBox properties.
Use your form's AcceptButton and CancelButton properties so that buttons are automatically chosen
when the user chooses the ENTER or ESC key. Make the program open the Open File dialog box when the
user chooses ENTER and close the box when the user chooses ESC.
To continue or review
To learn more about programming in Visual Studio, see Programming Concepts.
To learn more about Visual Basic, see Developing Applications with Visual Basic.
To learn more about Visual C#, see Introduction to the C# Language and the .NET Framework.
To go to the next tutorial, see Tutorial 2: Create a Timed Math Quiz.
To return to the previous tutorial step, see Step 10: Write Code for Additional Buttons and a Check Box.
Tutorial 2: Create a Timed Math Quiz
11/21/2019 • 2 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version
selector at the top left. We recommend upgrading to Visual Studio 2019. Download it here

In this tutorial, you build a quiz in which the quiz taker must answer four random arithmetic problems within a
specified time. You learn how to:
Generate random numbers by using the Random class.
Trigger events to occur at a specific time by using a Timer control.
Control program flow by using if else statements.
Perform basic arithmetic operations in code.
When you finish, your quiz will look like the following picture, except with different numbers.

Quiz that you create in this tutorial

NOTE
This tutorial covers both Visual C# and Visual Basic, so focus on the information that's specific to the programming
language that you're using.

Related Topics
T IT L E DESC RIP T IO N

Step 1: Create a Project and Add Labels to Your Form Start by creating the project, changing properties, and adding
Label controls.

Step 2: Create a Random Addition Problem Create an addition problem, and use the Random class to
generate random numbers.

Step 3: Add a Countdown Timer Add a countdown timer so that the quiz can be timed.
T IT L E DESC RIP T IO N

Step 4: Add the CheckTheAnswer() Method Add a method to check whether the quiz taker entered a
correct answer for the problem.

Step 5: Add Enter Event Handlers for the NumericUpDown Add event handlers that make your quiz easier to take.
Controls

Step 6: Add a Subtraction Problem Add a subtraction problem that generates random numbers,
uses the timer, and checks for correct answers.

Step 7: Add Multiplication and Division Problems Add multiplication and division problems that generate
random numbers, use the timer, and check for correct
answers.

Step 8: Customize the Quiz Try other features, such as changing colors and adding a hint.
Step 1: Create a Project and Add Labels to Your Form
10/18/2019 • 5 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version selector
at the top left. We recommend upgrading to Visual Studio 2019. Download it here

As the first steps in developing this quiz, you create the project, and you add labels, a button, and other controls to
a form. You also set properties for each control that you add. The project will contain the form, the controls, and
(later in the tutorial) code. The button starts the quiz, the labels show the quiz problems, and the other controls
show the quiz answers and the time that remains to finish the quiz.

NOTE
This topic is part of a tutorial series about basic coding concepts. For an overview of the tutorial, see Tutorial 2: Create a
Timed Math Quiz.

To create a project and set properties for a form


1. On the menu bar, choose File , New , Project .
2. In the Installed Templates list, choose either C# or Visual Basic .
3. In the list of templates, choose the Windows Forms Application template, name it Math Quiz , and then
choose the OK button.
A form that's named Form1.cs or Form1.vb appears, depending on the programming language that you
chose.
4. Choose the form, and then change its Text property to Math Quiz .
The Proper ties window contains properties for the form.
5. Change the size of the form to 500 pixels wide by 400 pixels tall.
You can resize the form by dragging its edges until the correct size appears in the lower-left corner of the
integrated development environment (IDE). As an alternative, you can change the values of the Size
property.
6. Change the value of the FormBorderStyle property to Fixed3D , and set the MaximizeBox property to
False .
These values prevent quiz takers from resizing the form.
To create the Time Remaining box
1. Add a Label control from the Toolbox, and then set the value of its (Name) property to timeLabel .
This label will become a box in the upper-right corner that shows the number of seconds that remain in the
quiz.
2. Change the AutoSize property to False so that you can resize the box.
3. Change the BorderStyle property to FixedSingle to draw a line around the box.
4. Set the Size property to 200, 30 .
5. Move the label to the upper-right corner of the form, where blue spacer lines will appear.
These lines help you align controls on the form.
6. In the Proper ties window, choose the Text property, and then choose the Backspace key to clear its value.
7. Choose the plus sign (+) next to the Font property, and then change the value of the Size property to
15.75 .
You can change several font properties, as the following picture shows.

Properties window showing font size


8. Add another Label control from the Toolbox, and then set its font size to 15.75 .
9. Set the Text property to Time Left .
10. Move the label so that it lines up just to the left of the timeLabel label.
To add controls for the addition problems
1. Add a Label control from the Toolbox, and then set its Text property to ? (question mark).
2. Set the AutoSize property to False .
3. Set the Size property to 60, 50 .
4. Set the font size to 18 .
5. Set the TextAlign property to MiddleCenter .
6. Set the Location property to 50, 75 to position the control on the form.
7. Set the (Name) property to plusLeftLabel .
8. Choose the plusLeftLabel label, and then choose either the Ctrl+C keys or Copy on the Edit menu.
9. Paste the label three times by choosing either the Ctrl+V keys or Paste on the Edit menu.
10. Arrange the three new labels so that they are in a row to the right of the plusLeftLabel label.
You can use the spacer lines to space them out and line them up.
11. Set the value of the second label's Text property to + (plus sign).
12. Set the value of the third label's (Name) property to plusRightLabel .
13. Set the value of the fourth label's Text property to = (equal sign).
14. Add a NumericUpDown control from the Toolbox, set its font size to 18 , and set its width to 100 .
You'll learn more about this kind of control later.
15. Line up the NumericUpDown control with the label controls for the addition problem.
16. Change the value of the (Name) property for the NumericUpDown control to sum .
You've created the first row, as the following picture shows.

First row of math quiz


To add controls for the subtraction, multiplication, and division problems
1. Copy all five controls for the addition problem (the four Label controls and the NumericUpDown control),
and then paste them.
The form contains five new controls, which are still selected.
2. Move all of the controls into place so that they line up below the addition controls.
You can use the spacer lines to give enough distance between the two rows.
3. Change the value of the Text property for the second label to – (minus sign).
4. Name the first question-mark label minusLeftLabel .
5. Name the second question-mark label minusRightLabel .
6. Name the NumericUpDown control difference .
7. Paste the five controls two more times.
8. For the third row, name the first label timesLeftLabel , change the second label's Text property to ×
(multiplication sign), name the third label timesRightLabel , and name the NumericUpDown control
product .
9. For the fourth row, name the first label dividedLeftLabel , change the second label's Text property to ÷
(division sign), name the third label dividedRightLabel , and name the NumericUpDown control quotient .

NOTE
You can copy the multiplication sign × and the division sign ÷ from this tutorial and paste them onto the form.

To add a start button and set the tab-index order


1. Add a Button control from the Toolbox, and then set its (Name) property to star tButton .
2. Set the Text property to Star t the quiz .
3. Set the font size to 14 .
4. Set the AutoSize property to True , which causes the button to automatically resize to fit the text.
5. Center the button near the bottom of the form.
6. Set the value of the TabIndex property for the star tButton control to 1 .
NOTE
The TabIndex property sets the order of the controls when the quiz taker chooses the Tab key. To see how it works,
open any dialog box (for example, on the menu bar, choose File , Open ), and then choose the Tab key a few times.
Watch how your cursor moves from control to control each time that you choose the Tab key. A programmer decided
the order when creating that form.

7. Set the value of the TabIndex property for the NumericUpDown sum control to 2 , for the difference control
to 3 , for the product control to 4 , and for the quotient control to 5 .
The form should look like the following illustration.

Initial math quiz form


8. To verify whether the TabIndex property works as you expect, save and run your program by choosing the
F5 key, or by choosing Debug , Star t Debugging on the menu bar, and then choose the Tab key a few
times.
To continue or review
To go to the next tutorial step, see Step 2: Create a Random Addition Problem.
To return to the overview topic, see Tutorial 2: Create a Timed Math Quiz.
Step 2: Create a Random Addition Problem
10/18/2019 • 6 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version
selector at the top left. We recommend upgrading to Visual Studio 2019. Download it here

In the second part of this tutorial, you make the quiz challenging by adding math problems that are based on
random numbers. You also create a method that's named StartTheQuiz() and that fills in the problems and starts
the countdown timer. Later in this tutorial, you'll add the subtraction, multiplication, and division problems.

NOTE
This topic is part of a tutorial series about basic coding concepts. For an overview of the tutorial, see Tutorial 2: Create a
Timed Math Quiz.

To create a random addition problem


1. In the form designer, choose the form (Form1).
2. On the menu bar, choose View , Code .
Form1.cs or Form1.vb appears, depending on the programming language that you're using, so that you can
view the code behind the form.
3. Create a Random object by adding a new statement near the top of the code, like the following.

public partial class Form1 : Form


{
// Create a Random object called randomizer
// to generate random numbers.
Random randomizer = new Random();

Public Class Form1

' Create a Random object called randomizer


' to generate random numbers.
Private randomizer As New Random

You've added a Random object to your form and named the object randomizer .
Random is known as an object. You've probably heard that word before, and you learn more about what it
means for programming in the next tutorial. For now, just remember that you can use new statements to
create buttons, labels, panels, OpenFileDialogs, ColorDialogs, SoundPlayers, Randoms, and even forms, and
those items are referred to as objects. When you run your program, the form is started, and the code
behind it creates a Random object and names it randomizer .
Soon you'll build a method to check the answers, so your quiz must use variables to store the random
numbers that it generates for each problem. See Variables or Types. To properly use variables, you must
declare them, which means listing their names and data types.
4. Add two integer variables to the form, and name them addend1 and addend2 .

NOTE
An integer variable is known as an int in C# or an Integer in Visual Basic. This kind of variable stores a positive or
negative number from -2147483648 through 2147483647 and can store only whole numbers, not decimals.

You use a similar syntax to add an integer variable as you did to add the Random object, as the following
code shows.

// Create a Random object called randomizer


// to generate random numbers.
Random randomizer = new Random();

// These integer variables store the numbers


// for the addition problem.
int addend1;
int addend2;

' Create a Random object called randomizer


' to generate random numbers.
Private randomizer As New Random

' These integer variables store the numbers


' for the addition problem.
Private addend1 As Integer
Private addend2 As Integer

5. Add a method that's named StartTheQuiz() and that uses the Random object's Next() method to show the
random numbers in the labels. StartTheQuiz() will eventually fill in all of the problems and then start the
timer, so add a comment. The function should look like the following.

/// <summary>
/// Start the quiz by filling in all of the problems
/// and starting the timer.
/// </summary>
public void StartTheQuiz()
{
// Fill in the addition problem.
// Generate two random numbers to add.
// Store the values in the variables 'addend1' and 'addend2'.
addend1 = randomizer.Next(51);
addend2 = randomizer.Next(51);

// Convert the two randomly generated numbers


// into strings so that they can be displayed
// in the label controls.
plusLeftLabel.Text = addend1.ToString();
plusRightLabel.Text = addend2.ToString();

// 'sum' is the name of the NumericUpDown control.


// This step makes sure its value is zero before
// adding any values to it.
sum.Value = 0;
}
''' <summary>
''' Start the quiz by filling in all of the problems
''' and starting the timer.
''' </summary>
''' <remarks></remarks>
Public Sub StartTheQuiz()
' Fill in the addition problem.
' Generate two random numbers to add.
' Store the values in the variables 'addend1' and 'addend2'.
addend1 = randomizer.Next(51)
addend2 = randomizer.Next(51)

' Convert the two randomly generated numbers


' into strings so that they can be displayed
' in the label controls.
plusLeftLabel.Text = addend1.ToString()
plusRightLabel.Text = addend2.ToString()

' 'sum' is the name of the NumericUpDown control.


' This step makes sure its value is zero before
' adding any values to it.
sum.Value = 0
End Sub

Notice that when you enter the dot (.) after randomizer in the code, an IntelliSense window opens and
shows you all of the Random object's methods that you can call. For example, Intellisense lists the Next()
method, as follows.

Next
method
When you enter a dot after an object, IntelliSense shows a list of the object's members, such as properties,
methods, and events.

NOTE
When you use the Next() method with the Random object, such as when you call randomizer.Next(50) , you
get a random number that's less than 50 (from 0 through 49). In this example, you called randomizer.Next(51) .
You used 51 and not 50 so that the two random numbers will add up to an answer that's from 0 through 100. If you
pass 50 to the Next() method, it chooses a number from 0 through 49, so the highest possible answer is 98, not
100. After the first two statements in the method run, each of the two integer variables, addend1 and addend2 ,
hold a random number from 0 through 50. This screenshot shows Visual C# code, but IntelliSense works the same
way for Visual Basic.

Take a closer look at these statements.

plusLeftLabel.Text = addend1.ToString();
plusRightLabel.Text = addend2.ToString();
' Convert the two randomly generated numbers
' into strings so that they can be displayed
' in the label controls.
plusLeftLabel.Text = addend1.ToString()
plusRightLabel.Text = addend2.ToString()

The statements set the Text properties of plusLeftLabel and plusRightLabel so that they display the two
random numbers. You must use the integer's ToString() method to convert the numbers to text. (In
programming, string means text. Label controls display only text, not numbers.
6. In the design window, either double-click the Star t button, or choose it and then choose the Enter key.
When a quiz taker chooses this button, the quiz should start, and you've just added a Click event handler to
implement that behavior.
7. Add the following two statements.

private void startButton_Click(object sender, EventArgs e)


{
StartTheQuiz();
startButton.Enabled = false;
}

' Call the StartTheQuiz() method and enable


' the Start button.
Private Sub startButton_Click() Handles startButton.Click
StartTheQuiz()
startButton.Enabled = False
End Sub

The first statement calls the new StartTheQuiz() method. The second statement sets the Enabled property
of the star tButton control to False so that the quiz taker can't choose the button during a quiz.
8. Save your code, run it, and then choose the Star t button.
A random addition problem appears, as the following illustration shows.

Random addition problem


In the next step of the tutorial, you'll add the sum.
To continue or review
To go to the next tutorial step, see Step 3: Add a Countdown Timer.
To return to the previous tutorial step, see Step 1: Create a Project and Add Labels to Your Form.
Step 3: Add a Countdown Timer
10/18/2019 • 6 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version
selector at the top left. We recommend upgrading to Visual Studio 2019. Download it here

In the third part of this tutorial, you'll add a countdown timer to track the number of seconds that remain for the
quiz taker to finish.

NOTE
This topic is part of a tutorial series about basic coding concepts. For an overview of the tutorial, see Tutorial 2: Create a
Timed Math Quiz.

To add a countdown timer


1. Add an integer variable that's named timeLeft , just like you did in the previous procedure. Your code
should look like the following.

public partial class Form1 : Form


{
// Create a Random object called randomizer
// to generate random numbers.
Random randomizer = new Random();

// These integer variables store the numbers


// for the addition problem.
int addend1;
int addend2;

// This integer variable keeps track of the


// remaining time.
int timeLeft;

Public Class Form1

' Create a Random object called randomizer


' to generate random numbers.
Private randomizer As New Random

' These integer variables store the numbers


' for the addition problem.
Private addend1 As Integer
Private addend2 As Integer

' This integer variable keeps track of the


' remaining time.
Private timeLeft As Integer

Now you need a method that actually counts the seconds, such as a timer, which raises an event after the
amount of time that you specify.
2. In the design window, move a Timer control from the Components category of the Toolbox to your form.
The control appears in the gray area at the bottom of the design window.
3. On the form, choose the timer1 icon that you just added, and set its Inter val property to 1000 .
Because the interval value is milliseconds, a value of 1000 causes the Tick event to fire every second.
4. On the form, double-click the Timer control, or choose it and then choose the Enter key.
The code editor appears and displays the method for the Tick event handler that you just added.
5. Add the following statements to the new event handler method.

private void timer1_Tick(object sender, EventArgs e)


{
if (timeLeft > 0)
{
// Display the new time left
// by updating the Time Left label.
timeLeft = timeLeft - 1;
timeLabel.Text = timeLeft + " seconds";
}
else
{
// If the user ran out of time, stop the timer, show
// a MessageBox, and fill in the answers.
timer1.Stop();
timeLabel.Text = "Time's up!";
MessageBox.Show("You didn't finish in time.", "Sorry!");
sum.Value = addend1 + addend2;
startButton.Enabled = true;
}
}

Private Sub Timer1_Tick() Handles Timer1.Tick

If timeLeft > 0 Then


' Display the new time left
' by updating the Time Left label.
timeLeft -= 1
timeLabel.Text = timeLeft & " seconds"
Else
' If the user ran out of time, stop the timer, show
' a MessageBox, and fill in the answers.
Timer1.Stop()
timeLabel.Text = "Time's up!"
MessageBox.Show("You didn't finish in time.", "Sorry!")
sum.Value = addend1 + addend2
startButton.Enabled = True
End If

End Sub

Based on what you added, the timer checks each second whether time has run out by determining whether
the timeLeft integer variable is greater than 0. If it is, time still remains. The timer first subtracts 1 from
timeLeft and then updates the Text property of the timeLabel control to show the quiz taker how many
seconds remain.
If no time remains, the timer stops and changes the text of the timeLabel control so that it shows Time's
up! A message box announces that the quiz is over, and the answer is revealed—in this case, by adding
addend1 and addend2. The Enabled property of the startButton control is set to true so that the quiz
taker can start another quiz.
You just added an if else statement, which is how you tell programs to make decisions. An if else
statement looks like the following.

NOTE
The following example is for illustration only–don't add it to your project.

If (something that your program will check) Then


' One or more statements that will run
' if what the program checked is true.
Else
' One or more statements that will run
' if what the program checked is false.
End If

if (something that your program will check)


{
// One or more statements that will run
// if what the program checked is true.
}
else
{
// One or more statements that will run
// if what the program checked is false.
}

Look closely at the statement that you added in the else block to show the answer to the addition
problem.

sum.Value = addend1 + addend2;

sum.Value = addend1 + addend2

The statement addend1 + addend2 adds the values in the two variables together. The first part ( sum.Value )
uses the Value property of the sum NumericUpDown control to display the correct answer. You use the same
property later to check the answers for the quiz.
Quiz takers can enter numbers more easily by using a NumericUpDown control, which is why you use one for
the answers to the math problems. All of the potential answers are whole numbers from 0 through 100. By
leaving the default values of the Minimum , Maximum , and DecimalPlaces properties, you ensure that
quiz takers can't enter decimals, negative numbers, or numbers that are too high. (If you wanted to allow
quiz takers to enter 3.141 but not 3.1415, you could set the DecimalPlaces property to 3.)
6. Add three lines to the end of the StartTheQuiz() method, so the code looks like the following.
/// <summary>
/// Start the quiz by filling in all of the problem
/// values and starting the timer.
/// </summary>
public void StartTheQuiz()
{
// Fill in the addition problem.
// Generate two random numbers to add.
// Store the values in the variables 'addend1' and 'addend2'.
addend1 = randomizer.Next(51);
addend2 = randomizer.Next(51);

// Convert the two randomly generated numbers


// into strings so that they can be displayed
// in the label controls.
plusLeftLabel.Text = addend1.ToString();
plusRightLabel.Text = addend2.ToString();

// 'sum' is the name of the NumericUpDown control.


// This step makes sure its value is zero before
// adding any values to it.
sum.Value = 0;

// Start the timer.


timeLeft = 30;
timeLabel.Text = "30 seconds";
timer1.Start();
}

''' <summary>
''' Start the quiz by filling in all of the problem
''' values and starting the timer.
''' </summary>
''' <remarks></remarks>
Public Sub StartTheQuiz()

' Fill in the addition problem.


' Generate two random numbers to add.
' Store the values in the variables 'addend1' and 'addend2'.
addend1 = randomizer.Next(51)
addend2 = randomizer.Next(51)

' Convert the two randomly generated numbers


' into strings so that they can be displayed
' in the label controls.
plusLeftLabel.Text = addend1.ToString()
plusRightLabel.Text = addend2.ToString()

' 'sum' is the name of the NumericUpDown control.


' This step makes sure its value is zero before
' adding any values to it.
sum.Value = 0

' Start the timer.


timeLeft = 30
timeLabel.Text = "30 seconds"
Timer1.Start()

End Sub

Now, when your quiz starts, the timeLeft variable is set to 30 and the Text property of the timeLabel
control is set to 30 seconds. Then the Start() method of the Timer control starts the countdown. (The
quiz doesn't check the answer yet—that comes next.)
7. Save your program, run it, and then choose the Star t button on the form.
The timer starts to count down. When time runs out, the quiz ends, and the answer appears. The following
illustration shows the quiz in progress.

Math quiz in progress


To continue or review
To go to the next tutorial step, see Step 4: Add the CheckTheAnswer() Method.
To return to the previous tutorial step, see Step 2: Create a Random Addition Problem.
Step 4: Add the CheckTheAnswer() Method
10/18/2019 • 3 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version
selector at the top left. We recommend upgrading to Visual Studio 2019. Download it here

In the fourth part of this tutorial, you'll write a method, CheckTheAnswer() , that determines whether the answers to
the math problems are correct. This topic is part of a tutorial series about basic coding concepts. For an overview
of the tutorial, see Tutorial 2: Create a Timed Math Quiz.

NOTE
If you're following along in Visual Basic, you'll use the Function keyword instead of the usual Sub keyword because this
method returns a value. It's really that simple: a sub doesn't return a value, but a function does.

To verify whether the answers are correct


1. Add the CheckTheAnswer() method.
When this method is called, it adds the values of addend1 and addend2 and compares the result to the
value in the sum NumericUpDown control. If the values are equal, the method returns a value of true .
Otherwise, the method returns a value of false . Your code should look like the following.

/// <summary>
/// Check the answer to see if the user got everything right.
/// </summary>
/// <returns>True if the answer's correct, false otherwise.</returns>
private bool CheckTheAnswer()
{
if (addend1 + addend2 == sum.Value)
return true;
else
return false;
}

''' <summary>
''' Check the answer to see if the user got everything right.
''' </summary>
''' <returns>True if the answer's correct, false otherwise.</returns>
''' <remarks></remarks>
Public Function CheckTheAnswer() As Boolean

If addend1 + addend2 = sum.Value Then


Return True
Else
Return False
End If

End Function

Next, you'll check the answer by updating the code in the method for the timer's Tick event handler to call
the new CheckTheAnswer() method.
2. Add the following code to the if else statement.

private void timer1_Tick(object sender, EventArgs e)


{
if (CheckTheAnswer())
{
// If CheckTheAnswer() returns true, then the user
// got the answer right. Stop the timer
// and show a MessageBox.
timer1.Stop();
MessageBox.Show("You got all the answers right!",
"Congratulations!");
startButton.Enabled = true;
}
else if (timeLeft > 0)
{
// If CheckTheAnswer() return false, keep counting
// down. Decrease the time left by one second and
// display the new time left by updating the
// Time Left label.
timeLeft--;
timeLabel.Text = timeLeft + " seconds";
}
else
{
// If the user ran out of time, stop the timer, show
// a MessageBox, and fill in the answers.
timer1.Stop();
timeLabel.Text = "Time's up!";
MessageBox.Show("You didn't finish in time.", "Sorry!");
sum.Value = addend1 + addend2;
startButton.Enabled = true;
}
}

Private Sub Timer1_Tick() Handles Timer1.Tick

If CheckTheAnswer() Then
' If CheckTheAnswer() returns true, then the user
' got the answer right. Stop the timer
' and show a MessageBox.
Timer1.Stop()
MessageBox.Show("You got all of the answers right!", "Congratulations!")
startButton.Enabled = True
ElseIf timeLeft > 0 Then
' If CheckTheAnswer() return false, keep counting
' down. Decrease the time left by one second and
' display the new time left by updating the
' Time Left label.
timeLeft -= 1
timeLabel.Text = timeLeft & " seconds"
Else
' If the user ran out of time, stop the timer, show
' a MessageBox, and fill in the answers.
Timer1.Stop()
timeLabel.Text = "Time's up!"
MessageBox.Show("You didn't finish in time.", "Sorry!")
sum.Value = addend1 + addend2
startButton.Enabled = True
End If

End Sub
If the answer is correct, CheckTheAnswer() returns true . The event handler stops the timer, shows a
congratulatory message, and then makes the Star t button available again. Otherwise, the quiz continues.
3. Save your program, run it, start a quiz, and provide a correct answer to the addition problem.

NOTE
When you enter your answer, you must either select the default value before you start to enter your answer, or you
must delete the zero manually. You'll correct this behavior later in this tutorial.

When you provide a correct answer, a message box opens, the Star t button becomes available, and the
timer stops.
To continue or review
To go to the next tutorial step, see Step 5: Add Enter Event Handlers for the NumericUpDown Controls.
To return to the previous tutorial step, see Step 3: Add a Countdown Timer.
Step 5: Add Enter Event Handlers for the
NumericUpDown Controls
10/18/2019 • 4 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version
selector at the top left. We recommend upgrading to Visual Studio 2019. Download it here

In the fifth part of this tutorial, you'll add Enter event handlers to make entering answers for quiz problems a little
easier. This code will select and clear the current value in each NumericUpDown control as soon as the quiz taker
chooses it and starts to enter a different value.

NOTE
This topic is part of a tutorial series about basic coding concepts. For an overview of the tutorial, see Tutorial 2: Create a
Timed Math Quiz.

To verify the default behavior


1. Run your program, and start the quiz.
In the NumericUpDown control for the addition problem, the cursor flashes next to 0 (zero).
2. Enter 3 , and note that the control shows 30 .
3. Enter 5 , and note that 350 appears but changes to 100 after a second.
Before you fix this problem, think about what's happening. Consider why the 0 didn't disappear when you
entered 3 and why 350 changed to 100 but not immediately.
This behavior may seem odd, but it makes sense given the logic of the code. When you choose the Star t
button, its Enabled property is set to False , and the button appears dimmed and is unavailable. Your
program changes the current selection (focus) to the control that has the next lowest TabIndex value, which
is the NumericUpDown control for the addition problem. When you use the Tab key to go to a
NumericUpDown control, the cursor is automatically positioned at the start of the control, which is why the
numbers that you enter appear from the left side and not the right side. When you specify a number that's
higher than the value of the MaximumValue property, which is set to 100, the number that you enter is
replaced with the value of that property.
To add an Enter event handler for a NumericUpDown control
1. Choose the first NumericUpDown control (named "sum") on the form, and then, in the Proper ties dialog
box, choose the Events icon on the toolbar.
The Events tab in the Proper ties dialog box displays all of the events that you can respond to (handle) for
the item that you choose on the form. Because you chose the NumericUpDown control, all of the events
listed pertain to it.
2. Choose the Enter event, enter answer_Enter , and then choose the Enter key.
Properties dialog box
You've just added an Enter event handler for the sum NumericUpDown control, and you've named the
handler answer_Enter .
3. In the method for the answer_Enter event handler, add the following code.

private void answer_Enter(object sender, EventArgs e)


{
// Select the whole answer in the NumericUpDown control.
NumericUpDown answerBox = sender as NumericUpDown;

if (answerBox != null)
{
int lengthOfAnswer = answerBox.Value.ToString().Length;
answerBox.Select(0, lengthOfAnswer);
}
}

''' <summary>
''' Modify the behavior of the NumericUpDown control
''' to make it easier to enter numeric values for
''' the quiz.
''' </summary>
Private Sub answer_Enter(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles sum.Enter

' Select the whole answer in the NumericUpDown control.


Dim answerBox = TryCast(sender, NumericUpDown)

If answerBox IsNot Nothing Then


Dim lengthOfAnswer = answerBox.Value.ToString().Length
answerBox.Select(0, lengthOfAnswer)
End If

End Sub

This code may look complex, but you can understand it if you look at it step by step. First, look at the top of
the method: object sender in C# or sender As System.Object in Visual Basic. This parameter refers to the
object whose event is firing, which is known as the sender. In this case, the sender object is the
NumericUpDown control. So, in the first line of the method, you specify that the sender isn't just any generic
object but specifically a NumericUpDown control. (Every NumericUpDown control is an object, but not
every object is a NumericUpDown control.) The NumericUpDown control is named answerBox in this
method, because it will be used for all of the NumericUpDown controls on the form, not just the sum
NumericUpDown control. Because you declare the answerBox variable in this method, its scope applies only
to this method. In other words, the variable can be used only within this method.
The next line verifies whether answerBox was successfully converted (cast) from an object to a
NumericUpDown control. If the conversion was unsuccessful, the variable would have a value of null (C#)
or Nothing (Visual Basic). The third line gets the length of the answer that appears in the NumericUpDown
control, and the fourth line selects the current value in the control based on this length. Now, when the quiz
taker chooses the control, Visual Studio fires this event, which causes the current answer to be selected. As
soon as the quiz taker starts to enter a different answer, the previous answer is cleared and replaced with
the new answer.
4. In Windows Forms Designer, choose the difference NumericUpDown control.
5. In the Events page of the Proper ties dialog box, scroll down to the Enter event, choose the drop-down
arrow at the end of the row, and then choose the answer_Enter event handler that you just added.
6. Repeat the previous step for the product and quotient NumericUpDown controls.
7. Save your program, and then run it.
When you choose a NumericUpDown control, the existing value is automatically selected and then cleared
when you start to enter a different value.
To continue or review
To go to the next tutorial step, see Step 6: Add a Subtraction Problem.
To return to the previous tutorial step, see Step 4: Add the CheckTheAnswer() Method.
Step 6: Add a Subtraction Problem
10/18/2019 • 6 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version
selector at the top left. We recommend upgrading to Visual Studio 2019. Download it here

In the sixth part of this tutorial, you'll add a subtraction problem and learn how to perform the following tasks:
Store the subtraction values.
Generate random numbers for the problem (and be sure that the answer is between 0 and 100).
Update the method that checks the answers so that it checks the new subtraction problem too.
Update your timer's Tick event handler so that the event handler fills in the correct answer when time runs
out.
To add a subtraction problem
1. Add two integer variables for the subtraction problem to your form, between the integer variables for the
addition problem and the timer. The code should look like the following.

public partial class Form1 : Form


{
// Create a Random object called randomizer
// to generate random numbers.
Random randomizer = new Random();

// These integer variables store the numbers


// for the addition problem.
int addend1;
int addend2;

// These integer variables store the numbers


// for the subtraction problem.
int minuend;
int subtrahend;

// This integer variable keeps track of the


// remaining time.
int timeLeft;
Public Class Form1

' Create a Random object called randomizer


' to generate random numbers.
Private randomizer As New Random

' These integer variables store the numbers


' for the addition problem.
Private addend1 As Integer
Private addend2 As Integer

' These integer variables store the numbers


' for the subtraction problem.
Private minuend As Integer
Private subtrahend As Integer

' This integer variable keeps track of the


' remaining time.
Private timeLeft As Integer

The names of the new integer variables—minuend and subtrahend —aren't programming terms. They're
the traditional names in arithmetic for the number that's being subtracted (the subtrahend) and the number
from which the subtrahend is being subtracted (the minuend). The difference is the minuend minus the
subtrahend. You could use other names, because your program doesn't require specific names for variables,
controls, components, or methods. You must follow rules such as not starting names with digits, but you
can generally use names such as x1, x2, x3, and x4. However, generic names make code difficult to read and
problems nearly impossible to track down. To keep variable names unique and helpful, you'll use the
traditional names for multiplication (multiplicand × multiplier = product) and division (dividend ÷ divisor =
quotient) later in this tutorial.
Next, you'll modify the StartTheQuiz() method to provide random values for the subtraction problem.
2. Add the following code after the "Fill in the subtraction problem" comment.
/// <summary>
/// Start the quiz by filling in all of the problem
/// values and starting the timer.
/// </summary>
public void StartTheQuiz()
{
// Fill in the addition problem.
// Generate two random numbers to add.
// Store the values in the variables 'addend1' and 'addend2'.
addend1 = randomizer.Next(51);
addend2 = randomizer.Next(51);

// Convert the two randomly generated numbers


// into strings so that they can be displayed
// in the label controls.
plusLeftLabel.Text = addend1.ToString();
plusRightLabel.Text = addend2.ToString();

// 'sum' is the name of the NumericUpDown control.


// This step makes sure its value is zero before
// adding any values to it.
sum.Value = 0;

// Fill in the subtraction problem.


minuend = randomizer.Next(1, 101);
subtrahend = randomizer.Next(1, minuend);
minusLeftLabel.Text = minuend.ToString();
minusRightLabel.Text = subtrahend.ToString();
difference.Value = 0;

// Start the timer.


timeLeft = 30;
timeLabel.Text = "30 seconds";
timer1.Start();
}
''' <summary>
''' Start the quiz by filling in all of the problem
''' values and starting the timer.
''' </summary>
''' <remarks></remarks>
Public Sub StartTheQuiz()

' Fill in the addition problem.


' Generate two random numbers to add.
' Store the values in the variables 'addend1' and 'addend2'.
addend1 = randomizer.Next(51)
addend2 = randomizer.Next(51)

' Convert the two randomly generated numbers


' into strings so that they can be displayed
' in the label controls.
plusLeftLabel.Text = addend1.ToString()
plusRightLabel.Text = addend2.ToString()

' 'sum' is the name of the NumericUpDown control.


' This step makes sure its value is zero before
' adding any values to it.
sum.Value = 0

' Fill in the subtraction problem.


minuend = randomizer.Next(1, 101)
subtrahend = randomizer.Next(1, minuend)
minusLeftLabel.Text = minuend.ToString()
minusRightLabel.Text = subtrahend.ToString()
difference.Value = 0

' Start the timer.


timeLeft = 30
timeLabel.Text = "30 seconds"
Timer1.Start()

End Sub

To prevent negative answers for the subtraction problem, this code uses the Next() method of the Random
class a little differently from how the addition problem does. When you give the Next() method two
values, it picks a random number that's greater than or equal to the first value and less than the second one.
The following code chooses a random number from 1 through 100 and stores it in the minuend variable.

minuend = randomizer.Next(1, 101);

minuend = randomizer.Next(1, 101)

You can call the Next() method of the Random class, which you named "randomizer" earlier in this tutorial,
in multiple ways. Methods that you can call in more than one way are referred to as overloaded, and you
can use IntelliSense to explore them. Look again at the tooltip of the IntelliSense window for the Next()
method.
Intellisense window tooltip
The tooltip shows (+ 2 overload(s)) , which means that you can call the Next() method in two other ways.
Overloads contain different numbers or types of arguments, so that they work slightly differently from one
another. For example, a method might take a single integer argument, whereas one of its overloads might
take an integer and a string. You choose the correct overload based on what you want it to do. When you
add the code to the StartTheQuiz() method, more information appears in the Intellisense window as soon
as you enter randomizer.Next( . Choose the Up Arrow and Down Arrow keys to cycle through the overloads,
as the following illustration shows.

Overload for Next() method


in IntelliSense
In this case, you want to choose the last overload, because you can specify minimum and maximum values.
3. Modify the CheckTheAnswer() method to check for the correct subtraction answer.

/// <summary>
/// Check the answers to see if the user got everything right.
/// </summary>
/// <returns>True if the answer's correct, false otherwise.</returns>
private bool CheckTheAnswer()
{
if ((addend1 + addend2 == sum.Value)
&& (minuend - subtrahend == difference.Value))
return true;
else
return false;
}

''' <summary>
''' Check the answers to see if the user got everything right.
''' </summary>
''' <returns>True if the answer's correct, false otherwise.</returns>
''' <remarks></remarks>
Public Function CheckTheAnswer() As Boolean

If addend1 + addend2 = sum.Value AndAlso


minuend - subtrahend = difference.Value Then

Return True
Else
Return False
End If

End Function
In Visual C#, && is the logical and operator. In Visual Basic, the equivalent operator is AndAlso . These
operators indicate "If the sum of addend1 and addend2 equals the value of the sum NumericUpDown and if
minuend minus subtrahend equals the value of the difference NumericUpDown." The CheckTheAnswer()
method returns true only if the answers to the addition and the subtraction problems are both correct.
4. Replace the last part of the timer's Tick event handler with the following code so that it fills in the correct
answer when time runs out.

else
{
// If the user ran out of time, stop the timer, show
// a MessageBox, and fill in the answers.
timer1.Stop();
timeLabel.Text = "Time's up!";
MessageBox.Show("You didn't finish in time.", "Sorry!");
sum.Value = addend1 + addend2;
difference.Value = minuend - subtrahend;
startButton.Enabled = true;
}

Else
' If the user ran out of time, stop the timer, show
' a MessageBox, and fill in the answers.
Timer1.Stop()
timeLabel.Text = "Time's up!"
MessageBox.Show("You didn't finish in time.", "Sorry!")
sum.Value = addend1 + addend2
difference.Value = minuend - subtrahend
startButton.Enabled = True
End If

5. Save and run your code.


Your program includes a subtraction problem, as the following illustration shows.

Math quiz with subtraction problem


To continue or review
To go to the next tutorial step, see Step 7: Add Multiplication and Division Problems.
To return to the previous tutorial step, see Step 5: Add Enter Event Handlers for the NumericUpDown
Controls.
Step 7: Add Multiplication and Division Problems
10/18/2019 • 5 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version
selector at the top left. We recommend upgrading to Visual Studio 2019. Download it here

In the seventh part of this tutorial, you'll add multiplication and division problems, but first think about how to
make that change. Consider the initial step, which involves storing values.
To add multiplication and division problems
1. Add four more integer variables to the form.

public partial class Form1 : Form


{
// Create a Random object called randomizer
// to generate random numbers.
Random randomizer = new Random();

// These integer variables store the numbers


// for the addition problem.
int addend1;
int addend2;

// These integer variables store the numbers


// for the subtraction problem.
int minuend;
int subtrahend;

// These integer variables store the numbers


// for the multiplication problem.
int multiplicand;
int multiplier;

// These integer variables store the numbers


// for the division problem.
int dividend;
int divisor;

// This integer variable keeps track of the


// remaining time.
int timeLeft;
Public Class Form1

' Create a Random object called randomizer


' to generate random numbers.
Private randomizer As New Random

' These integer variables store the numbers


' for the addition problem.
Private addend1 As Integer
Private addend2 As Integer

' These integer variables store the numbers


' for the subtraction problem.
Private minuend As Integer
Private subtrahend As Integer

' These integer variables store the numbers


' for the multiplication problem.
Private multiplicand As Integer
Private multiplier As Integer

' These integer variables store the numbers


' for the division problem.
Private dividend As Integer
Private divisor As Integer

' This integer variable keeps track of the


' remaining time.
Private timeLeft As Integer

2. As you did before, modify the StartTheQuiz() method to fill in random numbers for the multiplication and
division problems.
/// <summary>
/// Start the quiz by filling in all of the problem
/// values and starting the timer.
/// </summary>
public void StartTheQuiz()
{
// Fill in the addition problem.
// Generate two random numbers to add.
// Store the values in the variables 'addend1' and 'addend2'.
addend1 = randomizer.Next(51);
addend2 = randomizer.Next(51);

// Convert the two randomly generated numbers


// into strings so that they can be displayed
// in the label controls.
plusLeftLabel.Text = addend1.ToString();
plusRightLabel.Text = addend2.ToString();

// 'sum' is the name of the NumericUpDown control.


// This step makes sure its value is zero before
// adding any values to it.
sum.Value = 0;

// Fill in the subtraction problem.


minuend = randomizer.Next(1, 101);
subtrahend = randomizer.Next(1, minuend);
minusLeftLabel.Text = minuend.ToString();
minusRightLabel.Text = subtrahend.ToString();
difference.Value = 0;

// Fill in the multiplication problem.


multiplicand = randomizer.Next(2, 11);
multiplier = randomizer.Next(2, 11);
timesLeftLabel.Text = multiplicand.ToString();
timesRightLabel.Text = multiplier.ToString();
product.Value = 0;

// Fill in the division problem.


divisor = randomizer.Next(2, 11);
int temporaryQuotient = randomizer.Next(2, 11);
dividend = divisor * temporaryQuotient;
dividedLeftLabel.Text = dividend.ToString();
dividedRightLabel.Text = divisor.ToString();
quotient.Value = 0;

// Start the timer.


timeLeft = 30;
timeLabel.Text = "30 seconds";
timer1.Start();
}
''' <summary>
''' Start the quiz by filling in all of the problem
''' values and starting the timer.
''' </summary>
''' <remarks></remarks>
Public Sub StartTheQuiz()

' Fill in the addition problem.


' Generate two random numbers to add.
' Store the values in the variables 'addend1' and 'addend2'.
addend1 = randomizer.Next(51)
addend2 = randomizer.Next(51)

' Convert the two randomly generated numbers


' into strings so that they can be displayed
' in the label controls.
plusLeftLabel.Text = addend1.ToString()
plusRightLabel.Text = addend2.ToString()

' 'sum' is the name of the NumericUpDown control.


' This step makes sure its value is zero before
' adding any values to it.
sum.Value = 0

' Fill in the subtraction problem.


minuend = randomizer.Next(1, 101)
subtrahend = randomizer.Next(1, minuend)
minusLeftLabel.Text = minuend.ToString()
minusRightLabel.Text = subtrahend.ToString()
difference.Value = 0

' Fill in the multiplication problem.


multiplicand = randomizer.Next(2, 11)
multiplier = randomizer.Next(2, 11)
timesLeftLabel.Text = multiplicand.ToString()
timesRightLabel.Text = multiplier.ToString()
product.Value = 0

' Fill in the division problem.


divisor = randomizer.Next(2, 11)
Dim temporaryQuotient As Integer = randomizer.Next(2, 11)
dividend = divisor * temporaryQuotient
dividedLeftLabel.Text = dividend.ToString()
dividedRightLabel.Text = divisor.ToString()
quotient.Value = 0

' Start the timer.


timeLeft = 30
timeLabel.Text = "30 seconds"
Timer1.Start()

End Sub

3. Modify the CheckTheAnswer() method so that it also checks the multiplication and division problems.
/// <summary>
/// Check the answers to see if the user got everything right.
/// </summary>
/// <returns>True if the answer's correct, false otherwise.</returns>
private bool CheckTheAnswer()
{
if ((addend1 + addend2 == sum.Value)
&& (minuend - subtrahend == difference.Value)
&& (multiplicand * multiplier == product.Value)
&& (dividend / divisor == quotient.Value))
return true;
else
return false;
}

''' <summary>
''' Check the answers to see if the user got everything right.
''' </summary>
''' <returns>True if the answer's correct, false otherwise.</returns>
''' <remarks></remarks>
Public Function CheckTheAnswer() As Boolean

If addend1 + addend2 = sum.Value AndAlso


minuend - subtrahend = difference.Value AndAlso
multiplicand * multiplier = product.Value AndAlso
dividend / divisor = quotient.Value Then

Return True
Else
Return False
End If

End Function

You can't easily enter the multiplication sign (×) and the division sign (÷) using the keyboard, so Visual C#
and Visual Basic accept an asterisk (*) for multiplication and a slash mark (/) for division.
4. Change the last part of the timer's Tick event handler so that it fills in the correct answer when time runs
out.

else
{
// If the user ran out of time, stop the timer, show
// a MessageBox, and fill in the answers.
timer1.Stop();
timeLabel.Text = "Time's up!";
MessageBox.Show("You didn't finish in time.", "Sorry");
sum.Value = addend1 + addend2;
difference.Value = minuend - subtrahend;
product.Value = multiplicand * multiplier;
quotient.Value = dividend / divisor;
startButton.Enabled = true;
}
Else
' If the user ran out of time, stop the timer, show
' a MessageBox, and fill in the answers.
Timer1.Stop()
timeLabel.Text = "Time's up!"
MessageBox.Show("You didn't finish in time.", "Sorry!")
sum.Value = addend1 + addend2
difference.Value = minuend - subtrahend
product.Value = multiplicand * multiplier
quotient.Value = dividend / divisor
startButton.Enabled = True
End If

5. Save and run your program.


Quiz takers must answer four problems to complete the quiz, as the following illustration shows.

Math quiz with four problems


To continue or review
To go to the next tutorial step, see Step 8: Customize the Quiz.
To return to the previous tutorial step, see Step 6: Add a Subtraction Problem.
Step 8: Customize the Quiz
11/21/2019 • 2 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version selector
at the top left. We recommend upgrading to Visual Studio 2019. Download it here

In the last part of the tutorial, you'll explore some ways to customize the quiz and expand on what you've already
learned. For example, think about how the program creates random division problems for which the answer is
never a fraction. To learn more, turn the timeLabel control a different color, and give the quiz taker a hint.
To customize the quiz
When only five seconds remain in a quiz, turn the timeLabel control red by setting its BackColor property
( timeLabel.BackColor = Color.Red; ). Reset the color when the quiz is over.
Give the quiz taker a hint by playing a sound when the correct answer is entered into a NumericUpDown
control. (You must write an event handler for each control's ValueChanged() event, which fires whenever the
quiz taker changes the control's value.)
To continue or review
To go to the next tutorial, see Tutorial 3: Create a Matching Game.
To return to the previous tutorial step, see Step 7: Add Multiplication and Division Problems.
Tutorial 3: Create a Matching Game
11/21/2019 • 2 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version
selector at the top left. We recommend upgrading to Visual Studio 2019. Download it here

In this tutorial, you build a matching game, where the player must match pairs of hidden icons. You learn how to:
Store objects, such as icons, in a List object.
Use a foreach loop in Visual C# or a For Each loop in Visual Basic to iterate through items in a list.
Keep track of a form's state by using reference variables.
Build an event handler to respond to events that you can use with multiple objects.
Make a timer that counts down and then fires an event exactly once after being started.
When you finish this tutorial, your program will look like the following picture.

Game that you create in this tutorial

NOTE
In this tutorial, both Visual C# and Visual Basic are covered, so focus on information specific to the programming language
that you're using.

If you get stuck or have programming questions, try posting your question on one of the MSDN forums. See
Visual Basic Forum and Visual C# Forum. Also, there are great, free video learning resources available to you. To
learn more about programming in Visual Basic, see Visual Basic Fundamentals: Development for Absolute
Beginners. To learn more about programming in Visual C#, see C# Fundamentals: Development for Absolute
Beginners.
Related Topics
T IT L E DESC RIP T IO N

Step 1: Create a Project and Add a Table to Your Form Begin by creating the project and adding a
TableLayoutPanel control to keep the controls aligned
properly.

Step 2: Add a Random Object and a List of Icons Add a Random object and a List object, to create a list of
icons.

Step 3: Assign a Random Icon to Each Label Assign the icons randomly to the Label controls, so that
each game is different.

Step 4: Add a Click Event Handler to Each Label Add a Click event handler that changes the color of the label
that is clicked.

Step 5: Add Label References Add reference variables to keep track of which labels are
clicked.

Step 6: Add a Timer Add a timer to the form to keep track of the time that has
passed in the game.

Step 7: Keep Pairs Visible Keep pairs of icons visible, if a matching pair is selected.

Step 8: Add a Method to Verify Whether the Player Won Add a CheckForWinner() method to verify whether the
player won.

Step 9: Try Other Features Try other features, such as changing icons and colors, adding
a grid, and adding sounds. Try making the board bigger and
adjusting the timer.
Step 1: Create a Project and Add a Table to Your
Form
10/18/2019 • 4 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version selector
at the top left. We recommend upgrading to Visual Studio 2019. Download it here

The first step in creating a matching game is to create the project and add a table to your form. The table helps
align the icons into an orderly 4x4 grid. You also set several properties to enhance the appearance of the game
board.
To create a project and add a table to your form
1. On the menu bar, choose File , New , Project .
2. If you’re not using Visual Studio Express, you need to select a programming language first. From the
Installed Templates list, choose either Visual C# or Visual Basic .
3. In the list of project templates, choose Windows Forms Application , name the project MatchingGame ,
and then choose the OK button.
4. In the Proper ties window, set the following form properties.
a. Change the form's Text property from Form1 to Matching Game . This text appears at the top of
the game window.
b. Set the size of the form to 550 pixels wide by 550 tall. You can do this either by setting the Size
property to 550, 550 , or by dragging the corner of the form until you see the correct size in the
lower-right corner of the integrated development environment (IDE).
5. Display the toolbox by choosing the Toolbox tab on the left side of the IDE.
6. Drag a TableLayoutPanel control from the Containers category in the toolbox, and then set the following
properties for it.
a. Set the BackColor property to CornflowerBlue . To do this, open the BackColor dialog box by
choosing the drop-down arrow next to the BackColor property in the Proper ties window. Then,
choose the Web tab in the BackColor dialog box to view a list of available color names.

NOTE
The colors are not in alphabetical order, and CornflowerBlue is near the bottom of the list.

b. Set the Dock property to Fill by choosing the drop-down button next to the property and choosing
the large middle button. This spreads the table out so that it covers the entire form.
c. Set the CellBorderStyle property to Inset . This provides visual borders between each cell on the
board.
d. Choose the triangle button in the upper-right corner of the TableLayoutPanel to display its task menu.
e. On the task menu, choose Add Row twice to add two more rows, and then choose Add Column
twice to add two more columns.
f. On the task menu, choose Edit Rows and Columns to open the Column and Row Styles window.
Choose each of the columns, choose the Percent option button, and then set each column's width to
25 percent of the total width. Then select Rows from the drop-down box at the top of the window,
and set each row's height to 25 percent. When you're done, choose the OK button.
Your TableLayoutPanel should now be a 4x4 grid, with sixteen equally sized square cells. These rows
and columns are where the icon images will appear later.
7. Be certain that the TableLayoutPanel is selected in the form editor. To verify this, you should see
tableLayoutPanel1 at the top of the Proper ties window. If it is not selected, choose the TableLayoutPanel
on the form, or choose it in the dropdown control at the top of the Proper ties window.
While the TableLayoutPanel is selected, open the toolbox and add a Label control (located in the Common
Controls category) to the upper-left cell of the TableLayoutPanel. The Label control should now be
selected in the IDE. Set the following properties for it.
a. Be sure that the label's BackColor property is set to CornflowerBlue .
b. Set the AutoSize property to False .
c. Set the Dock property to Fill .
d. Set the TextAlign property to MiddleCenter by choosing the drop-down button next to the
property, and then choosing the middle button. This ensures the icon appears in the middle of the
cell.
e. Choose the Font property. An ellipsis (…) button should appear.
f. Choose the ellipsis button, and set the Font value to Webdings , the Font Style to Bold , and the
Size to 72 .
g. Set the Text property of the label to the letter c .
The upper-left cell in the TableLayoutPanel should now contain a black box centered on a blue
background.

NOTE
The Webdings font is a font of icons that ships with the Windows operating system. In your matching game,
the player needs to match pairs of icons, so you use this font to display the icons to match. Instead of putting
c in the Text property, try entering different letters to see what icons are displayed. An exclamation point is a
spider, an uppercase N is an eye, and a comma is a chili pepper.

8. Choose your label control and copy it to the next cell in the TableLayoutPanel. (Choose the Ctrl+C keys, or on
the menu bar, choose Edit , Copy .) Then paste it. (Choose the Ctrl+V keys, or on the menu bar, choose Edit ,
Paste .) A copy of the first label appears in the second cell of the TableLayoutPanel. Paste it again, and
another label appears in the third cell. Keep pasting Label controls until all of the cells are filled.

NOTE
If you paste too many times, the IDE adds a new row to the TableLayoutPanel so that it has a place to add your new
label control. You can undo it. To remove the new cell, choose the Ctrl+Z keys, or on the menu bar, choose Edit ,
Undo .
Now your form is laid out. It should look like the following picture.

Initial matching game form


To continue or review
To go to the next tutorial step, see Step 2: Add a Random Object and a List of Icons.
To return to the overview topic, see Tutorial 3: Create a Matching Game.
Step 2: Add a Random Object and a List of Icons
10/18/2019 • 4 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version
selector at the top left. We recommend upgrading to Visual Studio 2019. Download it here

In this step, you create a set of matching symbols for the game. Each symbol is added to two random cells in the
TableLayoutPanel on the form. To do this, you use two new statements to create two objects. The first is a Random
object, like the one you used in the math quiz game. It is used in this code to randomly choose cells in the
TableLayoutPanel. The second object, which may be new to you, is a List object which is used to store the
randomly-chosen symbols.
To add a Random object and a list of icons
1. In Solution Explorer , choose Form1.cs if you're using Visual C#, or Form1.vb if you're using Visual Basic,
and then on the menu bar, choose View , Code . As an alternative, you can choose the F7 key or double-click
Form1 in Solution Explorer .
This displays the code module behind Form1.
2. In the existing code, add the following code.

public partial class Form1 : Form


{
// Use this Random object to choose random icons for the squares
Random random = new Random();

// Each of these letters is an interesting icon


// in the Webdings font,
// and each icon appears twice in this list
List<string> icons = new List<string>()
{
"!", "!", "N", "N", ",", ",", "k", "k",
"b", "b", "v", "v", "w", "w", "z", "z"
};

Public Class Form1

' Use this Random object to choose random icons for the squares
Private random As New Random

' Each of these letters is an interesting icon


' in the Webdings font,
' and each icon appears twice in this list
Private icons =
New List(Of String) From {"!", "!", "N", "N", ",", ",", "k", "k",
"b", "b", "v", "v", "w", "w", "z", "z"}

If you're using Visual C#, be sure you put the code after the opening curly brace and just after the class
declaration ( public partial class Form1 : Form ). If you're using Visual Basic, put the code right after the
class declaration ( Public Class Form1 ).
3. When adding the List object, notice the IntelliSense window that opens. The following is a Visual C#
example, but similar text appears when you add a list in Visual Basic.

IntelliSense window

NOTE
The Intellisense window appears only when you enter code manually. If you copy and paste the code, it doesn't
appear.

If you look at the code (and remarks) in small sections, it's easier to understand. Your programs can use
List objects to keep track of many different types of items. A list can hold numbers, true/false values, text,
or other objects. You can even have a List object that holds other List objects. The items in a list are
called elements, and each list only holds one type of element. So, a list of numbers can only hold numbers
—you can't add text to that list. Similarly, you can't add numbers to a list of true/false values.
When you create a List object using a new statement, you need to specify the kind of data you want to
store in it. That's why the tooltip at the top of the IntelliSense window shows the types of elements in the
list. Also, that's what List<string> (in Visual C#) and List(Of String) (in Visual Basic) means: It's a List
object that holds elements of string data type. A string is what your program uses to store text, which is
what the tooltip to the right of the IntelliSense window is telling you.
4. Consider why in Visual Basic a temporary array must be created first, but in Visual C#, the list can be
created with one statement. This is because the Visual C# language has collection initializers, which prepare
the list to accept values. In Visual Basic, you can use a collection initializer. However, for compatibility with
the previous version of Visual Basic, we recommend using the preceding code.
When you use a collection initializer with a new statement, after the new List object is created, the
program fills it with the data you provided inside the curly braces. In this case, you get a list of strings
named icons , and that list will be initialized so that it contains sixteen strings. Each of those strings is a
single letter, and they all correspond to the icons that will be in the labels. So, the game will have a pair of
exclamation points, a pair of uppercase N letters, a pair of commas, and so on. (When these characters are
set to the Webdings font, they will appear as symbols, such as a bus, a bike, a spider, and so forth.) Your
List object will have sixteen strings in all, one for each cell in the TableLayoutPanel panel.

NOTE
In Visual Basic, you get the same result, but first the strings are put into a temporary array, which is then converted
into a List object. An array is similar to a list, except, for example, arrays are created with a fixed size. Lists can
shrink and grow as needed, which is important in this program.

To continue or review
To go to the next tutorial step, see Step 3: Assign a Random Icon to Each Label.
To return to the previous tutorial step, see Step 1: Create a Project and Add a Table to Your Form.
Step 3: Assign a Random Icon to Each Label
10/18/2019 • 6 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version
selector at the top left. We recommend upgrading to Visual Studio 2019. Download it here

If the icons show up in the same cells every game, it's not very challenging. To avoid this, assign the icons
randomly to the label controls on your form by using an AssignIconsToSquares() method.
To assign a random icon to each label
1. Before adding the following code, consider how the method works. There's a new keyword: foreach in
Visual C# and For Each in Visual Basic. (One of the lines is commented out on purpose, which is explained
at the end of this procedure.)

/// <summary>
/// Assign each icon from the list of icons to a random square
/// </summary>
private void AssignIconsToSquares()
{
// The TableLayoutPanel has 16 labels,
// and the icon list has 16 icons,
// so an icon is pulled at random from the list
// and added to each label
foreach (Control control in tableLayoutPanel1.Controls)
{
Label iconLabel = control as Label;
if (iconLabel != null)
{
int randomNumber = random.Next(icons.Count);
iconLabel.Text = icons[randomNumber];
// iconLabel.ForeColor = iconLabel.BackColor;
icons.RemoveAt(randomNumber);
}
}
}
''' <summary>
''' Assign each icon from the list of icons to a random square
''' </summary>
''' <remarks></remarks>
Private Sub AssignIconsToSquares()

' The TableLayoutPanel has 16 labels,


' and the icon list has 16 icons,
' so an icon is pulled at random from the list
' and added to each label
For Each control In TableLayoutPanel1.Controls
Dim iconLabel = TryCast(control, Label)
If iconLabel IsNot Nothing Then
Dim randomNumber = random.Next(icons.Count)
iconLabel.Text = icons(randomNumber)
' iconLabel.ForeColor = iconLabel.BackColor
icons.RemoveAt(randomNumber)
End If
Next

End Sub

2. Add the AssignIconsToSquares() method as shown in the previous step. You can put it just below the code
you added in Step 2: Add a Random Object and a List of Icons.
As mentioned earlier, there's something new in your AssignIconsToSquares() method: a foreach loop in
Visual C# and For Each in Visual Basic. You can use a For Each loop any time you want to do the same
action multiple times. In this case, you want to execute the same statements for every label on your
TableLayoutPanel, as explained by the following code. The first line creates a variable named control that
stores each control one at a time while that control has the statements in the loop executed on it.

foreach (Control control in tableLayoutPanel1.Controls)


{
// The statements you want to execute
// for each label go here
// The statements use iconLabel to access
// each label's properties and methods
}

For Each control In TableLayoutPanel1.Controls


' The statements you want to execute
' for each label go here
' The statements use iconLabel to access
' each label's properties and methods
Next

NOTE
The names "iconLabel" and "control" are used because they are descriptive. You can replace these names with any
names, and the code will work exactly the same as long as you change the name in each statement inside the loop.

The AssignIconsToSquares() method iterates through each label control in the TableLayoutPanel and
executes the same statements for each of them. Those statements pull a random icon from the list that you
added in Step 2: Add a Random Object and a List of Icons. (That's why you included two of each icon in the
list, so there would be a pair of icons assigned to random label controls.)
Look more closely at the code that runs inside the foreach or For Each loop. This code is reproduced here.
Label iconLabel = control as Label;
if (iconLabel != null)
{
int randomNumber = random.Next(icons.Count);
iconLabel.Text = icons[randomNumber];
// iconLabel.ForeColor = iconLabel.BackColor;
icons.RemoveAt(randomNumber);
}

Dim iconLabel = TryCast(control, Label)


If iconLabel IsNot Nothing Then
Dim randomNumber = random.Next(icons.Count)
iconLabel.Text = icons(randomNumber)
' iconLabel.ForeColor = iconLabel.BackColor
icons.RemoveAt(randomNumber)
End If

The first line converts the control variable to a label named iconLabel . The line after that is an if
statement that checks to make sure the conversion worked. If the conversion does work, the statements in
the if statement run. (As you may recall from the previous tutorials, the if statement is used to evaluate
whatever condition you specify.) The first line in the if statement creates a variable named randomNumber
that contains a random number that corresponds to one of the items in the icons list. To do this, it uses the
Next method of the Random object that you created earlier. The Next method returns the random number.
This line also uses the Count property of the icons list to determine the range from which to choose the
random number. The next line assigns one of the icon list items to the Text property of the label. The
commented-out line is explained later in this topic. Finally, the last line in the if statement removes from
the list the icon that has been added to the form.
Remember, if you're not sure about what some part of the code does, you can position the mouse pointer
over a code element and review the resulting tooltip. You can also step through each line of code while the
program is running by using the Visual Studio debugger. See How Do I: Step with The Debugger in Visual
Studio? or Navigating through Code with the Debugger for more information.
3. To fill up the game board with icons, you need to call the AssignIconsToSquares() method as soon as the
program starts. If you're using Visual C#, add a statement just below the call to the InitializeComponent()
method in the Form1 constructor, so your form calls your new method to set itself up before it's shown.
Constructors are called when you create a new object, such as a class or struct. See Constructors (C#
Programming Guide) or Using Constructors and Destructors in Visual Basic for more information.

public Form1()
{
InitializeComponent();

AssignIconsToSquares();
}

For Visual Basic, add the AssignIconsToSquares() method call to the Form1_Load method so that the code
looks like the following.

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load


AssignIconsToSquares()
End Sub

4. Save your program and run it. It should show a form with random icons assigned to each label.
5. Close your program, and then run it again. Notice that different icons are assigned to each label, as shown
in the following picture.

Matching game with random icons


The icons are visible now because you haven't hidden them. To hide them from the player, you can set each
label's Forecolor property to the same color as its BackColor property.

TIP
Another way to hide controls like labels is to set their Visible property to False .

6. To hide the icons, stop the program and remove the comment marks for the commented line of code inside
the For Each loop.

iconLabel.ForeColor = iconLabel.BackColor;

iconLabel.ForeColor = iconLabel.BackColor

7. On the menu bar, choose the Save All button to save your program, and then run it. The icons seem to
have disappeared—only a blue background appears. However, the icons are randomly assigned and are still
there. Because the icons are the same color as the background, it hides them from the player. After all, it
wouldn't be a very challenging game if the player could see all of the icons right away!
To continue or review
To go to the next tutorial step, see Step 4: Add a Click Event Handler to Each Label.
To return to the previous tutorial step, see Step 2: Add a Random Object and a List of Icons.
Step 4: Add a Click Event Handler to Each Label
10/18/2019 • 3 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version
selector at the top left. We recommend upgrading to Visual Studio 2019. Download it here

The matching game works as follows:


1. When a player chooses one of the squares with a hidden icon, the program shows the icon to the player by
changing the icon color to black.
2. Then the player chooses another hidden icon.
3. If the icons match, they stay visible. If not, both icons are hidden again.
To get your program to work that way, you add a Click event handler that changes the color of the label that
is chosen.
To add a Click event handler to each label
1. Open the form in the Windows Forms Designer. In Solution Explorer, choose Form1.cs or Form1.vb. On the
menu bar, choose View , Designer .
2. Choose the first label control to select it. Then, hold down the CTRL key while you choose each of the other
labels to select them. Be sure that every label is selected.
3. Choose the Events button on the tool bar in the Proper ties window to view the Events page in the
Proper ties window. Scroll down to the Click event, and enter label_Click in the box, as shown in the
following picture.

Properties window showing Click event


4. Choose the ENTER key. The IDE adds a Click event handler called label_Click() to the code, and hooks it to
each of the labels on the form.
5. Fill in the rest of the code, as follows:
/// <summary>
/// Every label's Click event is handled by this event handler
/// </summary>
/// <param name="sender">The label that was clicked</param>
/// <param name="e"></param>
private void label_Click(object sender, EventArgs e)
{
Label clickedLabel = sender as Label;

if (clickedLabel != null)
{
// If the clicked label is black, the player clicked
// an icon that's already been revealed --
// ignore the click
if (clickedLabel.ForeColor == Color.Black)
return;

clickedLabel.ForeColor = Color.Black;
}
}

''' <summary>
''' Every label's Click event is handled by this event handler
''' </summary>
''' <param name="sender">The label that was clicked</param>
''' <param name="e"></param>
''' <remarks></remarks>
Private Sub label_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Label9.Click,
Label8.Click, Label7.Click, Label6.Click, Label5.Click, Label4.Click,
Label3.Click, Label2.Click, Label16.Click, Label15.Click, Label14.Click,
Label13.Click, Label12.Click, Label11.Click, Label10.Click, Label1.Click

Dim clickedLabel = TryCast(sender, Label)

If clickedLabel IsNot Nothing Then

' If the clicked label is black, the player clicked


' an icon that's already been revealed --
' ignore the click
If clickedLabel.ForeColor = Color.Black Then Exit Sub

clickedLabel.ForeColor = Color.Black
End If
End Sub

NOTE
If you copy and paste the label_Click() code block rather than entering the code manually, be sure to replace the
existing label_Click() code. Otherwise, you'll end up with a duplicate code block.

NOTE
You may recognize object sender at the top of the event handler as the same one used in the Tutorial 2: Create a
Timed Math Quiz tutorial. Because you hooked up different label control Click event to a single event handler
method, the same method is called no matter which label the user chooses. The event handler method needs to
know which label was chosen, so it uses the name sender to identify the label control. The first line of the method
tells the program that it's not just a generic object, but specifically a label control, and that it uses the name
clickedLabel to access the label's properties and methods.
This method first checks whether clickedLabel was successfully converted (cast) from an object to a label
control. If unsuccessful, it has a value of null (C#) or Nothing (Visual Basic), and you don't want to execute
the remainder of the code in the method. Next, the method checks the chosen label's text color by using the
label's ForeColor property. If the label's text color is black, then that means the icon's already been chosen
and the method is done. (That's what the return statement does: It tells the program to stop executing the
method.) Otherwise, the icon hasn't been chosen, so the program changes the label's text color to black.
6. On the menu bar, choose File , Save All to save your progress, and then, on the menu bar, choose Debug ,
Star t Debugging to run your program. You should see an empty form with a blue background. Choose
any of the cells in the form, and one of the icons should become visible. Continue choosing different places
in the form. As you choose the icons, they should appear.
To continue or review
To go to the next tutorial step, see Step 5: Add Label References.
To return to the previous tutorial step, see Step 3: Assign a Random Icon to Each Label.
Step 5: Add Label References
10/18/2019 • 4 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version
selector at the top left. We recommend upgrading to Visual Studio 2019. Download it here

The program needs to track which label controls the player chooses. Right now, the program shows all labels
chosen by the player. But we're going to change that. After the first label is chosen, the program should show the
label's icon. After the second label is chosen, the program should display both icons for a brief time, and then hide
both icons again. Your program will now keep track of which label control is chosen first and which is chosen
second by using reference variables.
To add label references
1. Add label references to your form by using the following code.

public partial class Form1 : Form


{
// firstClicked points to the first Label control
// that the player clicks, but it will be null
// if the player hasn't clicked a label yet
Label firstClicked = null;

// secondClicked points to the second Label control


// that the player clicks
Label secondClicked = null;

Public Class Form1

' firstClicked points to the first Label control


' that the player clicks, but it will be Nothing
' if the player hasn't clicked a label yet
Private firstClicked As Label = Nothing

' secondClicked points to the second Label control


' that the player clicks
Private secondClicked As Label = Nothing

These reference variables look similar to the statements you used earlier to add objects (like Timer objects,
List objects, and Random objects) to your form. However, these statements don't cause two extra label
controls to appear on the form because there's no new keyword used in either of the two statements.
Without the new keyword, no object is created. That's why firstClicked and secondClicked are called
reference variables: They just keep track (or, refer to) Label objects.
When a variable isn't keeping track of an object, it's set to a special reserved value: null in Visual C# and
Nothing in Visual Basic. So, when the program starts, both firstClicked and secondClicked are set to
null or Nothing , which means that the variables aren't keeping track of anything.

2. Modify your Click event handler to use the new firstClicked reference variable. Remove the last statement
in the label_Click() event handler method ( clickedLabel.ForeColor = Color.Black; ) and replace it with the
if statement that follows. (Be sure you include the comment, and the whole if statement.)
/// <summary>
/// Every label's Click event is handled by this event handler
/// </summary>
/// <param name="sender">The label that was clicked</param>
/// <param name="e"></param>
private void label_Click(object sender, EventArgs e)
{
Label clickedLabel = sender as Label;

if (clickedLabel != null)
{
// If the clicked label is black, the player clicked
// an icon that's already been revealed --
// ignore the click
if (clickedLabel.ForeColor == Color.Black)
return;

// If firstClicked is null, this is the first icon


// in the pair that the player clicked,
// so set firstClicked to the label that the player
// clicked, change its color to black, and return
if (firstClicked == null)
{
firstClicked = clickedLabel;
firstClicked.ForeColor = Color.Black;

return;
}
}
}

''' <summary>
''' Every label's Click event is handled by this event handler
''' </summary>
''' <param name="sender">The label that was clicked</param>
''' <param name="e"></param>
''' <remarks></remarks>
Private Sub label_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Label9.Click,
Label8.Click, Label7.Click, Label6.Click, Label5.Click, Label4.Click,
Label3.Click, Label2.Click, Label16.Click, Label15.Click, Label14.Click,
Label13.Click, Label12.Click, Label11.Click, Label10.Click, Label1.Click

Dim clickedLabel = TryCast(sender, Label)

If clickedLabel IsNot Nothing Then

' If the clicked label is black, the player clicked


' an icon that's already been revealed --
' ignore the click
If clickedLabel.ForeColor = Color.Black Then Exit Sub

' If firstClicked is Nothing, this is the first icon


' in the pair that the player clicked,
' so set firstClicked to the label that the player
' clicked, change its color to black, and return
If firstClicked Is Nothing Then
firstClicked = clickedLabel
firstClicked.ForeColor = Color.Black
Exit Sub
End If
End If

End Sub
3. Save and run your program. Choose one of the label controls, and its icon appears.
4. Choose the next label control, and notice that nothing happens. The program is already keeping track of the
first label that the player chose, so firstClicked isn't equal to null in Visual C# or Nothing in Visual
Basic. When your if statement checks firstClicked to determine if it's equal to null or Nothing , it finds
that it isn't, and it doesn't execute the statements in the if statement. So, only the first icon that's chosen
turns black, and the other icons are invisible, as shown in the following picture.

Matching game showing one icon


You'll fix this situation in the next step of the tutorial by adding a Timer control.
To continue or review
To go to the next tutorial step, see Step 6: Add a Timer.
To return to the previous tutorial step, see Step 4: Add a Click Event Handler to Each Label.
Step 6: Add a Timer
10/18/2019 • 7 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version
selector at the top left. We recommend upgrading to Visual Studio 2019. Download it here

Next, you add a Timer control to the matching game. A timer waits a specified number of milliseconds, and then
fires an event, referred to as a tick. This is useful for starting an action, or repeating an action on a regular basis. In
this case, you'll use a timer to enable players to choose two icons, and if the icons don't match, hide the two icons
again after a short period of time.
To add a timer
1. From the toolbox in Windows Forms Designer, choose Timer (in the Components category) and then
choose the ENTER key, or double-click the timer to add a timer control to the form. The timer's icon, called
Timer1 , should appear in a space below the form, as shown in the following picture.

Timer

NOTE
If the toolbox is empty, be sure to select the form designer, and not the code behind the form, before opening the
toolbox.

2. Choose the Timer1 icon to select the timer. In the Proper ties window, switch from viewing events to
viewing properties. Then, set the timer's Inter val property to 750 , but leave its Enabled property set to
False . The Inter val property tells the timer how long to wait between ticks, or when it triggers its Tick
event. A value of 750 tells the timer to wait three quarters of a second (750 milliseconds) before it fires its
Tick event. You'll call the Start() method to start the timer only after the player chooses the second label.
3. Choose the timer control icon in Windows Forms Designer and then choose the ENTER key, or double-click
the timer, to add an empty Tick event handler. Either replace the code with the following code, or manually
enter the following code into the event handler.
/// <summary>
/// This timer is started when the player clicks
/// two icons that don't match,
/// so it counts three quarters of a second
/// and then turns itself off and hides both icons
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void timer1_Tick(object sender, EventArgs e)
{
// Stop the timer
timer1.Stop();

// Hide both icons


firstClicked.ForeColor = firstClicked.BackColor;
secondClicked.ForeColor = secondClicked.BackColor;

// Reset firstClicked and secondClicked


// so the next time a label is
// clicked, the program knows it's the first click
firstClicked = null;
secondClicked = null;
}

''' <summary>
''' This timer is started when the player clicks
''' two icons that don't match,
''' so it counts three quarters of a second
''' and then turns itself off and hides both icons
''' </summary>
''' <remarks></remarks>
Private Sub Timer1_Tick() Handles Timer1.Tick

' Stop the timer


Timer1.Stop()

' Hide both icons


firstClicked.ForeColor = firstClicked.BackColor
secondClicked.ForeColor = secondClicked.BackColor

' Reset firstClicked and secondClicked


' so the next time a label is
' clicked, the program knows it's the first click
firstClicked = Nothing
secondClicked = Nothing

End Sub

The Tick event handler does three things: First, it makes sure the timer isn't running by calling the Stop()
method. Then it uses two reference variables, firstClicked and secondClicked , to make the icons of the
two labels that the player chose invisible again. Finally, it resets the firstClicked and secondClicked
reference variables to null in Visual C# and Nothing in Visual Basic. This step is important because it's
how the program resets itself. Now it's not keeping track of any Label controls, and it's ready for the player
to choose a label again.
NOTE
A Timer object has a Start() method that starts the timer, and a Stop() method that stops it. When you set
the timer's Enabled property to True in the Proper ties window, it starts ticking as soon as the program begins.
But when you leave it set to False , it doesn't start ticking until its Start() method is called. Normally, a timer fires
its Tick event over and over again, using the Inter val property to determine how many milliseconds to wait
between ticks. You may have noticed how the timer's Stop() method is called inside the Tick event. That puts the
timer into one shot mode, meaning that when the Start() method is called, it waits for the specified interval,
triggers a single Tick event, and then stops.

4. To see the new timer in action, go to the code editor and add the following code to the top and bottom of
the label_Click() event handler method. (You're adding an if statement to the top, and three statements
to the bottom; the rest of the method stays the same.)

/// <summary>
/// Every label's Click event is handled by this event handler
/// </summary>
/// <param name="sender">The label that was clicked</param>
/// <param name="e"></param>
private void label_Click(object sender, EventArgs e)
{
// The timer is only on after two non-matching
// icons have been shown to the player,
// so ignore any clicks if the timer is running
if (timer1.Enabled == true)
return;

Label clickedLabel = sender as Label;

if (clickedLabel != null)
{
// If the clicked label is black, the player clicked
// an icon that's already been revealed --
// ignore the click
if (clickedLabel.ForeColor == Color.Black)
return;

// If firstClicked is null, this is the first icon


// in the pair that the player clicked,
// so set firstClicked to the label that the player
// clicked, change its color to black, and return
if (firstClicked == null)
{
firstClicked = clickedLabel;
firstClicked.ForeColor = Color.Black;
return;
}

// If the player gets this far, the timer isn't


// running and firstClicked isn't null,
// so this must be the second icon the player clicked
// Set its color to black
secondClicked = clickedLabel;
secondClicked.ForeColor = Color.Black;

// If the player gets this far, the player


// clicked two different icons, so start the
// timer (which will wait three quarters of
// a second, and then hide the icons)
timer1.Start();
}
}
''' <summary>
''' Every label's Click event is handled by this event handler
''' </summary>
''' <param name="sender">The label that was clicked</param>
''' <param name="e"></param>
''' <remarks></remarks>
Private Sub label_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Label9.Click,
Label8.Click, Label7.Click, Label6.Click, Label5.Click, Label4.Click,
Label3.Click, Label2.Click, Label16.Click, Label15.Click, Label14.Click,
Label13.Click, Label12.Click, Label11.Click, Label10.Click, Label1.Click

' The timer is only on after two non-matching


' icons have been shown to the player,
' so ignore any clicks if the timer is running
If Timer1.Enabled Then Exit Sub

Dim clickedLabel = TryCast(sender, Label)

If clickedLabel IsNot Nothing Then


' If the clicked label is black, the player clicked
' an icon that's already been revealed --
' ignore the click
If clickedLabel.ForeColor = Color.Black Then Exit Sub

' If firstClicked is Nothing, this is the first icon


' in the pair that the player clicked,
' so set firstClicked to the label that the player
' clicked, change its color to black, and return
If firstClicked Is Nothing Then
firstClicked = clickedLabel
firstClicked.ForeColor = Color.Black
Exit Sub
End If

' If the player gets this far, the timer isn't


' running and firstClicked isn't Nothing,
' so this must be the second icon the player clicked
' Set its color to black
secondClicked = clickedLabel
secondClicked.ForeColor = Color.Black

' If the player gets this far, the player


' clicked two different icons, so start the
' timer (which will wait three quarters of
' a second, and then hide the icons)
Timer1.Start()
End If

End Sub

The code at the top of the method checks whether the timer was started by checking the value of the
Enabled property. That way, if the player chooses the first and second Label controls and the timer starts,
choosing a third label won't do anything.
The code at the bottom of the method sets the secondClicked reference variable to track the second Label
control that the player chose, and then it sets that label's icon color to black to make it visible. Then, it starts
the timer in one shot mode, so that it waits 750 milliseconds and then fires a single Tick event. The timer’s
Tick event handler hides the two icons and resets the firstClicked and secondClicked reference variables
so the form is ready for the player to choose another pair of icons.
5. Save and run your program. Choose an icon, and it becomes visible.
6. Choose another icon. It appears briefly, and then both icons disappear. Repeat this numerous times. The
form now keeps track of the first and second icons that you choose, and uses the timer to pause before
making the icons disappear.
To continue or review
To go to the next tutorial step, see Step 7: Keep Pairs Visible.
To return to the previous tutorial step, see Step 5: Add Label References.
Step 7: Keep Pairs Visible
10/18/2019 • 3 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version
selector at the top left. We recommend upgrading to Visual Studio 2019. Download it here

The game works well, as long as the player only chooses pairs of icons that don't match. But consider what should
happen when the player chooses a matching pair. Instead of making the icons disappear by turning on the timer
(using the Start() method), the game should reset itself so that it's no longer keeping track of any labels using
the firstClicked and secondClicked reference variables, without resetting the colors for the two labels that were
chosen.
To keep pairs visible
1. Add the following if statement to the label_Click() event handler method, near the end of the code just
above the statement where you start the timer. Take a close look at the code while adding it to the program.
Consider how the code works.

// If the player gets this far, the timer isn't


// running and firstClicked isn't null,
// so this must be the second icon the player clicked
// Set its color to black
secondClicked = clickedLabel;
secondClicked.ForeColor = Color.Black;

// If the player clicked two matching icons, keep them


// black and reset firstClicked and secondClicked
// so the player can click another icon
if (firstClicked.Text == secondClicked.Text)
{
firstClicked = null;
secondClicked = null;
return;
}

// If the player gets this far, the player


// clicked two different icons, so start the
// timer (which will wait three quarters of
// a second, and then hide the icons)
timer1.Start();
}
}
' If the player gets this far, the timer isn't
' running and firstClicked isn't Nothing,
' so this must be the second icon the player clicked
' Set its color to black
secondClicked = clickedLabel
secondClicked.ForeColor = Color.Black

' If the player clicked two matching icons, keep them


' black and reset firstClicked and secondClicked
' so the player can click another icon
If firstClicked.Text = secondClicked.Text Then
firstClicked = Nothing
secondClicked = Nothing
Exit Sub
End If

' If the player gets this far, the player


' clicked two different icons, so start the
' timer (which will wait three quarters of
' a second, and then hide the icons)
Timer1.Start()
End If
End Sub

The first line of the if statement you just added checks whether the icon in the first label that the player
chooses is the same as the icon in the second label. If the icons are identical, the program executes the three
statements between the curly braces in C# or the three statements within the if statement in Visual Basic.
The first two statements reset the firstClicked and secondClicked reference variables so that they no
longer keep track of any of the labels. (You may recognize those two statements from the timer's Tick event
handler.) The third statement is a return statement, which tells the program to skip the rest of the
statements in the method without executing them.
If programming in Visual C#, you may have noticed that some of the code uses a single equal sign ( = ),
while other statements use two equal signs ( == ). Consider why = is used in some places but == is used
in other places.
This is a good example that shows the difference. Take a careful look at the code between the parentheses in
the if statement.

firstClicked.Text = secondClicked.Text

firstClicked.Text == secondClicked.Text

Then look closely at the first statement in the block of code after the if statement.

firstClicked = Nothing

firstClicked = null;

The first of those two statements checks whether two icons are the same. Because two values are being
compared, the Visual C# program uses the == equality operator. The second statement actually changes
the value (called assignment), setting the firstClicked reference variable equal to null to reset it. That's
why it uses the = assignment operator instead. Visual C# uses = to set values, and == to compare them.
Visual Basic uses = for both variable assignment and comparison.
2. Save and run the program, and then start choosing icons on the form. If you choose a pair that doesn't
match, the timer's Tick event triggers, and both icons disappear. If you choose a matching pair, the new if
statement executes, and the return statement causes the method to skip the code that starts the timer, so
the icons stay visible, as shown in the following picture.

Matching game with visible icon pairs


To continue or review
To go to the next tutorial step, see Step 8: Add a Method to Verify Whether the Player Won.
To return to the previous tutorial step, see Step 6: Add a Timer.
Step 8: Add a Method to Verify Whether the Player
Won
10/18/2019 • 3 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version
selector at the top left. We recommend upgrading to Visual Studio 2019. Download it here

You've created a fun game, but it needs an additional item to finish it. The game should end when the player wins,
so you need to add a CheckForWinner() method to verify whether the player won.
To add a method to verify whether the player won
1. Add a CheckForWinner() method to the bottom of your code, below the timer1_Tick() event handler, as
shown in the following code.

/// <summary>
/// Check every icon to see if it is matched, by
/// comparing its foreground color to its background color.
/// If all of the icons are matched, the player wins
/// </summary>
private void CheckForWinner()
{
// Go through all of the labels in the TableLayoutPanel,
// checking each one to see if its icon is matched
foreach (Control control in tableLayoutPanel1.Controls)
{
Label iconLabel = control as Label;

if (iconLabel != null)
{
if (iconLabel.ForeColor == iconLabel.BackColor)
return;
}
}

// If the loop didn’t return, it didn't find


// any unmatched icons
// That means the user won. Show a message and close the form
MessageBox.Show("You matched all the icons!", "Congratulations");
Close();
}
''' <summary>
''' Check every icon to see if it is matched, by
''' comparing its foreground color to its background color.
''' If all of the icons are matched, the player wins
''' </summary>
Private Sub CheckForWinner()

' Go through all of the labels in the TableLayoutPanel,


' checking each one to see if its icon is matched
For Each control In TableLayoutPanel1.Controls
Dim iconLabel = TryCast(control, Label)
If iconLabel IsNot Nothing AndAlso
iconLabel.ForeColor = iconLabel.BackColor Then Exit Sub
Next

' If the loop didn't return, it didn't find


' any unmatched icons
' That means the user won. Show a message and close the form
MessageBox.Show("You matched all the icons!", "Congratulations")
Close()

End Sub

The method uses another foreach loop in Visual C# or For Each loop in Visual Basic to go through each
label in the TableLayoutPanel. It uses the equality operator ( == in Visual C# and = in Visual Basic) to check
each label's icon color to verify whether it matches the background. If the colors match, the icon remains
invisible, and the player hasn't matched all of the icons remaining. In that case, the program uses a return
statement to skip the rest of the method. If the loop gets through all of the labels without executing the
return statement, that means that all of the icons on the form were matched. The program shows a
MessageBox to congratulate the player on winning, and then calls the form's Close() method to end the
game.
2. Next, have the label's Click event handler call the new CheckForWinner() method. Be sure that your program
checks for a winner immediately after it shows the second icon that the player chooses. Look for the line
where you set the second chosen icon's color, and then call the CheckForWinner() method right after that, as
shown in the following code.

// If the player gets this far, the timer isn't


// running and firstClicked isn't null,
// so this must be the second icon the player clicked
// Set its color to black
secondClicked = clickedLabel;
secondClicked.ForeColor = Color.Black;

// Check to see if the player won


CheckForWinner();

// If the player clicked two matching icons, keep them


// black and reset firstClicked and secondClicked
// so the player can click another icon
if (firstClicked.Text == secondClicked.Text)
{
firstClicked = null;
secondClicked = null;
return;
}
' If the player gets this far, the timer isn't
' running and firstClicked isn't Nothing,
' so this must be the second icon the player clicked
' Set its color to black
secondClicked = clickedLabel
secondClicked.ForeColor = Color.Black

' Check to see if the player won


CheckForWinner()

' If the player clicked two matching icons, keep them


' black and reset firstClicked and secondClicked
' so the player can click another icon
If firstClicked.Text = secondClicked.Text Then
firstClicked = Nothing
secondClicked = Nothing
Exit Sub
End If

3. Save and run the program. Play the game and match all of the icons. When you win, the program displays a
congratulatory MessageBox (as shown in the following picture), and then closes the box.

Matching game with MessageBox


To continue or review
To go to the next tutorial step, see Step 9: Try Other Features.
To return to the previous tutorial step, see Step 7: Keep Pairs Visible.
Step 9: Try Other Features
11/21/2019 • 2 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version selector
at the top left. We recommend upgrading to Visual Studio 2019. Download it here

To learn more, try changing icons and colors, adding a game timer, and adding sounds. To make the game more
challenging, try making the board bigger and adjusting the timer.
To try other features
Replace the icons and colors with ones you choose.

TIP
Try looking at the label's Forecolor property.

Add a game timer that tracks how long it takes for the player to win.

TIP
To do this, you can add a label to display the elapsed time on the form above the TableLayoutPanel, and add another
timer to the form to track the time. Use code to start the timer when the player starts the game, and stop the timer
after they match the last two icons.

Add a sound when the player finds a match, another sound when the player uncovers two icons that don't
match, and a third sound when the program hides the icons again.

TIP
To play sounds, you can use the System.media namespace. See Play Sounds in Windows Forms App (C# .NET) or How
To Play Audio In Visual Basic for more information.

Make the game more difficult by making the board bigger.

TIP
You'll need to do more than just add rows and columns to the TableLayoutPanel – you'll also need to consider the
number of icons you create.

Make the game more challenging by hiding the first icon if the player is too slow to respond and doesn't
choose the second icon before a certain amount of time.
To continue or review
If you get stuck or have programming questions, try posting your question on one of the MSDN forums.
See Visual Basic Forum and Visual C# Forum.
There are great, free video learning resources available to you. To learn more about programming in Visual
Basic, see Visual Basic Fundamentals: Development for Absolute Beginners. To learn more about
programming in Visual C#, see C# Fundamentals: Development for Absolute Beginners.
To return to the previous tutorial step, see Step 8: Add a Method to Verify Whether the Player Won.
Getting Started with C++ in Visual Studio
10/18/2019 • 4 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version selector
at the top left. We recommend upgrading to Visual Studio 2019. Download it here

By completing this walkthrough, you’ll become familiar with many of the tools and dialog boxes that you can use
when you develop applications with Visual Studio. You’ll create a simple "Hello, World"-style application while you
learn more about working in the integrated development environment (IDE).
This topic contains the following sections:
Sign In to Visual Studio
Create a simple application
Add Code to the Application
Debug and Test the application
Build a release version of the app

Sign In to Visual Studio


When you start Visual Studio for the first time, you are given the chance to sign in using a Microsoft account such
as Live or Outlook. Signing in allows your settings to be synchronized across all your devices. For more
information, see Signing in to Visual Studio
Figure 1: Visual Studio IDE
After you open Visual Studio, you can see the three basic parts of the IDE: tool windows, menus and toolbars, and
the main window space. Tool windows are docked on the left and right sides of the app window, with Quick
Launch , the menu bar, and the standard toolbar at the top. The center of the application window contains the Star t
Page . When you open a solution or project, editors and designers appear in this space. When you develop an
application, you’ll spend most of your time in this central area.

Create a simple application


When you create an app in Visual Studio, you first create a project and a solution. For this example, you’ll create a
Windows console application.
To create a console app
1. On the menu bar, choose File , New , Project .

2. In the Visual C++ category, choose the Win32 Console Application template, and then name the project
GreetingsConsoleApp .
3. When the Win32 Application Wizard appears, choose the Finish button.

The GreetingsConsoleApp project and solution, with the basic files for a Win32 console app, are created and
automatically loaded into Solution Explorer . The GreetingsConsoleApp.cpp file is opened in the code
editor. The following items appear in Solution Explorer :
Figure 4: Project items
Add Code to the Application
Next, you'll add code to display the word "Hello" in the console window.
To display “Hello” in the console window
1. In the GreetingsConsoleApp.cpp file, enter a blank line before the line return 0; and then enter the
following code:

cout << "Hello\n";

A red squiggly line appears under cout . An error message appears if you point to it.

The error message also appears in the Error List window. You can display the window by, on the menu bar,
choosing View , Error List .
cout is included in the <iostream> header file.
2. To include the iostream header, enter the following code after #include "stdafx.h" :

#include \<iostream\>
using namespace std;

You probably noticed that a box appeared as you entered code, providing suggestions for the characters that
you entered. This box is part of C++ IntelliSense, which provides coding prompts, including listing class or
interface members and parameter information. You can also use code snippets, which are pre-defined blocks
of code. For more information, see Using IntelliSense and Code Snippets.
The red squiggly line under cout disappears when you fix the error.
3. Save the changes to the file.

Debug and Test the application


You can debug GreetingsConsoleApp to see whether the word "Hello" appears in the console window.
To debug the application
Start the debugger.

The debugger starts and runs the code. The console window (a separate window that looks like a command
prompt) appears for a few seconds but closes quickly when the debugger stops running. To see the text, you
need to set a breakpoint to stop program execution.
To add a breakpoint
1. Add a breakpoint from the menu bar at the line return 0; . You can also just click in the left margin to set a
breakpoint.
A red circle appears next to the line of code in the far left margin of the editor window.
2. Choose the F5 key to start debugging.
The debugger starts, and a console window appears showing the word Hello .

3. Press SHIFT + F5 to stop debugging.


For more information, see Console Projects.

Build a release version of the app


Now that you’ve verified that everything works, you can prepare a release build of the application.
To clean the solution files and build a release version
1. From the menu bar, delete intermediate files and output files that were created during previous builds.

2. Change the build configuration for GreetingsConsoleApp from Debug to Release .


3. Build the solution.

Congratulations on completing this walkthrough! If you want to explore more examples, see Visual Studio
Samples.

See Also
Walkthrough: Create a Simple Application Productivity Tips Visual Studio Samples Get Started Developing with
Visual Studio
Getting Started with Debugging in Visual Studio 2015
10/16/2020 • 11 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version selector
at the top left. We recommend upgrading to Visual Studio 2019. Download it here

Visual Studio 2015 provides a powerful integrated set of project build and debugging tools. In this topic, find out
how to start using the most basic set of debugging UI features.
Note: Links to more advanced features and platform- or feature-specific topics are at the bottom of this page.

My code doesn’t work. Help me, Visual Studio 2015!


So you’ve figured out the editor and you’ve created some code. Now, you want to start debugging that code. In
Visual Studio 2015, as with most IDEs, there are two phases to debugging: building the code to catch and resolve
project and compiler errors; and running that code in the environment to catch and resolve run-time and dynamic
errors.
Configuring a Build
There are two basic types of build configuration: Debug and Release . The first configuration produces a slower,
larger executable that allows for a richer interactive run-time debugging experience, but should never be shipped.
The second builds a faster, more optimized executable that’s appropriate to ship (at least from the perspective of
the compiler).
The default build configuration is Debug .

You can also specify a specific build platform to target, such as x86 (32-bit Intel CPUs), x64 (64-bit Intel CPUs), and
ARM (ARM CPUs, only supported for certain app types). The default is x86 for managed and native projects. To
change it, click on build platform dropdown and select a different platform or Configuration Manager…
You can specify a targeted build configuration using the Configuration Manager . Launch it, click the
Configuration or the CPU dropdown, and select New… to create a new build or platform.

Starting out, just use Debug and x86 as your build configuration and platform, respectively. When you’re done
coding and debugging, change the configuration to Release and target a specific platform. (Older versions of
Visual Studio provided an AnyCPU default platform for .Net code projects.)
Note: When you build your project, the configuration and platform values are also used to determine what project
directory path is created to store the executable. Typically, this is <path-to-project>\<project-name>\
<configuration>\<platform> . For example, a project with a configuration of Debug and a platform of x86
would be found under Projects\MyProjectNameHere\MyProjectNameHere\bin\Debug\x86 . This can be useful if you have
your own tools or scripts that manage these built executables.
Building your Code
With your build configured, it’s time to actually build your project. The easiest way to do it to press F7, but you can
also start the build by selecting Build->Build Solution from the main menu.

You can observe the build process in the Output status window at the bottom of the Visual Studio UI. Errors,
warnings, and build operations are displayed here. If you have errors (or if you have a warnings above a configured
level), your build will fail. You can click on the errors and warnings to go to the line where they occurred. Rebuild
your project by pressing either F7 again (to recompile only the files with errors) or Ctrl+Alt+F7 (for a clean and
complete rebuild).
There are two build tabbed windows in the results window below the editor: the Output window, which contains
the raw compiler output (including error messages); and the Error List window, which provides a sortable and
filterable list of all errors and warnings.
When successful, you will see results like this in the Output window.

Reviewing the Error List


Unless you’ve made no modifications to code you’ve previously and successfully compiled, you probably have an
error. If you’re new to coding, you probably have lots of them. Errors are sometimes obvious, such a simple syntax
error or incorrect variable name, and sometimes they are difficult to understand, with only a cryptic code to guide
you. For a cleaner view of the issues, navigate to the bottom of the build Output window, and click the Error List
tab. This takes you to a more organized view of the errors and warnings for your project, and gives you some extra
options as well.

Click on the error line in the Error List window and jump to the line the error occurs in. (Or turn on line numbers
by clicking in the Quick Launch bar in the upper-right, typing “line numbers” into it, and pressing Enter. This is the
fastest way to get to Options window entry where you can turn on line numbers. Learn to use the Quick Launch
bar and save yourself a lot of UI clicks!)

Use Ctrl+G to quickly jump to the line number where the error occurred.
The error is identified by a red “squiggle” underscore. Hover over it for additional details. Make the fix and it will go
away, although you may introduce a new error with the correction. (This is called a “regression”.)
Walk through the error list and address all the errors in your code.

Reviewing Errors in Detail


Many errors may make no sense to you, phrased as they are in the terms of the compiler. In those cases, you will
need additional information. From the Error List window, you can do an automatic Bing search for more
information on the error (or warning) by right-clicking on the corresponding entry line and selecting Show Error
Help from the context menu.

This launches a tab inside Visual Studio 2015 that hosts the results of a Bing search for the error code and text. The
results are from many different sources on the Internet, and not all may be helpful.
Alternatively, you can click on the hyperlinked error code value in the Code column of the Error List . This will
launch a Bing search for just the error code.
Performing Static Code Analysis
“Static code analysis” is a fancy way of saying “automatically check my code for common problems that can lead to
run-time errors or problems in code management”. Get in the habit of running it once you’ve cleaned up the
obvious errors preventing build, and take some time to address the warnings it may produce. You’ll save yourself
some headaches down the road, as well as learn a few code style techniques.
Press Alt+F11 (or select Analyze->Run Code Analysis on Solution from the top menu) to start static code
analysis. This may take some time if you have a lot of code.

Any new or updated warnings will appear in the Error List tab at the bottom of the IDE. Click on the warnings to
jump to them.
The warnings will be identified with a bright yellow-green squiggle instead of a red one. Hover over them for more
detail, and right-click on them to get a context menu to assist in fixes or refactoring options.

Using Light Bulbs to Fix or Refactor Code


Light Bulbs are a new feature for Visual Studio 2015 that let you refactor code inline. They are an easy way to fix
common warnings quickly and effectively. To access them, right-click on a warning squiggle (or press Ctrl+. while
hovering over the squiggle), and then select Quick Actions .

You will see a list of possible fixes or refactors you can apply to that line of code.

Light Bulbs can be used wherever the code analyzers determine there is an opportunity to fix, refactor, or improve
your code. Click on any line of code, right-click to open the context menu, and select Quick Options (or, again, if
you prefer efficiency, press Ctrl+.). If there is area refactoring or improvement options available, they will be
displayed; otherwise, the message No quick options available here will be displayed in the lower-left corner bezel
of the IDE.

With experience, you can quickly use the arrow keys and Ctrl+. to check for Quick Option refactoring opportunities
and clean up your code!
For more information on Light Bulbs, read Perform quick actions with light bulbs.
Debugging Your Running Code
Now that you’ve successfully built your code and performed a little clean up, run it by pressing F5 or selecting
Debug->Star t Debugging . This will start your app in a debug environment so you can observe its behavior in
detail. The Visual Studio 2015 IDE changes while your app is running: the Output window is replaced by two new
ones (in the default window configuration), the Autos/Locals/Modules/Watch tabbed window and the Call
Stack/Breakpoints/Exception Settings/Output tabbed window. These windows have multiple tabs which allow
you to inspect and evaluate your app’s variables, threads, call stacks, and various other behaviors as it runs.

Try various actions with your app and observe the changes. If something appears abnormal, pause the app by
pressing Ctrl+Alt+Break (or click on the Pause button).

Press F5 to continue running the app (or click the Continue button).

You can stop your app by pressing Shift+F5 or by clicking the Stop button. Or, you can simply close the app’s main
window (or command line dialog).
If your code ran perfectly and exactly as expected, congratulations! Change the build configuration to Release and
rebuild it for deployment! (Professionals may want to jump to the bit on Unit Testing at the end, though.) However,
if it stops responding, or crashed, or gave you some strange results, you’ll need to find the source of those
problems and fix the bugs.
Setting Simple Breakpoints
Breakpoints are the most basic and essential feature of reliable debugging. A breakpoint indicates where Visual
Studio should suspend your running code so you can take a look at the values of variables, or the behavior of
memory, or whether or not a branch of code is getting run. You do NOT need to rebuild a project after setting and
removing breakpoints.
Set a breakpoint by clicking in the far margin of the line where you want the break to occur, or select the line of
code and press F9. When you run your code, it will stop before the instructions for this line of code are executed.

When the code breaks, the marked line of code has not executed yet. At this point, you may want to execute the
instructions for the line of code marked by the breakpoint and inspect the changed values. This is called “stepping
into” the code. If the marked code is a method call, you can step into it by pressing F11. You can also “step over” the
line of code by pressing F10. For more details on breakpoint step actions, read Navigating through Code with the
Debugger.
Common uses for breakpoints include:
1. To narrow down the source of a crash or program not responding, scatter them throughout and around the
code of the method call you think is causing the failure. As you step through the code, remove and then
reset the breakpoints closer together until you find the offending line of code.
2. When you introduce new code, set a breakpoint at the beginning of it and step through the code to make
sure it is behaving as expected.
3. If you have implemented a complicated behavior, set breakpoint(s) for the algorithmic code so you can
inspect the values of the variables and data when the program breaks.
4. If you are writing C or C++ code, use breakpoints to stop the code so you can inspect address values (look
for NULL) and reference counts when debugging for memory-related failures.
For more information on using breakpoints, read Using Breakpoints
Setting Conditional Breakpoints
If you have a breakpoint in a loop or recursion, or if you have a lot of breakpoints which you frequently step
through, use a conditional breakpoint to ensure that your code is suspended ONLY when specific conditions are
met. Otherwise, you’ll be pressing F11 an awful lot.
To set a conditional breakpoint and suspend your code when a variable is set to a certain value or passes a certain
threshold, click in the margin to set a breakpoint, and then select the “cog” from the hover menu that appears.

You will see a dialog that looks like this where you can set specific conditions for the break to occur.
For more detail on how to declare the expressions used to evaluate conditional breakpoints, check out the
Channel9 video Breakpoint Configuration Experience in Visual Studio 2015.
Inspecting Your Code at Run-time
When your running code hits a breakpoint and halts, you can inspect your variables and call stacks to determine
what is going on. Are the values in the ranges you expect to see? Are calls being made in the right order?

Hover over a variable to see the value(s) and reference(s) it currently contains. If you see a value you didn’t expect,
you probably have a bug in the preceding or calling lines of code. Move breakpoints up or add conditions to the
existing breakpoints to narrow your search further.
Additionally, Visual Studio 2015 displays the Diagnostic Tools window, where you can observe your app’s CPU and
memory usage over time. Use them to look for unanticipated heavy CPU usage or memory allocation. Use it in
conjunction with the Watch window and breakpoints to determine what’s causing unexpected heavy usage or
unreleased resources.
Running Unit Tests
Unit tests are programs that exercise code paths in your app or service. Visual Studio 2015 installs the Microsoft
unit testing frameworks for both managed and native code. Use a unit testing framework to create unit tests, run
them, and report the results of these tests. Rerun unit tests when you make changes to test that your code is still
working correctly. When you use Visual Studio 2015 Enterprise, you can run tests automatically after every build.
To get started, read Generate unit tests for your code with IntelliTest.
To learn more about unit tests in Visual Studio 2015 and how they can help you create better quality code, read
Unit Test Basics.

See Also
Debugging in Visual Studio Debugger Settings and Preparation Debug 64-Bit Applications Debugger Basics
Solutions and Projects in Visual Studio
10/18/2019 • 2 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version
selector at the top left. We recommend upgrading to Visual Studio 2019. Download it here

When you create an app, application, website, Web App, script, plug-in, etc in Visual Studio, you start with a
project. In a logical sense, a project contains of all the source code files, icons, images, data files and anything else
that will be compiled into an executable program or web site, or else is needed in order to perform the
compilation. A project also contains all the compiler settings and other configuration files that might be needed
by various services or components that your program will communicate with.
In a literal sense, a project is an XML file (*.vbproj, *.csproj, *.vcxproj) that defines a virtual folder hierarchy along
with paths to all the items it "contains" and all the build settings. In Visual Studio, the project file is used by
Solution Explorer to display the project contents and settings. When you compile your project, the MSBuild
engine consumes the project file to create the executable. You can also customize projects to product other kinds
of output.
A project is contained, in a logical sense and in the file system, within a solution, which may contain one or more
projects, along with build information, Visual Studio window settings, and any miscellaneous files that aren't
associated with any project. In a literal sense, the solution is a text file with its own unique format; it is generally
not intended to be edited by hand.
A solution has an associated *.suo file that stores settings, preferences and configuration information for each
user that has worked on the project.
The following diagram shows the relationship between projects and solutions, and the items they logically
contain.

You can also create custom project and item templates. For more information, see Creating Project and Item
Templates.

Creating new projects


The easiest way to create a new project is to start with a pre-defined project template, which consists of a basic
set of pre-generated code files, config files, assets, and settings that get you started creating a particular type of
application or website in a particular programming language. These templates are what you see in the New
Project Dialog when you choose File | New | Project or File | New | Web Site from the main menu, and
then navigate. For more information, see Creating Solutions and Projects and NIB Creating Projects from
Templates.

Managing projects in Solution Explorer


After you create a new project, you use Solution Explorer to view and manage projects and solutions and their
associated items. The following illustration shows Server Explorer with a C# solution that contains two projects.

In This Section
Creating Solutions and Projects
Adding and Removing Project Items
Managing Project and Solution Properties
Managing references in a project
Application Properties
Managing Assembly and Manifest Signing
How to: Specify an Application Icon (Visual Basic, C#)
Targeting a Specific .NET Framework Version
Creating Project and Item Templates
See Also
Visual Studio IDE
Creating Solutions and Projects
1/10/2020 • 4 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version
selector at the top left. We recommend upgrading to Visual Studio 2019. Download it here

Projects are the logical containers for everything that's needed to build your application. When you create a
project by choosing File | New | Project from the main menu, Visual Studio creates a solution to contain it. You
can then add more new or existing projects to the solution if necessary. You can create projects from existing code
files and you can create temporary projects (.NET only) that will be deleted when you are done with them.

NOTE
The descriptions in this topic are based on the Visual Studio Community edition. The dialog boxes and menu commands you
see might differ from those described here, depending on your settings or Visual Studio edition. To change your settings,
choose Impor t and Expor t Settings on the Tools menu. For more information, see Customizing Development Settings in
Visual Studio.

Create a project from an installed project template


File | New | Project from the main menu to bring up the New Project dialog. In the left pane under Intalled |
Templates chose the programming language and platform or technology, then choose from the available
templates in the middle pane.
In the New Project dialog, the Solution drop-down gives you the option to create the new project in a new or
existing solution, or in a new instance of Visual Studio.

Create a project from existing code files


If you have a collection of loose source files, you can easily create a project that contains them. Choose File | New
|Project From Existing Code to start the Create Project from Existing Code Files Wizard and follow the
prompts.

TIP
This option works best for relatively simple collections of files.

Create a temporary project (C# and Visual Basic)


By working with temporary projects, you can create and experiment with a .NET project without specifying a disk
location. When you create a project, you just select a project type and template and specify a name in the New
Project dialog box. At any time while you are working with the temporary project, you can save it, or you can
discard it.

Create a .NET project that targets a specific version of the .NET


Framework
You can create a project to target earlier versions of the .NET Framework by using the .NET Framework version
drop-down menu at the top of the New Project dialog box. Set this value before selecting a project template, as
only templates compatible with that .NET Framework version will appear in the list.
You must have .NET Framework 3.5 installed on your system to access framework versions earlier than 4.0.

Downloading Sample Solutions


You can use Visual Studio to download and install sample solutions from the MSDN Code Gallery.
You can download the samples individually, or you can download a Sample Pack, which contains related samples
that share a technology or topic. You'll receive a notification when source code changes are published for any
sample that you download.
For more information, see Visual Studio Samples.

Adding single files at the solution level


Sometimes you might have a file that multiple projects refer to, or that contains text or miscellaneous data that
logically belongs at the solution level rather than under a specific project. To add a single item to a solution:
1. Right-click on the solution node in Solution Explorer and choose Add | New Item or Add | Existing Item .

Creating Empty Solutions


Although a project must reside in a solution, you can create a solution that has no projects.
To create an empty solution
1. On the File menu, click New and then click New Project .
2. In the left pane, select Installed , select Other Project Types , and then select Visual Studio Solutions
from the expanded list.
3. In the middle pane, select Blank Solution .
4. Set the Name and Location values for your solution, then click OK .
After you create an empty solution, you can add new or existing projects or items to it by clicking Add New
Item or Add Existing Item on the Project menu.
Deleting Solutions
You can delete a solution permanently, but not by using Visual Studio. Before you delete a solution, move any
projects that you might want to use again in another solution. Then use File Explorer to delete the directory that
contains the .sln and .suo solution files.

NOTE
The .suo file is a hidden file that is not displayed under default File Explorer settings.

To d e l e t e a so l u t i o n

1. In Solution Explorer , right-click the solution to delete, and select Open folder in File Explorer .
2. In File Explorer, navigate up one level.
3. Select the directory containing the solution and press Delete.
See Also
Solutions and Projects NIB How to: Create Multi-Project Solutions
Adding and Removing Project Items
10/18/2019 • 2 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version selector
at the top left. We recommend upgrading to Visual Studio 2019. Download it here

You can add or remove projects and project items by right-clicking on the project or solution node in Solution
Explorer , and choosing Add or Remove . Removing a project from a solution, or an item from a project, does not
delete it from disk or source control unless you select the option to delete it permanently.

See Also
Solutions and Projects Managing Project and Solution Properties
Managing Project and Solution Properties
10/18/2019 • 2 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version selector
at the top left. We recommend upgrading to Visual Studio 2019. Download it here

Projects have properties that govern many aspects of compilation, debugging, testing and deploying. Some
properties are common among all project types, and some are unique to specific languages or platforms. You
access project properties by right-clicking the project node in Solution Explorer and choosing Properties, or by
typing properties into the QuickLaunch search box in the menu bar.

.NET projects also have a properties node in the project tree itself.

TIP
Solutions have a few properties, and so do project items; these properties are accessed in the Properties Window, not
Project Designer .

Project Properties
Project Properties are organized into groups and each group has its own property page, and the pages might be
different for different languages and project types.
C# and Visual Basic projects
In C# and Visual Basic projects, properties are exposed in the Project Designer . The following illustration shows
the Build property page for a WPF project in C#:

For information about each of the property pages in Project Designer, see Project Properties Reference.
C++ and JavaScript projects
C++ and JavaScript projects have a different user interface for managing project properties. This illustration shows
a C++ project property page (JavaScript pages are similar):

For information about C++ project properties, see Working with Project Properties. For more information about
JavaScript properties, see Property Pages, JavaScript.

Solution Properties
To access properties on the solution, right click the solution node in Solution Explorer and choose Proper ties . In
the dialog, you can set project configurations for Debug or Release builds, choose which projects(s) should be the
startup project when F5 is pressed, and set code analysis options.

See Also
Solutions and Projects in Visual Studio
Managing references in a project
10/18/2019 • 6 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version
selector at the top left. We recommend upgrading to Visual Studio 2019. Download it here

Before you write code against an external component or connected service, your project must first contain a
reference to it. A reference is essentially an entry in a project file that contains the information that Visual Studio
needs to locate the component or the service.
To add a reference, right click on the References node in Solution Explorer and choose Add Reference . For more
information, see How to: Add or Remove References By Using the Reference Manager.

You can make a reference to the following types of components/services:


Windows Store app references
.NET Framework class libraries or assemblies
COM components
Other assemblies or class libraries of projects in the same solution
XML Web services

Windows Store App References


Project References
Universal Windows Platform (UWP) projects that target Windows 10 can create references to other UWP projects
in the solution, or to Windows Store projects or binaries that target Windows 8.1, provided that these projects do
not use APIs that have been deprecated in Windows 10. For more information, see Move from Windows Runtime
8 to UWP.
If you choose to retarget Windows 8.1 projects to Windows 10, see Porting, Migrating, and Upgrading Visual
Studio Projects
Extension SDK References
Visual Basic, C#, C++ and JavaScript Windows Store projects that target the Universal Windows Platform (UWP)
can reference Extension SDKs that target Windows 8.1, as long as these Extension SDKs do not use APIs that have
been deprecated in Windows 10. Please check the Extension SDK vendor site to find out whether it can be
referenced by Windows Store projects that target UWP.
If you determine that the Extension SDK being referenced by your app is not supported, then you need to perform
the following steps:
1. Look at the name of the project that is causing the error. The platform your project is targeting is noted in
parentheses next to the project name. For example, MyProjectName (Windows 8.1) means that your
project MyProjectName is targeting platform version Windows 8.1.
2. Go to the site of the vendor who owns the unsupported Extension SDK and install the version of the
Extension SDK with dependencies that are compatible with the version of the platform your project is
targeting.

NOTE
One way to find out whether an Extension SDK has dependencies on other Extension SDKs is to restart Visual Studio,
create a new C# Windows Store project, right-click on the project and choose Add Reference , go to the Windows
tab, go to the Extensions sub-tab, select the Extension SDK and look at the right pane in the Reference Manager .
If it has dependencies, they will be listed there.

IMPORTANT
If your project is targeting Windows 10, and the Extension SDK installed in the previous step has a dependency on
the Microsoft Visual C++ Runtime Package, the version of Microsoft Visual C++ Runtime Package that is compatible
with Windows 10 is v14.0 and is installed with Visual Studio 2015.

3. If the Extension SDK you installed in the previous step has dependencies on other Extension SDKs, go to the
site(s) of the vendor(s) who own the dependencies and install the versions of these dependencies that are
compatible with the version of the platform your project is targeting.
4. Restart Visual Studio and open your app.
5. Right-click on the References node in the project that caused the error and choose Add Reference
6. Click the Windows tab and then the Extensions sub-tab, then uncheck the checkboxes for the old
Extension SDKs and check the checkboxes for the new Extension SDKs. Click OK .

Adding a Reference at Design Time


When you make a reference to an assembly in your project, Visual Studio searches for the assembly in the
following locations:
The current project directory. (You can find these assemblies by using the Browse tab.)
Other project directories in the same solution. (You can find these assemblies on the Projects tab.)
NOTE
All projects contain an implied reference to mscorlib. Visual Basic projects contain an implied reference to
Microsoft.VisualBasic .

All projects in Visual Studio contain an implied reference to System.Core , even if System.Core is removed from the list of
references.

References to Shared Components at Run Time


At run time, components must be either in the output path of the project or in the Global Assembly Cache (GAC). If
the project contains a reference to an object that is not in one of these locations, you must copy the reference to
the output path of the project when you build the project. The CopyLocal property indicates whether this copy has
to be made. If the value is True , the reference is copied to the project directory when you build the project. If the
value is False , the reference is not copied.
If you deploy an application that contains a reference to a custom component that is registered in the GAC, the
component will not be deployed with the application, regardless of the CopyLocal setting. In earlier versions of
Visual Studio, you could set the CopyLocal property on a reference to ensure that the assembly was deployed.
Now, you must manually add the assembly to the \Bin folder. This puts all custom code under scrutiny, reducing
the risk of publishing custom code with which you are not familiar.
By default, the CopyLocal property is set to False if the assembly or component is in the global assembly cache or
is a framework component. Otherwise, the value is set to True . Project-to-project references are always set to
True .

Referencing a Project or Assembly That Targets a Different Version of


the .NET Framework
You can create applications that reference projects or assemblies that target a different version of the .NET
Framework. For example, you could create an application that targets the .NET Framework 4 Client Profile that
references an assembly that targets .NET Framework 2.0. If you create a project that targets an earlier version of
the .NET Framework, you cannot set a reference in that project to a project or assembly that targets the .NET
Framework 4 Client Profile or .NET Framework version 4.
For more information, see Targeting a Specific .NET Framework Version.

Project-to-Project References
Project-to-project references are references to projects that contain assemblies; you create them by using the
Project tab. Visual Studio can find an assembly when given a path to the project.
When you have a project that produces an assembly, you should reference the project and not use a file reference
(see below). The advantage of a project-to-project reference is that it creates a dependency between the projects in
the build system. The dependent project will be built if it has changed since the last time the referencing project
was built. A file reference does not create a build dependency, so it is possible to build the referencing project
without building the dependent project, and the reference can become obsolete. (That is, the project can reference
a previously built version of the project.) This can result in several versions of a single DLL being required in the
bin directory, which is not possible. When this conflict occurs, you will see a message such as Warning: the
dependency 'file' in project 'project' cannot be copied to the run directory because it would overwrite the
reference 'file.'. For more information, see Troubleshooting Broken References and How to: Create and Remove
Project Dependencies.
NOTE
A file reference instead of a project-to-project reference is created if the target version of the .NET Framework of one project
is version 4.5, and the target version of the other project is version 2, 3, 3.5, or 4.0.

File References
File references are direct references to assemblies outside the context of a Visual Studio project; you create them
by using the Browse tab of the Reference Manager . Use a file reference when you just have an assembly or
component and don't have the project that creates it as output.

See Also
Troubleshooting Broken References Programming with Assemblies How to: Add or Remove References By Using
the Reference Manager
How to: Add or Remove References By Using the
Reference Manager
1/10/2020 • 13 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version selector
at the top left. We recommend upgrading to Visual Studio 2019. Download it here

You can use the Reference Manager dialog box to add and manage references to components that you,
Microsoft, or another company developed. If you're developing a Universal Windows app, your project
automatically references all of the correct Windows SDK DLLs. If you are developing a .NET application, your
project automatically references mscorlib.dll. Some .NET APIs are exposed in components that you have to add
manually. References to COM components or custom components have to be added manually.

Adding and Removing a Reference


To Add a Reference
1. In Solution Explorer , right-click on the References node and choose Add Reference .
2. Specify the references to add, and then choose the OK button.
Reference Manager opens and lists the available references by group. The project type determines which
of the following groups appear:
Assemblies, with the Framework and Extensions subgroups.
Solution, with the Projects subgroup.
Windows, with the Core and Extensions subgroups. You can explore the references in the Windows SDK or
extension SDKs by using the Object Browser .
Browse, with the Recent subgroup.

Assemblies tab
The Assemblies tab lists all .NET Framework assemblies that are available for referencing. The Assemblies tab
doesn’t list any assemblies from the global assembly cache (GAC) because assemblies in the GAC are part of the
run-time environment. If you deploy or copy an application that contains a reference to an assembly that’s
registered in the GAC, the assembly won’t be deployed or copied with the application, regardless of the Copy Local
setting. For more information, see Project References.
When you manually add a reference to any of the EnvDTE namespaces (EnvDTE, EnvDTE80, EnvDTE90, EnvDTE90a,
or EnvDTE100), set the Embed Interop Types property of the reference to False in the Properties window. Setting
this property to True can cause build issues because of certain EnvDTE properties that can’t be embedded.
All desktop projects contain an implicit reference to mscorlib. Visual Basic projects contain an implicit reference to
Microsoft.VisualBasic. In Visual Studio 2012, all projects contain an implicit reference to System.Core, even if it’s
removed from the list of references.
If a project type doesn’t support Assemblies, the tab won’t appear in the Reference Manager dialog box.
The Assemblies tab consists of two sub-tabs:
1. Framework lists all assemblies that constitute the targeted Framework.
Advertised assemblies are in the Full Framework and enumerated in the Framework list when your
project targets a Profile of the targeted Framework. Advertised assemblies are grey to differentiate
them from the assemblies that exist in the targeted Framework profile of the project. For example, if a
project targets .NET Framework 4 Client, the Framework list shows advertised assemblies from .NET
Framework 4. When a user adds an advertised assembly, the user is notified that, after the
Reference Manager dialog box is closed, the project will be retargeted to the .NET Framework 4
and the advertised assembly will be added.
Projects for Windows 8.x Store apps contain references to all of the assemblies in the targeted .NET
for Windows 8.x Store apps by default on project creation. In managed projects, a read-only node
under the References folder in Solution Explorer indicates the reference to the entire Framework.
Accordingly, the Framework tab won’t enumerate any of the assemblies from the Framework and
instead display the following message: “All of the Framework assemblies are already referenced.
Please use the Object Browser to explore the references in the Framework.” For desktop projects, the
Framework tab enumerates assemblies from the targeted Framework, and the user must add the
references that the application requires.
2. Extensions lists all assemblies that external vendors of components and controls have developed to extend
the targeted Framework. Depending on the purpose of the user application, it might need these assemblies.
Extensions is populated by enumerating the assemblies that are registered in the following locations:

32-bit machine:
HKEY_CURRENT_USER\SOFTWARE\Microsoft\[Target Framework Identifier]\v[Target Framework
Version]\AssemblyFoldersEx\[UserComponentName]\@default=[Disk location of assemblies]
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\[Target Framework Identifier]\v[Target Framework
Version]\AssemblyFoldersEx\[UserComponentName]\@default=[Disk location of assemblies]
64-bit machine:
HKEY_CURRENT_USER\SOFTWARE\Wow6432Node\Microsoft\[Target Framework Identifier]\v[Target Framework
Version]\AssemblyFoldersEx\[UserComponentName]\@default=[Disk location of assemblies]
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\[Target Framework Identifier]\v[Target
Framework Version]\AssemblyFoldersEx\[UserComponentName]\@default=[Disk location of assemblies]
And older versions of the [Target Framework Identifier]

For example, if a project targets the .NET Framework 4 on a 32-bit machine, Extensions will
enumerate assemblies that are registered under
\Microsoft\.NETFramework\v4.0\AssemblyFoldersEx\,
\Microsoft\.NETFramework\v3.5\AssemblyFoldersEx\,
\Microsoft\.NETFramework\v3.0\AssemblyFoldersEx\, and
\Microsoft\.NETFramework\v2.0\AssemblyFoldersEx\.
Some components in the list may not be shown, depending on the .NET Framework version of your project.
This can occur under the following conditions:
A component that uses a recent version of the .NET Framework is incompatible with a project that targets an
earlier version of the .NET Framework.
For information about how to change the target .NET Framework version for a project, see How to: Target a
Version of the .NET Framework.
A component that uses .NET Framework 4 is incompatible with a project that targets the .NET Framework
4.5.
When you create a new application, some projects target the .NET Framework 4.5 by default. For more
information, see .NET Framework Client Profile.
You should avoid adding file references to outputs of another project in the same solution, because doing
this may cause compilation errors. Instead, use the Projects tab of the Add Reference dialog box to create
project-to-project references. This makes team development easier by enabling better management of the
class libraries you create in your projects. For more information, see Troubleshooting Broken References.

NOTE
In Visual Studio 2015, a file reference instead of a project reference is created if the target version of the .NET
Framework of one project is version 4.5, and the target version of the other project is version 2, 3, 3.5, or 4.0.

To display an assembly in the Add Reference dialog box


Move or copy the assembly to one of the following locations:
The current project directory. (You can find these assemblies by using the Browse tab.)
Other project directories in the same solution. (You can find these assemblies by using the Projects
tab.)
- or -
Set a registry key that specifies the location of assemblies to display:
For a 32-bit operating system, add one of the following registry keys.
[HKEY_CURRENT_USER\SOFTWARE\Microsoft\.NETFramework\VersionMinimum\AssemblyFoldersE
x\MyAssemblies]@="AssemblyLocation"
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\VersionMinimum\AssemblyFolders
Ex\MyAssemblies]@="AssemblyLocation"
For a 64-bit operating system, add one of the following registry keys in a 32-bit registry hive.
[HKEY_CURRENT_USER\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\VersionMinimum\A
ssemblyFoldersEx\MyAssemblies]@="AssemblyLocation"
[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\VersionMinimum\
AssemblyFoldersEx\MyAssemblies]@="AssemblyLocation"
VersionMinimum is the lowest .NET Framework version that applies. If VersionMinimum is v3.0,
folders specified in AssemblyFoldersEx apply to projects that target .NET Framework 3.0 and later.
AssemblyLocation is the directory of the assemblies that you want to appear in the Add Reference
dialog box, for example, C:\MyAssemblies\.
Creating the registry key under the HKEY_LOCAL_MACHINE node allows all users to see the
assemblies in the specified location in the Add Reference dialog box. Creating the registry key
under the HKEY_CURRENT_USER node affects only the setting for the current user.
Open the Add Reference dialog box again. The assemblies should appear on the .NET tab. If they do
not, make sure that the assemblies are located in the specified AssemblyLocation directory, restart
Visual Studio, and try again.

COM tab
The COM tab lists all COM components that are available for referencing. If you want to add a reference to a
registered COM DLL that contains an internal manifest, unregister the DLL first. Otherwise, Visual Studio adds the
assembly reference as an ActiveX Control instead of as a native DLL.
If a project type doesn’t support COM, the tab won’t appear in the Reference Manager dialog box.

Solution tab
The Solution tab lists all compatible projects within the current solution, in the Projects sub-tab.
A project can reference another project that targets a different version of the .NET Framework. For example, you
could create a project that targets the .NET Framework 4 but that references an assembly that’s been built for the
.NET Framework 2. However, the .NET Framework 2 project can’t reference a .NET Framework 4 project. For more
information, see Targeting a Specific .NET Framework Version.
A project that targets the .NET Framework 4 is incompatible with a project that targets the .NET Framework 4 Client
Profile.
In Visual Studio 2012, a file reference instead of a project reference is created if one project targets the .NET
Framework 4 and another project targets an earlier version.
A project that targets the .NET for Windows 8.x Store apps can’t add a project reference to a project that targets the
.NET Framework and vice versa.

Windows tab
The Windows tab lists all SDKs that are specific to platforms on which Windows operating systems run.
You can generate a WinMD file in Visual Studio in two ways:
Windows 8.x Store app managed projects : Windows 8.x Store app projects can output WinMD binaries
by setting Project Properties | Output Type = WinMD File. The WinMD filename must be the superset
namespace of all the namespaces that exist within it. For example, if a project consists of namespaces A.B
and A.B.C, the possible names for its outputted WinMD are A.winmd and A.B.winmd. If a user enters a
Project Properties | Assembly Name or Project Properties | Namespace value that’s disjoint from the set of
namespaces in the project or there is no superset namespace within a project, a build warning is generated:
'A.winmd' isn’t a valid .winmd file name for this assembly. All types within a Windows Metadata file must
exist in a sub namespace of the file name. Types that don’t exist in a sub namespace of the file name won’t
be able to be located at runtime. In this assembly, the smallest common namespace is 'CSWSClassLibrary1'.
A desktop Visual Basic or Visual C# project can only consume WinMDs that are generated by using the
Windows 8 SDKs, which are known as first-party WinMDs, and can’t generate WinMDs.
Windows 8.x Store app native projects : A native WinMD file consists of only metadata. Its
implementation exists in a separate DLL file. One can produce native binaries by choosing the Windows
Runtime Component project template in the New Project dialog box or by starting from a blank project
and modifying the project properties to generate a WinMD file. If the project consists of disjoint
namespaces, a build error will tell the user to combine their namespaces or run the MSMerge tool.
The Windows tab consists of two subgroups.
Core Subgroup
The Core subgroup lists all of the WinMDs (for Windows Runtime elements) in the SDK for the targeted version of
Windows.
Windows 8.x Store app projects contain references to all of the WinMDs in the Windows 8 SDK by default on
project creation. In managed projects, a read-only node under the References folder in Solution Explorer
indicates the reference to the entire Windows 8 SDK. Accordingly, the Core subgroup in the Reference Manager
won’t enumerate any of the assemblies from the Windows 8 SDK and instead displays a message: “The Windows
SDK is already referenced. Please use the Object Browser to explore the references in the Windows SDK.”
In the desktop projects, the Core subgroup doesn’t appear by default. You can add the Windows Runtime by
opening the shortcut menu for the project node, choosing Unload Project , adding the following snippet, and re-
opening the project (on the project node, choose Reload Project ). When you invoke the Reference Manager
dialog box, the Core subgroup appears.

<PropertyGroup>
<TargetPlatformVersion>8.0</TargetPlatformVersion>
</PropertyGroup>

Make sure to select the Windows check box on this subgroup. You should then be able to use Windows Runtime
elements. However, you'll also want to add System.Runtime, in which the Windows Runtime defines some standard
classes and interfaces, such as IEnumerable, that are used throughout the Windows Runtime libraries. For
information about how to add System.Runtime, see Managed desktop apps and Windows Runtime.
Extensions Subgroup
Extensions lists the user SDKs that extend the targeted Windows platform. This tab appears for Windows 8.x Store
app projects only. Desktop projects won’t show this tab because they can consume only first-party .winmd files.
An SDK is a collection of files that Visual Studio treats as a single component. In the Extensions tab, SDKs that apply
to the project from which the Reference Manager dialog box was invoked are listed as single entries. When
added to a project, all of the SDK content is consumed by Visual Studio such that the user doesn’t need to take any
further actions to leverage the SDK contents in IntelliSense, toolbox, designers, Object Browser, build, deployment,
debugging, and packaging. For information about how to display your SDK in the Extensions tab, see Creating a
Software Development Kit.

NOTE
If a project references an SDK that depends on another SDK, Visual Studio won’t consume the second SDK unless the user
manually adds a reference to the second SDK. When a user chooses an SDK on the Extensions tab, the Reference
Manager dialog box helps the user identify SDK dependencies by listing not only the name and version of the SDK but also
the name of any SDK dependencies in the details pane. If a user doesn’t notice the dependencies and only adds that SDK,
MSBuild will prompt the user to add the dependencies.

If a project type doesn’t support Extensions , the tab doesn’t appear in the Reference Manager dialog box.

Browse button
You can use the Browse button to browse for a component in the file system.
A project can reference a component that targets a different version of the .NET Framework. For example, you
could create an application that targets the .NET Framework 4 Client Profile, which references a component that
targets the .NET Framework 2. For more information, see Targeting a Specific .NET Framework Version.
You should avoid adding file references to outputs of another project in the same solution, because this tactic may
cause compilation errors. Instead, use the Solution tab of the Reference Manager dialog box to create project-
to-project references. This tactic makes team development easier by enabling better management of the class
libraries that you create in your projects. For more information, see Troubleshooting Broken References.
You can’t browse to an SDK and add it to your project. You can only browse to a file (for example, an assembly or
.winmd) and add it to your project.
When doing a file reference to a WinMD, the expected layout is that the FileName.winmd, FileName.dll, and
FileName.pri files are all placed alongside each other. If you reference a WinMD in the following scenarios, an
incomplete set of files will be copied into the project output directory and, consequently, build and runtime failures
will occur.
Native component : a native project will create one WinMD for each disjoint set of namespaces and one
DLL that consists of the implementation. The WinMDs will have disparate names. When referencing this
native component file, MSBuild won’t recognize that the dissimilarly named WinMDs make one component.
Consequently, only the identically named FileName.dll and FileName.winmd will be copied, and runtime
errors will occur. To work around this issue, create an Extension SDK. For more information, see Creating a
Software Development Kit.
Consuming controls : at a minimum, a XAML control consists of a FileName.winmd, FileName.dll,
FileName.pri, XamlName.xaml, and an ImageName.jpg. When the project is built, the resource files that are
associated with the file reference won’t get copied into the project’s output directory, and only
FileName.winmd, FileName.dll and FileName.pri will be copied. A build error is logged to inform the user
that the resources XamlName.xaml and ImageName.jpg are missing. To succeed, the user will have to
manually copy these resource files into the project output directory for build and debugging/runtime. To
work around this issue, either create an Extension SDK by following the steps in Creating a Software
Development Kit or edit the project file to add the following property:

<PropertyGroup>
<GenerateLibraryOutput>True</GenerateLibraryOutput>
</PropertyGroup>

NOTE
If you add the property, the build might run slower.

Recent
Assemblies, COM, Windows, and Browse each support a Recent tab, which enumerates the list of components that
were recently added to projects.

Search
The search bar in the Reference Manager dialog box operates over the tab that’s in focus. For example, if a user
types “System” in the search bar while the Solution tab is in focus, the search won’t return any results unless the
solution consists of a project name that contains “System”.

See Also
NIB How to: Add or Remove References By Using the Add Reference Dialog Box Managing references in a project
Adding References Using NuGet Versus an Extension
SDK
1/13/2020 • 7 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version selector
at the top left. We recommend upgrading to Visual Studio 2019. Download it here

You can provide a package for consumption within Visual Studio projects by using either the NuGet extension to
Visual Studio or a software development kit (SDK). By describing the similarities and differences between the two
mechanisms, this topic can help you choose the best one for your task.
NuGet is an open-source, package-management system that simplifies the process of incorporating libraries
into a project solution. For more information, see NuGet Overview.
An SDK is a collection of files that Visual Studio treats as a single reference item. The Reference Manager
dialog box lists all SDKs that are relevant to the project that’s open when you display that dialog box. When
you add an SDK to a project, you can access all of the contents of that SDK through IntelliSense, the Toolbox ,
designers, the Object Browser , MSBuild, deployment, debugging, and packaging. For more information
about SDKs, see Creating a Software Development Kit.

Which Mechanism Should I Use?


The following table helps you compare the referencing features of an SDK with the referencing features of NuGet.

F EAT URE SDK SUP P O RT SDK N OT ES N UGET SUP P O RT N UGET N OT ES

The mechanism Y You add an SDK by Y


references one entity using the Reference
and then all the files Manager dialog box,
and functionality are and all the files and
available. functionality are
available during the
development
workflow.

MSBuild automatically Y References in the SDK Y


consumes assemblies are automatically
and Windows passed to the
metadata (.winmd) compiler.
files.

MSBuild automatically Y The SDKName.props N


consumes the .h or file tells Visual Studio
.lib files. how to set up the
Visual C++ directory,
and so forth, for
automatic .h or .lib file
consumption.
F EAT URE SDK SUP P O RT SDK N OT ES N UGET SUP P O RT N UGET N OT ES

MSBuild automatically Y In Solution Y


consumes the .js or Explorer , you can
.css files. expand the JavaScript
SDK reference node
to show individual .js
or .css files and then
generate
<source include/>
tags by dragging
those files to their
source files. The SDK
supports F5 and
automatic package
setup.

MSBuild automatically Y The Toolbox can N


adds the control in consume SDKs and
the Toolbox. show controls in the
tabs that you specify.

The mechanism Y VSIX has a special Y The VSIX can be


supports Visual manifest and logic to embedded in another
Studio Installer for create SDK packages setup program.
extensions (VSIX).

The Object Browser Y The Object Browser N


enumerates automatically gets the
references. list of references in
SDKs and enumerates
them.

Files and links Y The Reference N NuGet provides its


automatically get Manager dialog box own Manage NuGet
added to the automatically Packages dialog box.
Reference Manager enumerates SDKs,
dialog box (help links, along with help links
and so forth auto and the list of SDK
populate) dependencies.

The mechanism Y SDKs can ship N


supports multiple multiple
architectures. configurations.
MSBuild consumes
the appropriate files
for each project
configuration.

The mechanism Y SDKs can ship N


supports multiple multiple
configurations. configurations.
Depending on project
architecture, MSBuild
consumes the
appropriate files for
each project
architecture.
F EAT URE SDK SUP P O RT SDK N OT ES N UGET SUP P O RT N UGET N OT ES

The mechanism can Y Depending on N You declare which files


specify “not to copy.” whether files are to copy in the
dropped in the \redist package manifest.
or \designtime folder,
you can control which
files to copy into the
consuming
application's package.

Content appears in Y Localized XML N


localized files. documents in SDKs
are automatically
included for a better
design-time
experience.

MSBuild supports Y The SDK supports N This isn't referencing.


consuming multiple consuming multiple You can’t have more
versions of an SDK versions than one version of
simultaneously. simultaneously. NuGet files in your
project at a time.

The mechanism Y The Reference Y (partial) Pivot is the Target


supports specifying Manager dialog box Framework. There is
applicable target and the Toolbox no filtering on user
frameworks, Visual show only the SDKs interface. At
Studio versions, and that apply to a installation time, it
project types. project, so that users might return an error.
can more easily
choose the
appropriate SDKs.

The mechanism Y You can specify the N


supports specifying correlation between
registration info for the .winmd file and
native WinMDs. the .dll file in
SDKManifest.xml.

The mechanism Y The SDK only notifies Y NuGet pulls them


supports specifying the user; the user automatically; the
dependencies on must still install them user isn't notified.
other SDKs. and reference them
manually.

The mechanism Y The SDK must pass N


integrates with concepts that are
Windows Store specific to the Store
concepts such as app so that packaging and
manifest and F5 work correctly with
Framework ID. SDKs that are
available in theStore.
F EAT URE SDK SUP P O RT SDK N OT ES N UGET SUP P O RT N UGET N OT ES

The mechanism Y The SDK must pass Y NuGet content


integrates with the Store-specific becomes part of the
app debugging concepts so that project. No special F5
pipeline for Windows packaging and F5 consideration is
8.x Store apps. work correctly with needed.
SDKs available in the
Store.

The mechanism Y The SDK must pass Y NuGet content


integrates with app Store-specific becomes part of the
manifests. concepts so that project. No special F5
packaging and F5 consideration is
work correctly with needed.
SDKs available in the
Store.

The mechanism Y If you drop the files in Y


deploys non- the \redist folder, the
reference files (for files are automatically
example, deploy test deployed.
framework upon
which to run tests of
Windows 8.x Store
apps).

The mechanism Y If you drop the N


automatically adds Windows 8 SDK or
the platform SDKs in the Windows Phone
Visual Studio IDE. SDK in a specific
location with a specific
layout, the SDK is
automatically
integrated with all the
Visual Studio features.
F EAT URE SDK SUP P O RT SDK N OT ES N UGET SUP P O RT N UGET N OT ES

The mechanism N Because you reference Y You can check out the
supports a clean an SDK, you must solution, and Visual
developer machine. check in your solution Studio immediately
(That is, no and the SDK recognizes and acts
installation is separately. You can on the files.
required, and simple check in the SDK from
retrieval from source the two non-registry
code control will default locations from
work.) which MSBuild
iterates SDKs (for
details, see Creating a
Software
Development Kit). As
an alternative, if a
custom location
consists of the SDKs,
you can specify the
following code in the
project file:

<PropertyGroup>
<SDKReferenceDirectoryRoot>C:\MySDKs</SDKReferenceDirectoryRoot>
</PropertyGroup>

Then check the SDKs


into that location.

You can join a large N/A The community is Y


existing community of new.
package authors.

You can join a large N/A The community is Y


existing community of new.
package consumers.

You can join an N/A The available Y


ecosystem of partners repositories include
(custom galleries, Visual Studio Gallery,
repositories, and so Microsoft Download
forth). Center, and Windows
Store.

The mechanism Y The SDK must pass Y


integrates with the checked-in
continuous- location
integration build (SDKReferenceDirector
servers for both yRoot property) on
package creation and command line to
consumption. MSBuild.

The mechanism Y The SDK supports Y


supports both stable adding references to
and pre-release multiple versions.
package versions.
F EAT URE SDK SUP P O RT SDK N OT ES N UGET SUP P O RT N UGET N OT ES

The mechanism Y If shipped as VSIX or Y


supports auto-update part of Visual Studio
for installed packages. automatic updates,
SDK provides
automatic
notifications.

The mechanism Y The SDK contains Y


contains a stand- MSBuild.exe.
alone .exe file for
creating and
consuming packages.

Packages can be Y You can’t check in Y


checked into version anything outside the
control. Documents node,
which means that the
Extension SDKs might
not be checked in.The
size of Extension SDK
might be large.

You can use a Y (consumption), N No tooling for Y


PowerShell interface (creation) creating an SDK.
to create and Consumption is
consume packages. executing MSBuild on
the command line.

You can use a Symbol Y If you drop .pdb files Y


package for in the SDK, the files
debugging support. get picked up
automatically.

The mechanism N/A The SDK gets revised Y


supports package with MSBuild.
manager auto-
updates.

The mechanism Y SDKManifest.xml Y


supports a supports many
lightweight manifest attributes, but a small
format. subset is usually
necessary.

The mechanism is Y The SDK supports all Y NuGet supports all


available for all Visual Visual Studio editions, Visual Studio editions,
Studio editions. from Visual Studio Express up through
Express through Visual Studio Ultimate.
Visual Studio
Ultimate.

The mechanism is N The SDK supports N You can review a list


available for all project Windows 8.x Store of allowed projects.
types. apps starting in Visual
Studio 2012.

See Also
Managing references in a project
How to: Add or Remove Imported Namespaces
(Visual Basic)
10/18/2019 • 2 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version selector
at the top left. We recommend upgrading to Visual Studio 2019. Download it here

Importing a namespace allows you to use elements from that namespace in your code without fully qualifying the
element. For example, if you want to access the Create method in the System.Messaging.MessageQueue class, you
can import the System.Messaging namespace and just refer to the element you need in code as
MessageQueue.Create .

Imported namespaces are managed on the References page of the Project Designer . The imports you specify in
this dialog box are passed directly to the compiler ( /imports ) and apply to all files in your project. Use the Imports
statement to use a namespace in a single source code file.
To add an imported namespace
1. In Solution Explorer , double-click the My Project node for the project.
2. In the Project Designer , click the References tab.
3. In the Impor ted Namespaces list, select the check box for the namespace that you wish to add.

NOTE
In order to be imported, the namespace must be in a referenced component. If the namespace does not appear in
the list, you will need to add a reference to the component that contains it. For more information, see NIB How to:
Add or Remove References By Using the Add Reference Dialog Box.

To remove an imported namespace


1. In Solution Explorer , double-click the My Project node for the project.
2. In the Project Designer , click the References tab.
3. In the Impor ted Namespaces list, clear the check box for the namespace that you wish to remove.

User Imports
User imports allow you to import a specific class within a namespace rather than the entire namespace. For
example, your application might have an import for the Systems.Diagnostics namespace, but the only class within
that namespace that you are interested in is the Debug class. You can define System.Diagnostics.Debug as a user
import, and then remove the import for System.Diagnostics .
If you later change you mind and decide that was really the EventLog class that you needed, you could enter
System.Diagnostics.EventLog as a user import and overwrite System.Diagnostics.Debug using the update
functionality.
To add a user import
1. In Solution Explorer , double-click the My Project node for the project.
2. In the Project Designer , click the References tab.
3. In the text box below the Impor ted Namespaces list, enter the full name for the namespace you wish to
import, including the root namespace.
4. Click the Add user impor t button to add the namespace to the Impor ted Namespaces list.

NOTE
The Add user impor t button will be disabled if the namespace matches one already in the list; you cannot add an
import twice.

To update a user import


1. In Solution Explorer , double-click the My Project node for the project.
2. In the Project Designer , click the References tab.
3. In the Impor ted Namespaces list, select the namespace you wish to change.
4. In the text box below the Impor ted Namespaces list, enter the name for the new namespace.
5. Click the Update user impor t button to update the namespace in the Impor ted Namespaces list.

See Also
Managing references in a project
Troubleshooting Broken References
10/18/2019 • 4 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version
selector at the top left. We recommend upgrading to Visual Studio 2019. Download it here

If your application attempts to use a broken reference, an exception error is generated. The inability to find the
referenced component is the primary trigger for the error, but there are several situations in which a reference can
be considered broken. These instances are shown in the following list:
The project's reference path is incorrect or incomplete.
The file being referenced has been deleted.
The file being referenced has been renamed.
The network connection or authentication has failed.
The reference is to a COM component that is not installed on the computer.
The following are remedies to these problems.

NOTE
Files in assemblies are referenced with absolute paths in the project file. Therefore, it is possible for users who work in a
multideveloper environment to be missing a referenced assembly in their local environment. To avoid these errors, it is
better in these cases to add project-to-project references. For more information, see NIB How to: Add or Remove References
By Using the Add Reference Dialog Box and Programming with Assemblies.

Reference Path Is Incorrect


If projects are shared on different computers, some references might not be found when a component is located in
a different directory on each computer. References are stored under the name of the component file (for example,
MyComponent). When a reference is added to a project, the folder location of the component file (for example,
C:\MyComponents\) is appended to the ReferencePath project property.
When the project is opened, it attempts to locate these referenced component files by looking in the directories on
the reference path. If the project is opened on a computer that stores the component in a different directory, such
as D:\MyComponents\, the reference cannot be found and an error appears in the Task List.
To fix this problem, you can delete the broken reference and then replace it using the Add Reference dialog box.
Another solution is to use the Reference Path item in the project's property pages and modify the folders in the
list to point to the correct locations. The Reference Path property is persisted for each user on each computer.
Therefore, modifying your reference path does not affect other users of the project.

TIP
Project-to-project references do not have these problems. For this reason, use them instead of file references, if you can.
To fix a broken project reference by correcting the reference path
1. In Solution Explorer , right-click your project node and click Proper ties .
2. The Project Designer appears.
3. If you are using Visual Basic, select the References page and click the Reference Paths button. In the
Reference Paths dialog box, type the path of the folder that contains the item you want to reference in the
Folder field, and then click the Add Folder button.
-or-
If you are using Visual C#, select the Reference Paths page. In the Folder field, type the path of the folder
that contains the item you want to reference, and then click the Add Folder button.

Referenced File Has Been Deleted


It is possible that the file being referenced has been deleted and no longer exists on the drive.
To fix a broken project reference for a file that no longer exists on your drive
Delete the reference.
If the reference exists in another location on your computer, read it from that location.
For more information, see NIB How to: Add or Remove References By Using the Add Reference Dialog Box.

Referenced File Has Been Renamed


It is possible that the file being referenced has been renamed.
To fix a broken reference for a file that has been renamed
Delete the reference, and then add a reference to the renamed file.
If the reference exists in another location on your computer, you have to read it in from that location. For
more information, see NIB How to: Add or Remove References By Using the Add Reference Dialog Box.

Network Connection or Authentication Has Failed


There can be many possible causes for inaccessible files: a failed network connection or a failed authentication, for
example. Each cause might have a unique means of recovery; for example, you might have to contact the local
administrator for access to the required resources. However, deleting the reference and fixing the code which used
it is always an option. For more information, see NIB How to: Add or Remove References By Using the Add
Reference Dialog Box.

COM Component Is Not Installed on Computer


If a user has added a reference to a COM component and a second user tries to run the code on a computer that
does not have this component installed, the second user will receive an error that the reference is broken.
Installing the component on the second computer will correct the error. For more information about how to use
references to COM components in your projects, see COM Interoperability in .NET Framework Applications.

See Also
Introduction to the Project Designer References Page, Project Designer (Visual Basic) NIB How to: Add or Remove
References By Using the Add Reference Dialog Box
Application Properties
10/18/2019 • 2 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version
selector at the top left. We recommend upgrading to Visual Studio 2019. Download it here

You can set general application properties for Visual Basic, C#, and F# applications, such as application type,
startup object, and assembly information, in the Application pane of the Project Designer .
The following tasks can be accomplished in the Application pane:
Specify assembly information
Specify a splash screen for an application
Specify application-level events
Change an assembly name
Change the namespace for an application
Change the application type
Change the Startup object for an application
Specify an application icon
Enable Windows XP visual styles
Specify instancing behavior for an application
Enable custom user authentication
Specify shutdown behavior for an application
The tasks available for your application depend on the development language being used.

In This Section
How to: Specify an Application Icon (Visual Basic, C#)

See Also
Application Page, Project Designer (Visual Basic) Application Page, Project Designer (C#) Introduction to the Project
Designer Publishing ClickOnce Applications Securing ClickOnce Applications Managing Debugging Properties
Managing Compilation Properties Managing Application Resources (.NET) Managing Application Settings (.NET)
Managing Application Resources (.NET)
10/18/2019 • 2 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version selector
at the top left. We recommend upgrading to Visual Studio 2019. Download it here

Resource files are files that are part of an application but are not compiled, for example icon files or audio files.
Since these files are not part of the compilation process, you can change them without having to recompile your
binaries. If you are planning to localize your application, you should use resource files for all the strings and other
resources that need to be changed when you localize your application.
For more information about resources in .NET desktop apps, see Resources in Desktop Apps. For more information
about resources in C++ desktop apps, see Working with Resource Files.
Windows Store apps use a different resource model from desktop apps. For information about resources in
Windows Store apps, see Defining Application Resources on the Windows Dev Center website.

Working with Resources


In a managed code project, open the project properties window (right-click the project node in Solution Explorer
and select Proper ties , or type project proper ties in the Quick Launch window, or type ALT + ENTER in the
Solution Explorer window). Select the Resources tab. You can add a .resx file if your project does not contain
one already, add and delete different kinds of resources, and modify existing resources.
To find out how to work with resources in C++ projects, see How to: Create a Resource.
Managing Application Settings (.NET)
11/21/2019 • 5 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version selector
at the top left. We recommend upgrading to Visual Studio 2019. Download it here

Application settings enable you to store application information dynamically. Settings allow you to store
information on the client computer that should not be included in the application code (for example a connection
string), user preferences and other information you need at runtime.
Application settings replace the dynamic properties used in earlier versions of Visual Studio.
Each application setting must have a unique name. The name can be any combination of letters, numbers, or an
underscore that does not start with a number, and it cannot contain spaces. The name can be changed through the
Name property.

Application settings can be stored as any data type that can be serialized to XML or has a TypeConverter that
implements ToString / FromString . The most common types are String , Integer , and Boolean , but you can also
store values as Color, Object, or as a connection string.
Application settings also contain a value. The value is set with the Value property and must match the data type of
the setting.
In addition, application settings can be bound to a property of a form or control at design time.
There are two types of application settings, based on scope:
Application-scoped settings can be used for information such as a URL for a Web service or a database
connection string. These values are associated with the application. Therefore, users cannot change them at
run time.
User-scoped settings can be used for information such as persisting the last position of a form or a font
preference. Users can change these values at run time.
You can change the type of a setting by using the Scope property.
The project system stores application settings in two XML files: an app.config file, which is created at design
time when you create the first application setting; and a user.config file, which is created at run time when
the user who runs the application changes the value of any user setting. Notice that changes in user settings
are not written to disk unless the application specifically calls a method to do this.

Creating Application Settings at Design Time


At design time, you can create application settings in two ways: by using the Settings page of the Project
Designer , or by using the Proper ties window for a form or control, which allows you to bind a setting to a
property.
When you create an application-scoped setting (for example, a database connection string, or a reference to server
resources), Visual Studio saves it in app.config with the <applicationSettings> tag. (Connection strings are saved
under the <connectionStrings> tag.)
When you create a user-scoped setting (for example, default font, home page, or window size), Visual Studio saves
it in app.config with the <userSettings> tag.

IMPORTANT
When you store connection strings in app.config, you should take precautions to avoid revealing sensitive information, such
as passwords or server paths, in the connection string.
If you take connection string information from an external source, such as a user supplying a user ID and password, you
must be careful to ensure that the values that you use to construct your connection string do not contain additional
connection string parameters that change the behavior of your connection.
Consider using the Protected Configuration feature to encrypt sensitive information in the configuration file. See Protecting
Connection Information for more information.

NOTE
Because there is no configuration file model for class libraries, application settings do not apply for Class Library projects. The
exception is a Visual Studio Tools for Office DLL project, which can have a configuration file.

Using Customized Settings Files


You can add customized settings files to your project for convenient management of groups of settings. Settings
that are contained in a single file are loaded and saved as a unit. Therefore, being able to store settings in separate
files for frequently-used and infrequently-used groups can save time in loading and saving settings.
For example, you can add a file such as SpecialSettings.settings to your project. While your SpecialSettings class
is not exposed in the My namespace, View Code can read the custom settings file that contains
Partial Class SpecialSettings .

The Settings Designer first searches for the Settings.settings file that the project system creates; this is the default
file that the Project Designer displays in the Settings tab. Settings.settings is located in the My Project folder for
Visual Basic projects and in the Properties folder for Visual C# projects. The Project Designer then searches for
other settings files in the project's root folder. Therefore, you should put your custom settings file there. If you add
a .settings file elsewhere in your project, the Project Designer will not be able to locate it.

Accessing or Changing Application Settings at Run Time in Visual Basic


In Visual Basic projects, you can access application settings at run time by using the My.Settings object. On the
Settings page, click the View code button to view the Settings.vb file. Settings.vb defines the Settings class,
which enables you to handle these events on the settings class: SettingChanging, PropertyChanged,
SettingsLoaded, and SettingsSaving. Notice that the Settings class in Settings.vb is a partial class that displays
only the user-owned code, not the whole generated class. For more information about accessing application
settings by using the My.Settings object, see Accessing Application Settings.
The values of any user-scoped settings that the user changes at run time (for example, the position of a form) are
stored in a user.config file. Notice that the default values are still saved in app.config.
If you have changed any user-scoped settings during run time, for example in testing the application, and want to
reset these settings to their default values, click the Synchronize button.
We strongly recommend that you use the My.Settings object and the default .settings file to access settings. This is
because you can use the Settings Designer to assign properties to settings, and, additionally, user settings are
automatically saved before application shutdown. However, your Visual Basic application can access settings
directly. In that case you have to access the MySettings class and use a custom .settings file in the root of the
project. You must also save the user settings before ending the application, as you would do for a C# application;
this is described in the following section.

Accessing or Changing Application Settings at Run Time in Visual C#


In languages other than Visual Basic, such as Visual C#, you must access the Settings class directly, as shown in
the following Visual C# example.

Properties.Settings.Default.FirstUserSetting = "abc";

You must also explicitly call the Save method of this wrapper class in order to persist the user settings. You usually
do this in the Closing event handler of the main form. The following Visual C# example shows a call to the Save
method.

Properties.Settings.Default.Save();

For general information about accessing application settings through the Settings class, see Application Settings
Overview. For information about iterating through the settings, see this forum post.

See Also
Accessing Application Settings
Managing Assembly and Manifest Signing
10/18/2019 • 2 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version selector
at the top left. We recommend upgrading to Visual Studio 2019. Download it here

Strong-name signing gives a software component a globally unique identity. Strong names are used to guarantee
that the assembly cannot be spoofed by someone else, and to ensure that component dependencies and
configuration statements map to the correct component and component version.
A strong name consists of the assembly's identity (simple text name, version number, and culture information), plus
a public key token and a digital signature.
For information about signing assemblies in Visual Basic and C# projects, see Creating and Using Strong-Named
Assemblies.
For information about signing assemblies in Visual C++ projects, see Strong Name Assemblies (Assembly Signing)
(C++/CLI).

Asset Types and Signing


You can sign .NET assemblies and application manifests. These include the following:
executables (.exe)
application manifests (.exe.manifest)
deployment manifests (.application)
shared component assemblies (.dll)
You must sign the following types of asset:
1. assemblies, if you want to deploy them to the global assembly cache (GAC).
2. ClickOnce application and deployment manifests. Visual Studio enables signing by default for these
applications.
3. Primary interop assemblies, which are used for COM interoperability. The TLBIMP utility enforces strong-
naming when creating a primary interop assembly from a COM type library.
In general you should not sign executables. A strongly-named component cannot reference a non-strongly-
named component that is deployed with the application. Visual Studio does not sign application executables,
but instead signs the application manifest, which points to the weak-named executable. You should generally
avoid signing components that are private to your application, because signing can make it more difficult to
manage dependencies.

How to Sign an Assembly in Visual Studio


You sign an application or component by using the Signing tab of the project properties window (right-click the
project node in the Solution Explorer and select Proper ties , or type project proper ties in the Quick Launch
window, or press ALT+ ENTER inside the Solution Explorer window). Select the Signing tab, then select the Sign
the assembly check box.
Specify a key file. If you choose to create a new key file, note that new key files are always created in the .pfx
format. You need a name and password for the new file.

WARNING
You should always protect your key file with a password to prevent someone else from using it. You can also secure your
keys by using providers or certificate stores.

You can also point to a key you have already created. For more information about creating keys, see How to: Create
a Public-Private Key Pair.
If you have access only to a public key, you can use delay signing to defer assigning the key. You enable delay
signing by selecting the Delay sign only check box. A delay-signed project won’t run, and you can’t debug it.
However, you can skip verification during development by using the Sn.exe (Strong Name Tool) with the -Vr
option.
For information about signing manifests, see How to: Sign Application and Deployment Manifests.

See Also
Strong-Named Assemblies Strong Name Assemblies (Assembly Signing) (C++/CLI)
How to: Sign Application and Deployment Manifests
10/18/2019 • 4 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version selector
at the top left. We recommend upgrading to Visual Studio 2019. Download it here

If you want to publish an application by using ClickOnce deployment, the application and deployment manifests
must be signed with a public/private key pair and signed using Authenticode technology. You can sign the
manifests by using a certificate from the Windows certificate store or a key file.
For more information about ClickOnce deployment, see ClickOnce Security and Deployment.
Signing the ClickOnce manifests is optional for .exe-based applications. For more information, see the "Generating
Unsigned Manifests" section of this document.
For information about creating key files, see How to: Create a Public-Private Key Pair.

NOTE
Visual Studio supports only Personal Information Exchange (PFX) key files that have the .pfx extension. However, you can
select other types of certificates from the current user's Windows certificate store by clicking Select from Store on the
Signing page of project properties.

To sign application and deployment manifests using a certificate


1. Go to the project properties window (right-click the project node in the Solution Explorer and select
Proper ties , or type project proper ties in the Quick Launch window, or press ALT+ ENTER inside the
Solution Explorer window). On the Signing tab, select the Sign the ClickOnce manifests check box.
2. Click the Select from Store button.
The Select a Cer tificate dialog box appears and displays the contents of the Windows certificate store.

TIP
If you click Click here to view cer tificate proper ties , the Cer tificate Details dialog box appears. This dialog
box includes detailed information about the certificate, and includes additional options. You can click cer tificates to
view additional Help information.

3. Select the certificate that you want to use to sign the manifests.
4. Additionally, you can specify the address of a timestamp server in the Timestamp ser ver URL text box.
This is a server that provides a timestamp specifying when the manifest was signed.
To sign application and deployment manifests using an existing key file
1. On the Signing page, select the Sign the ClickOnce manifests check box.
2. Click the Select from File button.
The Select File dialog box appears.
3. In the Select File dialog box, browse to the location of the key file (.pfx) that you want to use, and then
click Open .

NOTE
This option supports only files that have the .pfx extension. If you have a key file or certificate in another format,
store it in the Windows certificate store and select the certificate is described in the previous procedure. The selected
certificate's purpose should include code signing.

The Enter password to open file dialog box appears. (If the .pfx file is already stored in your Windows
certificate store, or is not password protected, you will not be prompted to enter a password.)
4. Enter the password to access the key file, and press ENTER.
To sign application and deployment manifests using a test certificate
1. On the Signing page, select the Sign the ClickOnce manifests check box.
2. To create a new certificate for testing, click the Create Test Cer tificate button.
3. In the Create Test Cer tificate dialog box, enter a password to help secure your test certificate.

Generating Unsigned Manifests


Signing the ClickOnce manifests is optional for .exe-based applications. The following procedures show how to
generate unsigned ClickOnce manifests.

IMPORTANT
Unsigned manifests can simplify development and testing of your application. However, unsigned manifests introduce
substantial security risks in a production environment. Only consider using unsigned manifests if your ClickOnce application
runs on computers within an intranet that is completely isolated from the internet or other sources of malicious code.

By default, ClickOnce automatically generates signed manifests unless one or more files are specifically excluded
from the generated hash. In other words, publishing the application results in signed manifests if all files are
included in the hash, even when the Sign the ClickOnce manifests check box is cleared.
To generate unsigned manifests and include all files in the generated hash
1. To generate unsigned manifests that include all files in the hash, you must first publish the application
together with signed manifests. Therefore, first sign the ClickOnce manifests by following one of the
previous procedures, and then publish the application.
2. On the Signing page, clear the Sign the ClickOnce manifests check box.
3. Reset the publish version so that only one version of your application is available. By default, Visual Studio
automatically increments the revision number of the publish version every time that you publish an
application. For more information, see How to: Set the ClickOnce Publish Version.
4. Publish the application.
To generate unsigned manifests and exclude one or more files from the generated hash
1. On the Signing page, clear the Sign the ClickOnce manifests check box.
2. Open the Application Files dialog box and set the Hash to Exclude for the files that you want to exclude
from the generated hash.
NOTE
Excluding a file from the hash configures ClickOnce to disable automatic signing of the manifests, so you do not need
to first publish with signed manifests as shown in the previous procedure.

3. Publish the application.

See Also
Strong-Named Assemblies How to: Create a Public-Private Key Pair Signing Page, Project Designer ClickOnce
Security and Deployment
How to: Specify an Application Icon (Visual Basic, C#)
10/18/2019 • 2 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version selector
at the top left. We recommend upgrading to Visual Studio 2019. Download it here

The Icon property for a project specifies the icon file (.ico) that will be displayed for the compiled application in
File Explorer and in the Windows taskbar.
The Icon property can be accessed in the Application pane of the Project Designer ; it contains a list of icons
that have been added to a project either as resources or as content files.

NOTE
After you set the icon property for an application, you might also set the Icon property of each Window or Form in the
application. For information about window icons for Windows Presentation Foundation (WPF) standalone applications, see
Icon property.

To specify an application icon


1. In Solution Explorer , choose a project node (not the Solution node).
2. On the menu bar, choose Project , Proper ties .
3. When the Project Designer appears, choose the Application tab.
4. (Visual Basic) In the Icon list, choose an icon (.ico) file.
C# Near the Icon list, choose the <Browse...> button, and then browse to the location of the icon file that
you want.

See Also
Application Page, Project Designer (Visual Basic) Application Page, Project Designer (C#) Managing Application
Properties How to: Add or Remove Resources
Targeting a Specific .NET Framework Version
10/18/2019 • 2 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version
selector at the top left. We recommend upgrading to Visual Studio 2019. Download it here

In Visual Studio, you can specify the version or profile of the .NET Framework that you want your project to target.
For an application to run on another computer, the Framework version that the application targets must be
compatible with the Framework version that is installed on the computer.
This section contains topics that describe how to target specific versions of the .NET Framework in your projects.

In This Section
Visual Studio Multi-Targeting Overview Provides an overview of the multi-targeting features in Visual Studio.
How to: Target a Version of the .NET Framework Details how to specify a particular .NET Framework for your
Visual Basic, Visual C# or Visual F# project.

Related Sections
.NET Framework Multi-Targeting for ASP.NET Web Projects Explains how to use this version of Visual Studio to
develop Web applications that run under earlier versions of the .NET Framework.
Application Page, Project Designer (C#) Describes the Target Framework control in the Project Designer for
Visual C# projects.
Application Page, Project Designer (Visual Basic) Describes the Target Framework control in the Project Designer
for Visual Basic projects.
How to: Modify the Target Framework and Platform Toolset Describes how to change settings for Visual C++
projects to target different versions of the .NET Framework and to use different platform toolsets.
Visual Studio Multi-Targeting Overview
1/10/2020 • 4 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version
selector at the top left. We recommend upgrading to Visual Studio 2019. Download it here

In this version of Visual Studio, you can specify the version of the .NET Framework that is required for your
application. Therefore, if you want to use this version of Visual Studio to continue to develop a project that you
started in an earlier version, you do not have to change the framework target. You could also create a solution that
contains projects that target different versions of the framework. Framework targeting also helps guarantee that
the application uses only functionality that is available in the specified version of the framework.

TIP
You can also target applications for different platforms. For more information, see Multitargeting

Framework Targeting Features


Framework targeting includes the following features:
When you open a project that targets an earlier version of the .NET Framework, Visual Studio can
automatically upgrade it or leave the target as is.
When you create a project, you can specify the version of the .NET Framework that you want to target.
You can change the version of the .NET Framework that an existing project targets.
You can target a different version of the .NET Framework in each of several projects in the same solution.
When you change the version of the .NET Framework that a project targets, Visual Studio makes any
required changes to references and configuration files.
When you work on a project that targets an earlier version of the .NET Framework, Visual Studio
dynamically changes the development environment, as follows:
It filters items in the New Project dialog box, the Add New Item dialog box, the Add New Reference
dialog box, and the Add Ser vice Reference dialog box to omit choices that are not available in the
targeted version.
It filters custom controls in the Toolbox to remove those that are not available in the targeted version and
to show the only the most up-to-date controls when multiple controls are available.
It filters IntelliSense to omit language features that are not available in the targeted version.
It filters properties in the Proper ties window to omit those that are not available in the targeted version.
It filters menu options to omit options that are not available in the targeted version.
For builds, it uses the version of the compiler and the compiler options that are appropriate for the targeted
version.
NOTE
Framework targeting does not guarantee that your application will run correctly. You must test your application to make
sure it runs against the targeted version. You cannot target framework versions that are earlier than the .NET Framework
2.0.

Selecting a Target Framework Version


When you create a project, select the target .NET Framework version in the New Project dialog box. The list of
available project templates is filtered based on the selection. In an existing project, you can change the target .NET
Framework version in the project properties dialog box. For more information, see How to: Target a Version of the
.NET Framework.

NOTE
In Express editions of Visual Studio, you cannot set the target framework in the New Project dialog box.

Resolving System and User Assembly References


To target a .NET Framework version, you must first install the appropriate assembly references. Assembly
references for the .NET Framework versions 2.0, 3.0, and 3.5 are included in the .NET Framework 3.5 SP1, which
you can download from the Microsoft Download Center, Microsoft Visual Studio website. Assembly references for
the .NET Framework 3.5 Client Profile, the .NET Framework 4, the .NET Framework 4 Client Profile, and Silverlight
are also available from the Visual Studio Downloads website.

NOTE
A .NET Framework client profile is a subset of the .NET Framework that provides a limited set of libraries and features. For
more information about client profiles, see .NET Framework Client Profile.

The Add Reference dialog box disables system assemblies that do not pertain to the target .NET Framework
version so that they cannot be added to a project inadvertently. (System assemblies are .dll files that are included
in a .NET Framework version.) References that belong to a framework version that is later than the targeted
version will not resolve, and controls that depend on such a reference cannot be added. If you want to enable such
a reference, reset the .NET Framework target of the project to one that includes the reference. For more
information, see Introduction to the Project Designer.
For more information about assembly references, see Resolving Assemblies at Design Time.

Enabling LINQ
When you target the .NET Framework 3.5 or later, a reference to System.Core and a project-level import for
System.Linq (in Visual Basic only) are added automatically. If you want to use LINQ features, you must also turn
Option Infer on (in Visual Basic only). The reference and import are removed automatically if you change the
target to an earlier .NET Framework version. For more information, see How to: Create a LINQ Project.

See Also
Multitargeting .NET Framework Multi-Targeting for ASP.NET Web Projects Platform compatibility and system
requirements
How to: Target a Version of the .NET Framework
10/18/2019 • 2 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version
selector at the top left. We recommend upgrading to Visual Studio 2019. Download it here

This document describes how to target a version of the .NET Framework when you create a project and how to
change the targeted version in an existing Visual Basic, Visual C#, or Visual F# project.

IMPORTANT
For information about how to change the target version for C++ projects, see How to: Modify the Target Framework and
Platform Toolset.

In this topic
Targeting a version when you create a project
Changing the target version

Targeting a version when you create a project


When you create a project, the version of the .NET Framework that you target determines which templates you can
use.

NOTE
In Express editions of Visual Studio, you must create the project first, and then you can change the target, as Changing the
target version describes later in this topic.

To target a version when you create a project


1. On the menu bar, choose File , New , Project .
2. In the list at the top of the New Project dialog box, choose the version of the .NET Framework that you
want your project to target.

NOTE
Typically, only one version of the .NET Framework is installed with Visual Studio. If you want to target another
version, you must first make sure that it's installed. See Visual Studio Multi-Targeting Overview.

3. In the list of installed templates, choose the type of project that you want to create, name the project, and
then choose the OK button.
The list of templates shows only those projects that are supported by the version of the .NET Framework
that you chose.
Changing the target version
You can change the targeted version of the .NET Framework in a Visual Basic, Visual C#, or Visual F# project by
following this procedure.
To change the targeted version
1. In Solution Explorer , open the shortcut menu for the project that you want to change, and then choose
Proper ties .

IMPORTANT
For information about how to change the target version for C++ projects, see How to: Modify the Target Framework
and Platform Toolset.

2. In the left column of the properties window, choose the Application tab.
NOTE
After you create a Windows Store app, you can't change the targeted version of either Windows or the .NET
Framework.

3. In the Target Framework list, choose the version that you want.
4. In the verification dialog box that appears, choose the Yes button.
The project unloads. When it reloads, it targets the .NET Framework version that you just chose.

NOTE
If your code contains references to a different version of the .NET Framework than the one that you targeted, error
messages may appear when you compile or run the code. To resolve these errors, you must modify the references.
See Troubleshooting .NET Framework Targeting Errors.

See Also
Visual Studio Multi-Targeting Overview .NET Framework Multi-Targeting for ASP.NET Web Projects
Troubleshooting .NET Framework Targeting Errors Application Page, Project Designer (C#) Application Page,
Project Designer (Visual Basic) Configuring Projects How to: Modify the Target Framework and Platform Toolset
Creating Project and Item Templates
10/18/2019 • 2 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version
selector at the top left. We recommend upgrading to Visual Studio 2019. Download it here

Visual Studio project and item templates provide reusable stubs that give users some basic code and structure
that they can use for their own purposes.

Visual Studio Templates


A number of predefined project and item templates are installed when you install Visual Studio. The Visual Basic
and Visual C# Windows Forms Application and Class Library templates that are available in the New Project
dialog box are examples of project templates. Installed item templates are available in the Add New Item dialog
box, and include items such as code files, XML files, HTML pages, and Style Sheets.
These templates provide a starting point for users to begin creating projects or expanding current projects.
Project templates provide the files that are required for a particular project type, include standard assembly
references, and set default project properties and compiler options. Item templates can range in complexity from
just one empty file that has the correct file name extension to a multi-file item that contains, for example, source
code files that have stub code, designer information files, and embedded resources.
In addition to the installed templates in the New Project and Add New Item dialog boxes, you can author your
own templates or download and use templates created by the community. For more information, see How to:
Create Project Templates and How to: Create Item Templates.

Contents of a Template
All project and item templates, whether installed together with Visual Studio or created by you, function by using
the same principles and have similar contents. All templates contain the following items:
The files to be created when the template is used. This includes source code files, embedded resources,
project files, and so on.
One .vstemplate file. This file contains the metadata that provides Visual Studio the information it needs to
display the template in the New Project and Add New Item dialog boxes and create a project or item
from the template. For more information about .vstemplate files, see Template Parameters.
When these files are compressed into a .zip file and put in the correct folder, Visual Studio automatically
displays them. Project templates appear in the My Templates section of the New Project dialog boxes,
and item templates appear in the Add New Item dialog boxes. For more information about template
folders, see How to: Locate and Organize Templates.

Starter Kits
Starter Kits are enhanced templates that can be shared with other members of the community. A Starter Kit
includes code samples that compile, documentation, and other resources to help users learn new tools and
programming techniques while they build useful, real-world applications. The basic contents and procedures for
Starter Kits are identical to those for templates. For more information, see How to: Create Starter Kits.
See Also
How to: Create Project Templates How to: Create Item Templates Template Parameters Customizing Templates
How to: Create Starter Kits
How to: Create Project Templates
10/18/2019 • 2 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version
selector at the top left. We recommend upgrading to Visual Studio 2019. Download it here

This procedure enables you to create a template using the Expor t Template wizard, which packages your
template in a .zip file. You can also create templates in the VSIX file format for improved deployment by using the
Export Template Wizard extension, or with templates included in the Visual Studio SDK, or you can create
templates manually.
To create a custom project template with the standard Export Template wizard
1. Create a project.

NOTE
Use only valid identifier characters when naming a project that will be the source for a template. A template
exported from a project named with invalid characters can cause compilation errors in future projects based on the
template. For more information on valid identifier characters, see Declared Element Names.

2. Edit the project until it is ready to be exported as a template.


3. As appropriate, edit the code files to indicate where parameter replacement should take place. For more
information on parameter replacement, see How to: Substitute Parameters in a Template.
4. On the File menu, click Expor t Template . The Expor t Template wizard opens.
5. Click Project Template .
6. If you have more than one project in your current solution, select the projects you want to export to a
template.
7. Click Next .
8. Select an icon and a preview image for your template. These will appear in the New Project dialog box.
9. Enter a template name and description.
10. Click Finish . Your project is exported into a .zip file and placed in the specified output location, and, if
selected, imported into Visual Studio.
If you have the Visual Studio SDK installed, you can wrap the finished template in a .vsix file for deployment
by using the VSIX Project template. For more information, see Getting Started with the VSIX Project
Template.

See Also
Creating Project and Item Templates How to: Create Item Templates
How to: Create Multi-Project Templates
10/18/2019 • 3 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version selector
at the top left. We recommend upgrading to Visual Studio 2019. Download it here

Multi-project templates act as containers for two or more projects. When a project based on a multi-project
template is created from the New Project dialog box, every project in the template is added to the solution.
A multi-project template must include the following items, compressed into a .zip file:
A root .vstemplate file for the entire multi-project template. This root .vstemplate file contains the metadata
that the New Project dialog box displays, and specifies where to find the .vstemplate files for the projects in
this template. This file must be located at the root of the .zip file.
One or more folders that contain the files that are required for a complete project template. This includes all
code files for the project, and also a .vstemplate file for the project.
For example, a multi-project template .zip file that has two projects could have the following files and
directories:
MultiProjectTemplate.vstemplate
\Project1\Project1.vstemplate
\Project1\Project1.vbproj
\Project1\Class.vb
\Project2\Project2.vstemplate
\Project2\Project2.vbproj
\Project2\Class.vb
The root .vstemplate file for a multi-project template differs from a single-project template in the following
ways:
The Type attribute of the VSTemplate element contains the value ProjectGroup . For example:

<VSTemplate Version="2.0.0" Type="ProjectGroup"


xmlns="http://schemas.microsoft.com/developer/vstemplate/2005">

The TemplateContent element contains a ProjectCollection element that has one or more
ProjectTemplateLink elements that define the paths to the .vstemplate files of the included projects. For
example:
<TemplateContent>
<ProjectCollection>
<ProjectTemplateLink>
Project1\Project1.vstemplate
</ProjectTemplateLink>
<ProjectTemplateLink>
Project2\Project2.vstemplate
</ProjectTemplateLink>
</ProjectCollection>
</TemplateContent>

Multi-project templates also behave differently than normal templates. Multi-project templates have the
following unique characteristics:
Individual projects in a multi-project template cannot be assigned names by the New Project dialog box.
Instead, use the ProjectName attribute on the ProjectTemplateLink element to specify the name for each
project. For more information, see the first example in the following section.
Multi-project templates can contain projects written in different languages, but the entire template itself can
only be put in one category by using the ProjectType element.
To create a multi-project template
1. Create the projects to include in the multi-project template.
2. Create .vstemplate files for every project. For more information, see How to: Create Project Templates.
3. Create a root .vstemplate file that to contain the metadata for the multi-project template. For more
information, see the first example in the following section.
4. Select the files and folders to include in your template, right-click the selection, click Send To , and then click
Compressed (zipped) Folder . The files and folders are compressed into a .zip file.
5. Put the .zip template file in the Visual Studio project template directory. By default, this directory is \My
Documents\Visual Studio Version\Templates\ProjectTemplates\.

Example
This example shows a basic multi-project root .vstemplate file. In this example, the template contains two projects,
My Windows Application and My Class Library . The ProjectName attribute on the ProjectTemplateLink element
sets the name for Visual Studio to assign this project. If the ProjectName attribute does not exist, the name of the
.vstemplate file is used as the project name.
<VSTemplate Version="2.0.0" Type="ProjectGroup"
xmlns="http://schemas.microsoft.com/developer/vstemplate/2005">
<TemplateData>
<Name>Multi-Project Template Sample</Name>
<Description>An example of a multi-project template</Description>
<Icon>Icon.ico</Icon>
<ProjectType>VisualBasic</ProjectType>
</TemplateData>
<TemplateContent>
<ProjectCollection>
<ProjectTemplateLink ProjectName="My Windows Application">
WindowsApp\MyTemplate.vstemplate
</ProjectTemplateLink>
<ProjectTemplateLink ProjectName="My Class Library">
ClassLib\MyTemplate.vstemplate
</ProjectTemplateLink>
</ProjectCollection>
</TemplateContent>
</VSTemplate>

Example
This example uses the SolutionFolder element to divide the projects into two groups, Math Classes and
Graphics Classes . The template contains four projects, two of which are placed in each solution folder.

<VSTemplate Version="2.0.0" Type="ProjectGroup"


xmlns="http://schemas.microsoft.com/developer/vstemplate/2005">
<TemplateData>
<Name>Multi-Project Template Sample</Name>
<Description>An example of a multi-project template</Description>
<Icon>Icon.ico</Icon>
<ProjectType>VisualBasic</ProjectType>
</TemplateData>
<TemplateContent>
<ProjectCollection>
<SolutionFolder Name="Math Classes">
<ProjectTemplateLink ProjectName="MathClassLib1">
MathClassLib1\MyTemplate.vstemplate
</ProjectTemplateLink>
<ProjectTemplateLink ProjectName="MathClassLib2">
MathClassLib2\MyTemplate.vstemplate
</ProjectTemplateLink>
</SolutionFolder>
<SolutionFolder Name="Graphics Classes">
<ProjectTemplateLink ProjectName="GraphicsClassLib1">
GraphicsClassLib1\MyTemplate.vstemplate
</ProjectTemplateLink>
<ProjectTemplateLink ProjectName="GraphicsClassLib2">
GraphicsClassLib2\MyTemplate.vstemplate
</ProjectTemplateLink>
</SolutionFolder>
</ProjectCollection>
</TemplateContent>
</VSTemplate>

See Also
Creating Project and Item Templates Visual Studio Template Schema Reference How to: Create Project Templates
Visual Studio Template Schema Reference SolutionFolder Element (Visual Studio Templates) ProjectTemplateLink
Element (Visual Studio Templates)
How to: Create Item Templates
10/18/2019 • 4 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version
selector at the top left. We recommend upgrading to Visual Studio 2019. Download it here

The steps in the first procedure of this topic show you how to create an item template by using the Expor t
Template wizard. If your template will consist of multiple files, see How to: Create Multi-file Item Templates.
The wizard does a lot of work for you to create the basic template, but in many cases you will need to manually
modify the .vstemplate file after you have exported the template. For example, if you want the item to appear in
the Add New Item dialog for a Windows 8.x Store app project, you’ll have to perform a few extra steps. The
second procedure in this topic helps you accomplish that task.
In some cases you may want or need to create an item template manually from scratch. The third procedure
shows how to do that.
See the Visual Studio Template Schema Reference for information about the elements that can be used in the
.vstemplate file.
To add a custom project item template to the Add New Item dialog box
1. Create or open a project in Visual Studio.
2. Add an item to the project and modify it if you want to.
3. Modify the code file to indicate where parameter replacement should take place. For more information, see
How to: Substitute Parameters in a Template.
4. On the File menu, click Expor t Template .
5. Click Item Template , select the project that contains the item, and click Next .
6. Select the item for which you want to create a template, and click Next .
7. Select the assembly references to include in the template, and click Next .
8. Type the icon file name, preview image, template name, and template description, and click Finish .
The files for the template are added to a .zip file and copied whatever directory you specify in the dialog.
The default location is ..\Users\<username>\Documents\Visual Studio <Version>\My Expor ted
Templates\ folder.

WARNING
In earlier versions of Visual Studio, the default location is ..\Users\<username>\Documents\Visual Studio
<Version>\Templates\ItemTemplates .

To enable the item template to be used in a store project


1. Follow the steps in the procedure above to export an item template.
2. Extract the .vstemplate file from the .zip file that was copied to the ..\Users\username\Documents\Visual
Studio Version\Templates\ItemTemplates\ (or My Expor ted Templates ) folder.
3. Open the .vstemplate file in Visual Studio.
4. For a Windows 8.1 store C# project, in the .vstemplate file, add the following XML within the opening and
closing <TemplateData> tag: <TemplateGroupID>WinRT-Managed</TemplateGroupID> .
A C++ Windows 8.1 store project uses a value of WinRT-Native-6.3 . For Windows 10 and other project
types, see TemplateGroupID Element (Visual Studio Templates).
The following example shows the entire contents of a .vstemplate file after the line of XML
<TemplateGroupID>WinRT-Managed</TemplateGroupID> has been added to it. This example is specific to C#
projects. You can modify the <ProjectType> and < TemplateGroupID> elements to specify other language
and project types.

<VSTemplate Version="3.0.0" xmlns="http://schemas.microsoft.com/developer/vstemplate/2005" Type="Item">


<TemplateData>
<DefaultName>MyItemStoreTemplate.xaml</DefaultName>
<Name>MyItemStoreTemplate</Name>
<Description>This is an example itemtemplate</Description>
<ProjectType>CSharp</ProjectType>
<SortOrder>10</SortOrder>
<Icon>__TemplateIcon.ico</Icon>
<TemplateGroupID>WinRT-Managed</TemplateGroupID>
</TemplateData>
<TemplateContent>
<References />
<ProjectItem SubType="Designer" TargetFileName="$fileinputname$.xaml"
ReplaceParameters="true">MyItemTemplate.xaml</ProjectItem>
<ProjectItem SubType="Code" TargetFileName="$fileinputname$.xaml.cs"
ReplaceParameters="true">MyItemTemplate.xaml.cs</ProjectItem>
</TemplateContent>
</VSTemplate>

For other possible TemplateGroupID values, see TemplateGroupID Element (Visual Studio Templates)). For
the complete .vstemplate reference, see Visual Studio Template Schema Reference
5. In Visual Studio, save the .vstemplate file and close it.
6. Copy and paste the .vstemplate file back to the .zip file located in the ..\Users\username\Documents\Visual
Studio Version\Templates\ItemTemplates\ folder.
If the Copy File dialog box appears, choose the Copy and Replace option.
You can now add an item based on this template to a Windows 8.x Store project by using the Add New
Item dialog box.
For more information about parameter names, see Template Parameters.
To enable templates for specific project sub-types
1. The development environment enables you to make project items available from the Add Item dialog box
for certain projects. Use this procedure to make custom items available for Windows, Web, Office, or
database projects.
Locate the ProjectType element in the .vstemplate file for the item template.
Add a ProjectSubType element immediately after the ProjectType element.
2. Set the text value of the element to one of the following values:
a. Windows
b. Office
c. Database
d. Web
For example: <ProjectSubType>Database</ProjectSubType> .
The following example shows an item template available for Office projects.

<VSTemplate Version="2.0.0" Type="Item" Version="2.0.0">


<TemplateData>
<Name>Class</Name>
<Description>An empty class file</Description>
<Icon>Class.ico</Icon>
<ProjectType>CSharp</ProjectType>
<ProjectSubType>Office</ProjectSubType>
<DefaultName>Class.cs</DefaultName>
</TemplateData>
<TemplateContent>
<ProjectItem>Class1.cs</ProjectItem>
</TemplateContent>
</VSTemplate>

To manually create an item template without using the Export Template wizard
1. Create a project and project item.
2. Modify the project item until it is ready to be saved as a template.
3. As appropriate, modify the code file to indicate where parameter replacement should occur. For more
information about parameter replacement, see How to: Substitute Parameters in a Template.
4. Create an XML file and save it by using a .vstemplate file name extension, in the same directory as your
new item template.
5. Author the .vstemplate XML file to provide item template metadata. For more information, see Visual
Studio Template Schema Reference and the example in the previous section.
6. Save the .vstemplate file and close it.
7. In Windows Explorer, select the files you want to include in your template, right-click the selection, click
Send To, and then click Compressed (zipped) Folder. The files that you selected are compressed into a .zip
file.
8. Copy the .zip file and paste it in the user item template location. In Visual Studio 2015, the default directory
is ..\Users\<username>\Documents\Visual Studio 2015\Templates\ItemTemplates\. For more information,
see How to: Locate and Organize Project and Item Templates.

See Also
Creating Project and Item Templates How to: Create Multi-file Item Templates Visual Studio Template Schema
Reference
How to: Create Multi-file Item Templates
10/18/2019 • 2 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version selector
at the top left. We recommend upgrading to Visual Studio 2019. Download it here

Item templates may only specify one item, but sometimes the item is made up of multiple files. For example, a
Windows Forms item template for Visual Basic requires the following three files:
A .vb file that contains the code for the form.
A .designer.vb file that contains the designer information for the form.
A .resx file that contains the embedded resources for the form.
Multi-file item templates require parameters to ensure the correct file name extensions are used when the
item is created in Visual Studio. If you create an item template by using the Expor t Template wizard, these
parameters are automatically generated, and no further editing is required. The following steps explain how
to use parameters to ensure that the correct file name extensions are created.
To manually create a multi-file item template
1. Create the item template as you would create a single-file item template. For more information, see How to:
Create Item Templates.
2. Add TargetFileName attributes to every ProjectItem element. Set the values of the TargetFileName
attributes to $fileinputname$.FileExtension, where FileExtension is the file name extension of the file that is
being included in the template. For example:

<ProjectItem TargetFileName="$fileinputname$.vb">
Form1.vb
</ProjectItem>
<ProjectItem TargetFileName="$fileinputname$.Designer.vb">
Form1.Designer.vb
</ProjectItem>
<ProjectItem TargetFileName="$fileinputname$.resx">
Form1.resx
</ProjectItem>

When an item derived from this template is added to a project, the file names will be based on the name
that the user typed in the Add New Item dialog box.
3. Select the files to be included in your template, right-click the selection, click Send To , and then click
Compressed (zipped) Folder . The files that you selected are compressed into a .zip file.
4. Put the .zip file in the user item template location. By default, the directory is \My Documents\Visual Studio
Version\Templates\ItemTemplates\. For more information, see How to: Locate and Organize Templates.

Example
The following example shows a Visual Studio Windows Forms template. When an item is created based on this
template, the names of the three files created will match the name entered in the Add New Item dialog box.
<VSTemplate Version="2.0.0" Type="Item"
xmlns="http://schemas.microsoft.com/developer/vstemplate/2005">
<TemplateData>
<Name>Multi-file Item Template</Name>
<Icon>Icon.ico</Icon>
<Description>An example of a multi-file item template</Description>
<ProjectType>VisualBasic</ProjectType>
</TemplateData>
<TemplateContent>
<ProjectItem TargetFileName="$fileinputname$.vb" SubType="Form">
Form1.vb
</ProjectItem>
<ProjectItem TargetFileName="$fileinputname$.Designer.vb">
Form1.Designer.vb
</ProjectItem>
<ProjectItem TargetFileName="$fileinputname$.resx">
Form1.resx
</ProjectItem>
</TemplateContent>
</VSTemplate>

See Also
Creating Project and Item Templates How to: Create Item Templates Template Parameters How to: Substitute
Parameters in a Template
How to: Manually Create Web Templates
10/18/2019 • 2 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version selector
at the top left. We recommend upgrading to Visual Studio 2019. Download it here

Creating a Web template is different than creating other kinds of templates. Because Web project templates appear
in the Add New Web Site dialog box, and Web project items are categorized by programming language, the
.vstemplate file must specify the template as a Web template and identify the programming language.

NOTE
Web templates must contain a empty .webproj file that is specified by using the File attribute of the Project element.
Although Web projects do not require project files, this file is required so that a Web template functions correctly.

To manually create a Web template


1. Create a Web project.
2. Modify or delete the files in the project, or add new files to the project.
3. Create an XML file and save it by using a .vstemplate file name extension, in the same directory as your
project. Do not add it to the project in Visual Studio.
4. Author the .vstemplate XML file to provide project template metadata. For more information, see the
example in the following section.
5. Locate the ProjectType element in the .vstemplate file, and set the text value to Web .
6. Following the ProjectType element, add a ProjectSubType element and set the text value to the
programming language of the template. The programming language can be one of the following values:
CSharp
VisualBasic
For example:

<TemplateData>
...
<ProjectType>Web</ProjectType>
<ProjectSubType>CSharp</ProjectSubType>
...
</TemplateData>

7. Select the files in your template (this includes the .vstemplate file), right-click the selection, click Send To ,
and then click Compressed (zipped) Folder . The files are compressed into a .zip file.
8. Put the .zip template file in the Visual Studio project template directory. By default, this directory is \My
Documents\Visual Studio Version\My Exported Templates\.
Example
The following example shows a basic .vstemplate file for a Web project template.

<VSTemplate Version="2.0.0" Type="Project"


xmlns="http://schemas.microsoft.com/developer/vstemplate/2005">>
<TemplateData>
<Name>MyWebProjecStarterKit</Name>
<Description>A simple Web template</Description>
<Icon>icon.ico</Icon>
<ProjectType>Web</ProjectType>
<ProjectSubType>CSharp</ProjectSubType>
<DefaultName>WebSite</DefaultName>
</TemplateData>
<TemplateContent>
<Project File="WebApplication.webproj">
<ProjectItem>icon.ico</ProjectItem>
<ProjectItem OpenInEditor="true">Default.aspx</ProjectItem>
<ProjectItem>Default.aspx.cs</ProjectItem>
</Project>
</TemplateContent>
</VSTemplate>

See Also
Creating Project and Item Templates Visual Studio Template Schema Reference
How to: Create Starter Kits
10/18/2019 • 2 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version
selector at the top left. We recommend upgrading to Visual Studio 2019. Download it here

A Starter Kit contains code for a complete application and documentation on how to modify or expand the
application. Creating a Starter Kit is fundamentally the same as creating a normal project template, the only
difference being that a Starter Kit contains documentation files that are set to open when a project based on the
Starter Kit is created.

Designing and Developing a Starter Kit


First, you must identify the type of Starter Kit that you want to develop and define your target audience. Next,
design the project and documentation to meet your objectives.
If you are creating a sample application or plug-in:
Create a project that builds without errors.
Add template code to implement additional tasks (optional).
Prepare the documentation.
If you are creating a learning tool:
Create a project that builds without errors.
Organize the resources, such as code snippets and item templates.
Prepare the documentation.

Creating a Template
After you have completed the project and the documentation, you are ready to create the project template for the
Starter Kit. This process is exactly the same as creating a project template.
The following topics contain information about creating templates.
How to: Create Project Templates Explains how to use the Expor t Template wizard to create a template.
How to: Update Existing Templates Describes how to edit an exported template. Use this procedure to modify the
.vstemplate file to customize your Starter Kit.

See Also
Creating Project and Item Templates Customizing Templates Visual Studio Template Schema Reference
How to: Locate and Organize Project and Item
Templates
10/18/2019 • 5 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version
selector at the top left. We recommend upgrading to Visual Studio 2019. Download it here

Template files must be placed in a location that Visual Studio recognizes so that the templates will appear in the
New Project and Add New Item dialog boxes. You can create custom subcategories for templates so that the
subcategories will also appear in the user interface.

Locating Templates
By default, Visual Studio searches two locations for project and item templates. If a compressed file that includes a
.vstemplate file exists in these locations, a template will appear in the New Project or Add New Item dialog
boxes.
Installed Templates
By default, templates installed together with the product are located in:
\VisualStudioInstallationDirectory\Common7\IDE\ItemTemplates\Language\Locale\
\VisualStudioInstallationDirectory\Common7\IDE\ProjectTemplates\Language\Locale\
For example, the following directory contains the Visual Studio project templates for English:
C:\VisualStudioInstallationDirectory\Common7\IDE\ItemTemplates\VisualBasic\1033\
Custom Templates
By default, custom templates are located in:
\My Documents\Visual Studio Version\Templates\ProjectTemplates\Language\
\My Documents\Visual Studio Version\Templates\ItemTemplates\Language\
For example, the following directory contains custom Visual C# project templates:
C:\Documents and Settings\UserName\My Documents\<Visual Studio
version>\Templates\ProjectTemplates\Visual C#\
Custom templates do not include a subdirectory for localized templates. You can change the default
directory for custom templates in the Options dialog box, under Environment\Projects and Solutions .

Organizing Templates
The categories in the New Project and Add New Item dialog boxes reflect the directory structures that exist in
the installed and custom template locations. You can modify these directory structures to organize your templates
in a way that makes sense to you.
NOTE
You cannot create a new category at the programming language level. New categories can only be created within each
language.

If the directory structures for installed and custom templates for a particular language do not have the same
structure (that is, there are directories under one folder that do not exist under the other) the set of categories that
appear in the New Project dialog will be the merger of all categories.
Organizing Installed Templates
You can organize installed templates by creating subdirectories in the programming language folder. These
subdirectories appear in the New Project and Add New Item dialog boxes as virtual folders within each
language.
To c r e a t e n e w i n st a l l e d p r o j e c t t e m p l a t e c a t e g o r i e s

1. Create a folder in the language folder of the installed template directory. For example, to create an Office
category for Visual Studio project templates you would create the following directory:
\VisualStudioInstallationDirectory\Common7\IDE\ProjectTemplates\VisualBasic\1033\Office\
2. Place all the templates for this category in the new folder.
3. Close all instances of Visual Studio.
4. On the Star t menu, click Run , type cmd , and click OK .
5. At the command prompt, locate the directory that contains devenv.exe, and type devenv
/installvstemplates .
6. Run Visual Studio.
7. On the File menu, click New , and then click Project .
8. Verify that the Office category appears in the New Project dialog box, in the Project types pane, under
Visual Basic.
You can also group a subset of the project item templates into a custom folder.
To c r e a t e n e w i n st a l l e d i t e m t e m p l a t e c a t e g o r i e s

1. Create a folder in the language folder of the installed template directory. For example, to create a Web
category for Visual C# item templates you would create the following directory:
\VisualStudioInstallationDirectory\Common7\IDE\ItemTemplates\CSharp\1033\Web\
2. Place all templates for this category in the new folder.
3. Close all instances of Visual Studio.
4. On the Star t menu, click Run , type cmd , and click OK .
5. At the command prompt, locate the directory that contains devenv.exe, and type devenv /setup .
6. Run Visual Studio.
7. Create a project or open an existing project.
8. On the Project menu, click Add New Item .
9. Verify that the Web category appears in the Add New Item dialog box, in the Project types pane.
Organizing Custom Templates
Custom templates can be organized into their own categories by adding new folders in the custom template
location. The New Project dialog box reflects any changes you make to your template categories.
To c r e a t e n e w c u st o m p r o j e c t t e m p l a t e c a t e g o r i e s

1. Create a folder in the language folder in the custom project template directory. For example, to create a
HelloWorld category for Visual C# templates, you would create the following directory:
\My Documents\<Visual Studio version>\Templates\ProjectTemplates\CSharp\HelloWorld\
2. Place all the templates for this category in the new folder.
3. On the File menu, click New , and then click Project .
4. Verify that the HelloWorld category appears in the New Project dialog box, in the Project types pane,
under Visual C#.
You can also group a subset of the custom item templates into a custom folder.
To c r e a t e n e w c u st o m i t e m t e m p l a t e c a t e g o r i e s

1. Create a folder in the language folder in the custom item template directory. For example, to create a
HelloWorld category for Visual C# templates you would create the following directory:
\My Documents\<Visual Studio version>\Templates\ItemTemplates\CSharp\HelloWorld\
2. Place all the templates for this category in the new folder.
3. Create a project or open an existing project.
4. On the Project menu, click Add New Item .
5. Verify that the HelloWorld category appears in the Add New Item dialog box, in the Project types pane.
Displaying Templates in Parent Categories
You can enable templates in subcategories to be displayed in their parent categories by using the
NumberOfParentCategoriesToRollUp element in the .vstemplate file. These steps are identical for both project
templates and item templates.
To d i sp l a y t e m p l a t e s i n p a r e n t c a t e g o r i e s

1. Locate the .zip file that contains the template.


2. Extract the .zip file.
3. Open the .vstemplate file in Visual Studio.
4. In the TemplateData element, add a NumberOfParentCategoriesToRollUp element. For example, the following
code makes the template visible in the parent category, but no higher.

<TemplateData>
...
<NumberOfParentCategoriesToRollUp>
1
</NumberOfParentCategoriesToRollUp>
...
</TemplateData>

5. Save and close the .vstemplate file.


6. Select the files in your template, right-click the selection, click Send To , and then click Compressed
(zipped) Folder . The files are compressed into a .zip file.
7. Delete the extracted template files and the old template .zip file.
8. Put the new .zip file in the directory that had the deleted .zip file.

See Also
Customizing Templates Visual Studio Template Schema Reference NumberOfParentCategoriesToRollUp (Visual
Studio Templates) How to: Create Project Templates How to: Create Item Templates
Customizing Project and Item Templates
10/18/2019 • 2 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version
selector at the top left. We recommend upgrading to Visual Studio 2019. Download it here

After project and item templates have been created, you still have the ability to further customize them to meet
your needs.
For example, you can perform the following tasks:
Modify and export an existing template as a custom template.
For more information, see How to: Update Existing Templates.
Pass custom parameters into a template to replace existing values.
For more information, see How to: Substitute Parameters in a Template.
Customize the wizards that create projects from templates.
For more information, see How to: Use Wizards with Project Templates.

Related Sections
Creating Project and Item Templates
How to: Troubleshoot Templates
How to: Create Project Templates
How to: Create Item Templates
How to: Create Starter Kits
Visual Studio Template Schema Reference
IWizard
How to: Update Existing Templates
10/18/2019 • 2 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version selector
at the top left. We recommend upgrading to Visual Studio 2019. Download it here

After you create a template and compress the files into a .zip file, you may want to modify the template. You can do
this by manually changing the files in the template, or by exporting a new template from a project that is based on
the template.

Using the Export Template Wizard to Update an Existing Template


Visual Studio provides an Expor t Template wizard that can be used to update an existing template.
To use Export Template to update an existing template
1. On the File menu, click New and then click New Project .
2. Select the template that you want to update, enter a name and location for your temporary project, and click
OK .
3. Modify the project in Visual Studio.
4. On the File menu, click Expor t Template , and use the Expor t Template wizard to create a new template.
5. After the updated template is compressed into a .zip file, delete the old template .zip file.

Manually Updating an Existing Template


You can update an existing template outside Visual Studio by modifying the files in the compressed .zip file.
To manually update an existing template
1. Locate the .zip file that contains the template. By default, this file is located in \My Documents\Visual Studio
Version\My Exported Templates\.
2. Extract the .zip file.
3. Modify or delete the current template files, or add new files to the template.
4. Open, modify, and save the .vstemplate XML file to handle updated behavior or new files. For more
information about the .vstemplate schema, see Visual Studio Template Schema Reference. For more
information about what you can parameterize in the source files, see Template Parameters
5. Select the files in your template, right-click, click Send To , and then click Compressed (zipped) Folder .
The files that you selected are compressed into a .zip file.
6. Put the new .zip file in the same directory as the old .zip file.
7. Delete the extracted template files and the old template .zip file.
8. Start (as administrator) an instance of the Developer Command Prompt (on the start menu, under Visual
Studio 2010 / Visual Studio Tools/Developer Command Prompt ).
9. Run the following command: devenv /installvstemplates .
See Also
Customizing Templates Creating Project and Item Templates Visual Studio Template Schema Reference Template
Parameters How to: Create Starter Kits
How to: Substitute Parameters in a Template
10/18/2019 • 2 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version
selector at the top left. We recommend upgrading to Visual Studio 2019. Download it here

You may replace template parameters such as class names and namespaces when a file based on a template is
created. For a complete list of template parameters, see Template Parameters.

Procedure
You may replace parameters in the files of a template whenever a project based on that template is created. This
procedure explains how to create a template that replaces the name of a namespace with the safe project name
when a new project is created with the template.
To use a parameter to replace namespace name with the project name
1. Insert the parameter in one or more of the code files in the template. For example:

namespace $safeprojectname$

NOTE
Template parameters are written in the format $parameter$.

2. In the .vstemplate file for the template, locate the ProjectItem element that includes this file.
3. Set the ReplaceParameters attribute to true for the ProjectItem element. For example:

<ProjectItem ReplaceParameters="true">Class1.cs</ProjectItem>

See Also
Creating Project and Item Templates Template Parameters Visual Studio Template Schema Reference ProjectItem
Element (Visual Studio Item Templates)
How to: Troubleshoot Templates
2/19/2020 • 2 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version selector
at the top left. We recommend upgrading to Visual Studio 2019. Download it here

If a template fails to load in the development environment, there are several ways to locate the problem.

Validating the .vstemplate File


If the .vstemplate file in a template does not adhere to the Visual Studio template schema, the template may not
appear in the New Project dialog box.
To validate the .vstemplate file
1. Locate the .zip file that contains the template.
2. Extract the .zip file.
3. On the File menu in Visual Studio, click Open , and then click File .
4. Select the .vstemplate file for the template, and click Open .
5. Verify that the XML of the .vstemplate file adheres to the Visual Studio template schema. For more
information on the .vstemplate schema, see Visual Studio Template Schema Reference.

NOTE
To get IntelliSense support while authoring the .vstemplate file, add a xmlns attribute to the VSTemplate element
and assign it a value of http://schemas.microsoft.com/developer/vstemplate/2005 .

6. Save and close the .vstemplate file.


7. Select the files included in your template, right-click, select Send To , and click Compressed (zipped)
Folder . The files that you selected are compressed into a .zip file.
8. Place the new .zip file in the same directory as the old .zip file.
9. Delete the extracted template files and the old template .zip file.

Monitoring the Event Log


Visual Studio logs errors encountered when processing template .zip files. If a template does not show up in the
New Project dialog box as expected, you can use Event Viewer to troubleshoot the issue.
To locate template errors in Event Viewer
1. In Windows, click Star t , click Control Panel , double-click Administrative Tools , and then double-click
Event Viewer .
2. In the left pane, click Application .
3. Look for events with a Source value of Visual Studio - VsTemplate .
4. Double-click on a template event to view the error.

See Also
Customizing Templates Creating Project and Item Templates Visual Studio Template Schema Reference
Visual Studio Template Reference
10/18/2019 • 2 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version selector
at the top left. We recommend upgrading to Visual Studio 2019. Download it here

The following links provide reference information about the different aspects of Visual Studio project and item
templates.

In This Section
Visual Studio Template Schema Reference Describes the XML elements used in .vstemplate files.
Template Parameters Describes the parameters available for project and item templates.
Microsoft.VisualStudio.TemplateWizard Describes the IWizard interface and related types.

Related Sections
How to: Create Project Templates
How to: Create Item Templates
Customizing Templates
How to: Create Starter Kits
Template Parameters
10/18/2019 • 3 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version
selector at the top left. We recommend upgrading to Visual Studio 2019. Download it here

By using parameters in your templates, you can replace the values of key portions of the template, such as class
names and namespaces, when the template is instantiated. These parameters are replaced by the template
wizard that runs in the background when a user clicks OK in the New Project or Add New Item dialog boxes.

Declaring and Enabling Template Parameters


Template parameters are declared in the format $parameter$. For example:
$safeprojectname$
$guid1$
$guid5$
To enable parameter substitution in templates
1. In the .vstemplate file of the template, locate the ProjectItem element that corresponds to the item for
which you want to enable parameter replacement.
2. Set the ReplaceParameters attribute of the ProjectItem element to true .
3. In the code file for the project item, include parameters where appropriate. For example, the following
parameter specifies that the safe project name be used for the namespace in a file:

namespace $safeprojectname$

Reserved Template Parameters


The following table lists the reserved template parameters that can be used by any template.

NOTE
Template parameters are case-sensitive.

PA RA M ET ER DESC RIP T IO N

clrversion Current version of the common language runtime (CLR).

GUID [1-10] A GUID used to replace the project GUID in a project file. You
can specify up to 10 unique GUIDs (for example, guid1) .
PA RA M ET ER DESC RIP T IO N

itemname The name provided by the user in the Add New Item dialog
box.

machinename The current computer name (for example, Computer01).

projectname The name provided by the user in the New Project dialog
box.

registeredorganization The registry key value from


HKLM\Software\Microsoft\Windows
NT\CurrentVersion\RegisteredOrganization.

rootnamespace The root namespace of the current project. This parameter


applies only to item templates.

safeitemname The name provided by the user in the Add New Item dialog
box, with all unsafe characters and spaces removed.

safeprojectname The name provided by the user in the New Project dialog
box, with all unsafe characters and spaces removed.

time The current time in the format DD/MM/YYYY 00:00:00.

SpecificSolutionName The name of the solution. When "create solution directory" is


checked, SpecificSolutionName has the solution name.
When "create solution directory" is not checked,
SpecificSolutionName is blank.

userdomain The current user domain.

username The current user name.

webnamespace The name of the current Web site. This parameter is used in
the Web form template to guarantee unique class names. If
the Web site is at the root directory of the Web server, this
template parameter resolves to the root directory of the
Web Server.

year The current year in the format YYYY.

Custom Template Parameters


You can specify your own template parameters and values, in addition to the default reserved template
parameters that are used during parameter replacement.For more information, see CustomParameters Element
(Visual Studio Templates)

Example: Replacing Files Names


You can specify variable file names for project items by using a parameter with the TargetFileName attribute. For
example, you could specify that the .exe file use the project name, specified by $projectname$ , as the file name.
<TemplateContent>
<ProjectItem
ReplaceParameters="true"
TargetFileName="$projectname$.exe">
File1.exe
</ProjectItem>
...
</TemplateContent>

Example: Using the Project Name for the Namespace Name


To use the project name for the namespace in a Visual C# class file, Class1.cs, use the following syntax:

#region Using directives

using System;
using System.Collections.Generic;
using System.Text;

#endregion

namespace $safeprojectname$
{
public class Class1
{
public Class1()
{

}
}
}

In the .vstemplate file for the project template, include the following XML when you reference the file Class1.cs:

<TemplateContent>
<ProjectItem ReplaceParameters="true">
Class1.cs
</ProjectItem>
...
</TemplateContent>

See Also
Customizing Templates
Writing Code in the Code and Text Editor
10/16/2020 • 13 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version
selector at the top left. We recommend upgrading to Visual Studio 2019. Download it here

The Visual Studio editor provides many features that make it easier for you to write and manage your code. You
can expand and collapse different blocks of code by using outlining. You can learn more about the code you are
using by using IntelliSense, the Object Browser , and the Call Hierarchy. You can navigate inside your code by
using features such as Navigate To , Go To Definition , and Find All References . You can insert blocks of code
with code snippets, and you can generate code by using features such as Generate From Usage . If you have
never used the Visual Studio 2015 editor before, see Editing Your Code for a quick overview.
You can view your code in a number of different ways. To see a class view of your solution, you can open the
Class View window or expand the nodes in the Solution Explorer under your class files.
You can search and replace text for single or multiple files. For more information, see Finding and Replacing Text.
If you use regular expressions, note that find and replace now use .NET regular expressions. For more
information, see Using Regular Expressions in Visual Studio.
The different Visual Studio languages offer different sets of features, and in some cases the features behave
differently in different languages. Many of these differences are specified in the descriptions of the features, but
for more information you can see the sections on specific Visual Studio languages.

IMPORTANT
The Visual Studio edition and the settings you are using may affect the features in the IDE. They might differ from those
described in this topic.

Editor Features
F EAT URE DESC RIP T IO N

Syntax Coloring Some syntax elements of code and markup files are colored
differently to distinguish them. For example, keywords (such
as using in C# and Imports in Visual Basic) are one color,
but types (such as Console and Uri ) are another color.
Other syntax elements are also colorized, such as string
literals and comments. C++ uses color to differentiate
among types, enumerations, and macros, among other
tokens.

You can see the default color for each type, and you can
change the color for any specific syntax element in the Fonts
and Colors, Environment, Options Dialog Box, which you can
open from the Tools menu.
F EAT URE DESC RIP T IO N

Error and Warning Marks As you add code and build your solution, you may see (a)
different-colored wavy underlines (known as squiggles) or (b)
light bulbs appearing in your code. Red squiggles denote
syntax errors, blue denotes compiler errors, green denotes
warnings, and purple denotes other types of errors. Light
bulbs suggest fixes for problems and make it easy to apply
the fix.

You can see the default color for each error and warning
squiggle in the Tools/Options/Environment/Fonts and
Colors dialog box. Look for Syntax Error , Compiler Error ,
Warning , and Other Error .

Brace Matching When the insertion point is placed on an open brace in a


code file, both it and the closing brace are highlighted. This
feature gives you immediate feedback on misplaced or
missing braces. You can turn brace matching on or off with
the Automatic Delimiter Highlighting setting
(Tools/Options/Text Editor ). You can change the highlight
color in the Fonts and Colors setting
(Tools/Options/Environment ). Look for Brace Matching
(Highlight) or Brace Matching (Rectangle) .

Line Numbers Line numbers can be displayed in the left margin of the code
window. They are not displayed by default. You can turn this
option on in the Text Editor All Languages settings
(Tools/Options/Text Editor/All Languages ). You can
display line numbers for individual programming languages
by changing the settings for those languages
(Tools/Options/Text Editor/<language> ). For line
numbers to print, you must select Include line numbers in
the Print dialog box.

Change Tracking The color of the left margin allows you to keep track of the
changes you have made in a file. Changes you have made
since the file was opened but not saved are denoted by a
yellow bar on the left margin (known as the selection
margin). After you have saved the changes (but before
closing the file), the bar turns green. If you undo a change
after you have saved the file, the bar turns orange. To turn
this feature off and on, change the Track changes option in
the Text Editor settings (Tools/Options/Text Editor ).

Selecting Code and Text You can select text either in the standard continuous stream
mode or in box mode, in which you select a rectangular
portion of text instead of a set of lines. To make a selection in
box mode, press ALT as you drag the mouse over the
selection (or press ALT + SHIFT + <arrow key>). The
selection includes all of the characters within the rectangle
defined by the first character and the last character in the
selection. Anything typed or pasted into the selected area is
inserted at the same point on each line.
F EAT URE DESC RIP T IO N

Zoom You can zoom in or out in any code window by pressing and
holding the CTRL key and moving the scroll wheel on the
mouse (or CTRL + SHIFT + . to increase and CTRL + SHIFT +
, to decrease). You can also use the Zoom box in the lower
left corner of the code window to set a specific zoom
percentage. The zoom feature does not work in tool
windows.

Virtual Space By default, lines in Visual Studio editors end after the last
character, so that the RIGHT ARROW key at the end of a line
moves the cursor to the beginning of the next line. In some
other editors a line does not end after the last character, and
you can place your cursor anywhere on the line. You can
enable virtual space in the editor in the Tools/Options/Text
Editor/All Languages settings. Note that you can enable
either Vir tual Space or Word Wrap , but not both.

Printing You can use the options in the Print dialog box to include
line numbers or hide collapsed regions of code when you
print a file. In the Page Setup dialog box, you can also
choose to print the full path and the name of the file by
choosing Page header .

You can set color printing options in the


Tools/Options/Environment/Fonts and Colors dialog
box. Choose Printer in the Show settings for list to
customize color printing. You can specify different colors for
printing a file than for editing a file.

Global Undo and Redo The Undo Last Global Action and Redo Last Global
Action commands on the Edit menu undo or redo global
actions that affect multiple files. Global actions include
renaming a class or namespace, performing a find-and-
replace operation across a solution, refactoring a database,
or any other action that changes multiple files. You can apply
the global undo and redo commands to actions in the
current Visual Studio session, even after you close the
solution in which an action was applied.

Advanced Editing Features


You can find a number of advanced features on the Edit/Advanced submenu. Not all these features are
available for all types of code files.

F EAT URE DESC RIP T IO N

Format Document Sets the proper indentation of lines of code and moves curly
braces to separate lines in the document.

Format Selection Sets the proper indentation of lines of code and moves curly
braces to separate lines in the selection.

Tabify Selected Lines Changes leading spaces to tabs where appropriate.


F EAT URE DESC RIP T IO N

Untabify Selected Lines Changes leading tabs to spaces. If you want to convert all
the spaces in your file to tabs (or all the tabs to spaces), you
can use the Edit.ConvertSpacesToTabs and
Edit.ConvertTabsToSpaces commands. These commands
do not appear in Visual Studio menus, but you can call them
from the Quick Access window or the command window.

Make Uppercase Changes all characters in the selection to uppercase, or if


there is no selection, changes the character at the insertion
point to uppercase.

Make Lowercase Changes all characters in the selection to lowercase, or if


there is no selection, changes the character at the insertion
point to lowercase.

Validate Document Validates JScript code files.

Delete Horizontal White Space Deletes tabs or spaces at the end of the current line.

View White Space Displays spaces as raised dots, and tabs as arrows. The end
of a file is displayed as a rectangular glyph. If
Tools/Options/Text Editor/All Languages/Word
Wrap/Show visible glyphs for word wrap is selected,
that glyph is also displayed.

Word Wrap Causes all the lines in a document to be visible in the code
window. You can turn word wrap off and on in the Text Editor
All Languages settings (Tools/Options/ Text Editor/All
Languages ).

Uncomment Selection Adds comment characters to the selection or the current line.

Comment Selection Removes comment characters from the selection or the


current line.

Increase Line Indent Adds a tab (or the equivalent spaces) to the selected lines or
the current line.

Decrease Line Indent Removes a tab (or the equivalent spaces) from the selected
lines or the current line.

Select Tag In a document that contains tags (for example, XML or


HTML), selects the tag.

Select Tag Content In a document that contains tags (for example, XML or
HTML), selects the content.

Navigate in the Code Window


You can move around in a document in several different ways. In addition to the standard operations, you can
use the Navigate Backward (or CTRL + MINUS) and Navigate For ward (CTRL + SHIFT + MINUS) buttons on
the toolbar to move the insertion point to previous locations or return to more recent locations in the active
document. These buttons retain the last 20 locations of the insertion point.
You can also use the enhanced scroll bar in a code window to get a bird’s-eye view of your code. In map mode,
you can see previews of the code when you move the cursor up and down the scroll bar, For more information,
see How to: Track Your Code by Customizing the Scrollbar.
The following commands are code-specific navigation methods:

C OMMAND DESC RIP T IO N

Go To <line number> (Edit/Go To or CTRL + G): Move to a specific line number in


the active document.

Navigate To (Edit/Navigate To or CTRL + ,): Finds a symbol or file in the


active solution. It helps you pick a good set of matching
results from a query. You can search for keywords that are
contained in a symbol by using camel casing and underscore
characters to divide the symbol into keywords.

Find All References (context menu): Finds all the references to the selected
element in the solution.

Go To Definition (context menu or F12): Finds the definition of the selected


element.

Peek Definition (context menu or Alt+F12): Finds the definition of the


selected element and displays it in a popup window. For
more information, see How to: View and Edit Code by Using
Peek Definition (Alt+F12).

Next Method, Previous Method (Edit/Next Method, Previous Method ) In Visual Basic
code files, use these commands to move the insertion point
to different methods.

Reference Highlighting When you click a symbol in the source code, all instances of
that symbol are highlighted in the document. The
highlighted symbols may include declarations and references,
and many other symbols that Find All References would
return. These include the names of classes, objects, variables,
methods, and properties. In Visual Basic code, keywords for
many control structures are also highlighted. To move to the
next or the previous highlighted symbol, press
CTRL+SHIFT+DOWN ARROW or CTRL+SHIFT+UP ARROW.
You can change the highlighting color in
Tools/Options/Environment/Fonts and
Colors/Highlighted Reference.
C OMMAND DESC RIP T IO N

Find code-related info You can find info about specific code, like changes and who
made those changes, references, bugs, work items, code
reviews, and unit test status when you use CodeLens in the
code editor. CodeLens works like a heads-up display when
you use Visual Studio Enterprise with Team Foundation
Server. See Find code changes and other history.

You can also use the navigation bar , that is, the two dropdown boxes displayed at the top of the code window,
to navigate in a code file. This bar allows you to navigate directly to a particular type or to one of the members
within a type. The navigation bar appears with Visual Basic, C#, and C++ code files.
To hide the navigation bar, change the Navigation bar option in the Text Editor All Languages settings
(Tools/Options/Text Editor/All Languages , or you can change the settings for individual languages). You can
navigate in the dropdown boxes as follows:
To shift focus from the code window to the navigation bar, press the shortcut key combination CTRL+F2.
To return focus from the navigation bar to the code window, press the ESC key.
To shift focus from item to item on the navigation bar, press the TAB key.
To select the Navigation bar item that has focus and return to the IDE, press the ENTER key
To navigate to a class or type, click its name in the left dropdown.
To navigate directly to a procedure in a class, click a procedure in the right dropdown.
In a partial class, members defined outside the current code file may be grayed out.

Find code using Navigate To


Visual Studio's "Navigate To" command does a focused search of your code to help you quickly find specified
elements in code files, file paths and code symbols. Unlike other text searches such as Find or Find in Files,
Navigate To limits its search to areas where actual code lives, such as files, forms and code modules. For example,
if you search for a string in an ASP.NET web application using Find or Find in Files in the whole solution, you
might get several hits, including instances of the string in code remarks. By using Navigate To, however, you
might only get a single function, ignoring any instances of the string in code remarks.
Navigate code using Navigate To
1. Open a solution or folder in Visual Studio.
2. On the main menu, choose Edit , Navigate To , or press CTRL + ,.
A small text box appears in the upper corner of the code editor.
3. In the text box, enter the name of the code element you want to find.
As you type, the results appear in a dropdown list below the text box.
4. To go to an element, choose it in the list.
Filter your search
To limit your search to only code symbols, preface your Navigate To query with an "@" character. For example, if
you search for @application , Navigate To displays, for example, only classes that have the word "application" in
them.
If you use camel casing in your code, you can find code elements faster by entering only the capital letters of
code element name. For example, if your code has a component called ViewSwitcher , you can find it by entering
just the capital letters of the name ( "VS" ) in the Navigate To window.

This feature is particularly helpful if your code has long names.

Customize the Editor


Impor t and Expor t Settings : You can share settings with another developer, have your settings conform to a
standard, or return to Visual Studio default settings by using the Impor t and Expor t Settings Wizard on the
Tools menu. You can change general settings or language and project-specific settings.
Keyboard Mapping : You can define new hotkeys or redefine existing ones in the
Tools/Options/Environment/Keyboard settings. For more information about hotkeys, see Default Keyboard
Shortcuts.
For information about language-specific editor options, see the following:
Visual Basic Settings
Using the Visual Studio Development Environment for C#
Options, Text Editor, JavaScript, Formatting
In this section
Finding and Replacing Text
Encodings and Line Breaks
Outlining
Refactoring
Productivity Tips
Using IntelliSense
Customizing the Editor
How to: Track Your Code by Customizing the Scrollbar
How to: View and Edit Code by Using Peek Definition (Alt+F12)
Perform quick actions with light bulbs
Code Snippets
Using the Toolbox
Viewing the Structure of Code
Setting Bookmarks in Code
Using the Task List
Find code changes and other history

See Also
Visual Studio IDE
Finding and Replacing Text
10/18/2019 • 3 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version
selector at the top left. We recommend upgrading to Visual Studio 2019. Download it here

You can find and replace text in the Visual Studio code editor, and certain text-based output windows such as the
Find Results windows, using the Find and Replace control or Find/Replace in Files . You can also search and
replace in some designer windows, such as the XAML designer and the Windows Forms designer, and tool
windows
You can scope searches to the current document, the current solution, or a custom set of folders. You can also
specify a set of file name extensions for multi-file searches. You can customize search syntax by using .NET regular
expressions.
To find and replace regular expressions, see Using Regular Expressions in Visual Studio.

TIP
The Find/Command box is still available as a toolbar control, but is no longer visible by default. You can display the
Find/Command box by choosing Add or Remove Buttons on the Standard toolbar and then choosing Find . For more
information, see Find/Command Box.

Find and Replace control


The Find and Replace control appears in the upper right corner of the code editor window. The Find and
Replace control immediately highlights every occurrence of the given search string in the current document. You
can navigate from one occurrence to another by choosing the Find Next button or the Find Previous button on
the search control.
You can access replacement options by choosing the button next to the Find text box. To make one replacement at
a time, choose the Replace Next button next to the Replace text box. To replace all matches, choose the Replace
All button.
To change the highlight color for matches, choose the Tools menu, select Options , and then choose
Environment , and select Fonts and Colors . In the Show settings for list, select Text Editor , and then in the
Display items list, select Find Highlight (Extension) .
Searching Tool Windows
You can use the Find control in code or text windows, such as Output windows, and Find Results windows, by
choosing Find and Replace on the Edit menu or (CTRL+F).
A version of the Find control is also available in some tool windows. For example, you can now filter the list of
controls in the Toolbox window by entering text in the search box. Other tool windows that now allow you to
search their contents include Solution Explorer , the Proper ties window, and Team Explorer , among others.

Find/Replace in Files
Find/Replace in Files works like the Find and Replace control, except that you can define a scope for your
search. Not only can you search the current open file in the editor, but you can also search all open documents,
the entire solution, the current project, and selected folder sets. You can also search by file name extension. To
access the Find/Replace in Files dialog box, choose Find and Replace on the Edit menu (or CTRL+SHIFT+F).
When you choose Find All , a Find Results window opens and lists the matches for your search. Selecting a
result in the list displays the associated file and highlights the match. If the file is not already open for editing, it is
opened in a preview tab in the right side of the tab well. You can use the Find control to search through the Find
Results list.
Creating Custom Search Folder Sets
You can define a search scope by choosing the Choose Search Folders button (it looks like … ) next to the Look
in box. In the Choose Search Folders dialog box, you can specify a set of folders in which to search, and you
can save the specification so that you can reuse it later. You can specify folders on a remote machine only if you
have mapped its drive to the local machine.
Creating Custom Component Sets
You can define component sets as your search scope by choosing the Edit Custom Component Set button next
to the Look in box. You can specify installed .NET or COM components, Visual Studio projects that are included in
your solution, or any assembly or type library (.dll, .tlb, .olb, .exe, or .ocx). To search references, select the Look in
references box.

See Also
Using Regular Expressions in Visual Studio
Use Regular Expressions in Visual Studio
10/18/2019 • 4 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version
selector at the top left. We recommend upgrading to Visual Studio 2019. Download it here

Visual Studio uses .NET Framework regular expressions to find and replace text. For more information about .NET
regular expressions, see .NET Framework Regular Expressions.
Before Visual Studio 2012, Visual Studio used custom regular expression syntax in the Find and Replace windows.
See Visual Studio Regular Expression Conversions for an explanation of how to convert some of the more
commonly-used custom regular expression symbols to the .NET versions.

TIP
In Windows operating systems, most lines end in “\r\n” (a carriage return followed by a new line). These characters are not
visible, but are present in the editor and are passed to the .NET Regular Expression service.

TIP
For information about regular expressions that are used in replacement patterns, see Substitutions. To use a numbered
capture group, the syntax is $1 to specify the numbered group and (x) to specify the group in question. For example,
the grouped regular expression (\d)([a-z]) finds four matches in the following string: 1a 2b 3c 4d . The replacement
string z$1 converts that string to z1 z2 z3 z4 .

Regular expression examples


Here are some examples:

P URP O SE EXP RESSIO N EXA M P L E

Match any single character (except a . a.o matches "aro" in "around" and
line break) "abo" in "about" but not "acro" in
"across".

Match zero or more occurrences of the * a*r matches "r" in "rack", "ar" in "ark",
preceding expression (match as many and "aar" in "aardvark"
characters as possible)

Match any character zero or more .* c.*e matches “cke” in “racket”, “comme”
times (Wildcard *) in “comment”, and “code” in “code”

Match one or more occurrences of the + e.+e matches "eede" in "feeder" but
preceding expression (match as many not "ee".
characters as possible)
P URP O SE EXP RESSIO N EXA M P L E

Match any character one or more .+ e.+e matches "eede" in "feeder" but not
times (Wildcard ?) "ee".

Match zero or more occurrences of the *? e.*?e matches "ee" in "feeder" but
preceding expression (match as few not "eede".
characters as possible)

Match one or more occurrences of the +? e.+?e matches "ente" and "erprise" in
preceding expression (match as few "enterprise", but not the whole word
characters as possible) "enterprise".

Anchor the match string to the ^ ^car matches the word "car" only
beginning of a line or string when it appears at the beginning of a
line.

Anchor the match string to the end of \r?$ End\r?$ matches "end" only when it
a line appears at the end of a line.

Match any single character in a set [abc] b[abc] matches "ba", "bb", and "bc".

Match any character in a range of [a-f] be[n-t] matches "bet" in "between",


characters "ben" in "beneath", and "bes" in
"beside", but not "below".

Capture and implicitly number the () ([a-z])X\1 matches "aXa"and "bXb",


expression contained within but not "aXb". ". “\1” refers to the first
parenthesis expression group “[a-z]”.

Invalidate a match (?!abc) real (?!ity) matches "real" in


"realty" and "really" but not in "reality."
It also finds the second "real" (but not
the first "real") in "realityreal".

Match any character that is not in a [^abc] be[^n-t] matches "bef" in "before",
given set of characters "beh" in "behind", and "bel" in "below",
but not "beneath".

Match either the expression before or | (sponge&#124;mud) bath matches


the one after the symbol. "sponge bath" and "mud bath."

Escape the character following the | \^ matches the character ^.


backslash

Specify the number of occurrences of {x}, where x is the number of x(ab){2}x matches "xababx", and
the preceding character or group occurrences x(ab){2,3}x matches "xababx" and
"xabababx" but not "xababababx".

Match text in a Unicode character class, \p{X} \p{Lu} matches "T" and "D" in
where “X” is the Unicode number. For "Thomas Doe".
more information about Unicode
character classes, see

Unicode Standard 5.2 Character


Properties.
P URP O SE EXP RESSIO N EXA M P L E

Match a word boundary \b (Outside a character class \b \bin matches "in" in "inside" but not
specifies a word boundary, and inside a "pinto".
character class specifies a backspace).

Match a line break (ie a carriage return \r?\n End\r?\nBegin matches "End" and
followed by a new line). "Begin" only when "End" is the last
string in a line and "Begin" is the first
string in the next line.

Match any alphanumeric character \w a\wd matches "add" and "a1d" but
not "a d".

Match any whitespace character. (?([^\r\n])\s) Public\sInterface matches the


phrase "Public Interface".

Match any numeric character \d \d matches and "3" in "3456", "2" in


23", and "1" in "1".

Match a Unicode character \uXXXX where XXXX specifies the \u0065 matches the character "e".
Unicode character value.

Match an identifier \b(\w+|[\w-[0-9\]]\w*)\b Matches "type1" but not &type1" or


"#define".

Match a string inside quotes ((\".+?\")|('.+?')) Matches any string inside single or
double quotes.

Match a hexadecimal number \b0[xX]([0-9a-fA-F])\b Matches "0xc67f" but not "0xc67fc67f".

Match integers and decimals \b[0-9]*\.*[0-9]+\b Matches "1.333".


Find/Command Box
10/18/2019 • 2 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version
selector at the top left. We recommend upgrading to Visual Studio 2019. Download it here

You can search for text and run Visual Studio commands from the Find/Command box. The Find/Command
box is still available as a toolbar control, but is no longer visible by default. You can display the
Find/Command box by choosing Add or Remove Buttons on the Standard toolbar and then choosing
Find .
To run a Visual Studio command, preface it with a greater than (>) sign.
The Find/Command box retains the last 20 items entered and displays them in a drop-down list. You can
navigate through the list by choosing the arrow keys.

Find/Command Box

Searching for Text


By default, when you specify text in the Find/Command box and then choose the ENTER key, Visual Studio
searches the current document or tool window using the options that are specified in the Find in Files dialog
box. For more information, see Finding and Replacing Text.

Entering Commands
To use the Find/Command box to issue a single Visual Studio command or alias rather than search for text,
enter the Visual Studio command, prefaced with a greater than (>) symbol. For example:

>File.NewFile c:\temp\MyFile /t:"General\Text File"

Alternatively, you can also use the Command window to enter and execute single or multiple commands. Some
commands or aliases can be entered and executed by themselves; others have required arguments in their
syntax. For a list of commands that have arguments, see Visual Studio Commands.

Escape Characters
A caret (^) character in a command line means that the character immediately following it is interpreted
literally, rather than as a control character. This can be used to embed straight quotation marks ("), spaces,
leading slashes, carets, or any other literal characters in a parameter or switch value, with the exception of
switch names. For example,

>Edit.Find ^^t /regex

A caret functions the same whether it is inside or outside quotation marks. If a caret is the last character on the
line, it is ignored.
See Also
Command Window Finding and Replacing Text
Find in Files
10/18/2019 • 3 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version selector
at the top left. We recommend upgrading to Visual Studio 2019. Download it here

Find in Files** allows you to search a specified set of files. The matches found and actions taken are listed in the
Find Results window selected in Result options .
You can use any of the following methods to display Find in Files in the Find and Replace window.
To display Find in Files
1. On the menu bar, choose Edit , Find and Replace .
2. Choose Find in Files .
To cancel a Find operation, press CTRL + BREAK.

NOTE
The Find and Replace tool does not search directories with the Hidden or System attribute set.

Find what
To search for a new text string or expression, specify it in the box. To search for any of the 20 strings that you
searched for most recently, open the list, and choose the string for which you want to search. Choose the adjacent
Expression Builder button if you want to use one or more regular expressions in your search string. For more
information, see Using Regular Expressions in Visual Studio.

Look in
The option chosen from the Look in drop-down list determines whether Find in Files searches only in currently
active files or in all files stored within certain folders. Select a search scope from the list or click the Browse (...)
button to display the Choose Search Folders dialog box and to enter your own set of directories. You can also
type a path directly into the Look in box.

WARNING
With the Entire Solution or Current Project options, project and solution files are not searched. If you want to look in
project files, choose a search folder.

NOTE
If the Look in option selected causes you to search a file that you have checked out from source code control, only the
version of that file which has been downloaded to your local machine is searched.
Include subfolders
Specifies that subfolders of the Look in folder will be searched.

Find options
You can expand or collapse the Find options section. The following options can be selected or cleared:
Match case When selected, a Find Results search will be case-sensitive
Match whole word When selected, the Find Results windows will only return whole word matches.
Use Regular Expressions If this check box is selected, you can use special notations to define patterns of text to
match in the Find what or Replace with text boxes. For a list of these notations, see Using Regular Expressions in
Visual Studio.
Look at these file types This list indicates the types of files to search through in the Look in directories. If this field
is blank, all of the files in the Look in directories will be searched.
Select any item in the list to enter a preconfigured search string that will find files of those particular types.

Result options
You can expand or collapse the Result options section. The following options can be selected or cleared:
Find results 1 window When selected, the results of the current search will replace the content of the Find Results
1 window. This window opens automatically to display your search results. To open this window manually, select
Other Windows from the View menu and choose Find Results 1 .
Find results 2 window When selected, the results of the current search will replace the content of the Find Results
2 window. This window opens automatically to display your search results. To open this window manually, select
Other Windows from the View menu and choose Find Results 2 .
Display file names only Displays a list of files containing search matches rather than displaying the search matches
themselves.
Append results Appends the results from the search to the previous search results.

See Also
Finding and Replacing Text Replace in Files Visual Studio Commands
Replace in Files
10/18/2019 • 4 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version selector
at the top left. We recommend upgrading to Visual Studio 2019. Download it here

Replace in Files** allows you to search the code of a specified set of files for a string or expression, and change
some or all of the matches found. The matches found and actions taken are listed in the Find Results window
selected in Result options .

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
Customizing Development Settings in Visual Studio.

You can use any of the following methods to display Replace in Files in the Find and Replace window.
To display Replace in Files
1. On the Edit menu, expand Find and Replace .
2. Choose Replace in Files .
— or —
If the Find and Replace window is already open, on the toolbar, choose Replace in Files .

Find what
To search for a new text string or expression, specify it in the box. To search for any of the 20 strings that you
searched for most recently, open the list, and choose the string for which you want to search. Choose the adjacent
Expression Builder button if you want to use one or more regular expressions in your search string. For more
information, see Using Regular Expressions in Visual Studio.

Replace With
To replace instances of the string in the Find what box with another string, enter the replacement string in the
Replace With box. To delete instances of the string in the Find what box, leave this field blank. Open the list to
display the 20 strings for which you searched most recently. Choose the adjacent Expression Builder button if
you want to use one or more regular expressions in your replacement string. For more information, see Using
Regular Expressions in Visual Studio.

Look in
The option chosen from the Look in drop-down list determines whether Replace in Files searches only in
currently active files or searches all files stored within certain folders. Select a search scope from the list, type a
folder path, or click the Browse (...) button to display the Choose Search Folders dialog box and choose a set of
folders to search. You can also type a path directly into the Look in box.
NOTE
If the Look in option selected causes you to search a file that you have checked out from source code control, only the
version of that file which has been downloaded to your local machine is searched.

Find options
You can expand or collapse the Find options section. The following options can be selected or cleared:
Match case When selected, the Find Results windows will only display instances of the Find what string that are
matched both by content and by case. For example, a search for "MyObject" with Match case selected will return
"MyObject" but not "myobject" or "MYOBJECT."
Match whole word When selected, the Find Results windows will only display instances of the Find what string
that are matched in complete words. For example, a search for "MyObject" will return "MyObject" but not
"CMyObject" or "MyObjectC."
Use Regular Expressions When this check box is selected, you can use special notations to define patterns of text in
the Find what or Replace with text boxes. For a list of these notations, see Using Regular Expressions in Visual
Studio.
Look at these file types This list indicates the types of files to search through in the Look in directories. If this field
is left blank, all of the files in the Look in directories will be searched.
Select any item in the list to enter a preconfigured search string that will find files of those particular types.

Result options
You can expand or collapse the Result options section. The following options can be selected or cleared:
Find Results 1 window When selected, the results of the current search will replace the content of the Find Results
1 window. This window opens automatically to display your search results. To open this window manually, select
Other Windows from the View menu and choose Find Results 1 .
Find Results 2 window When selected, the results of the current search will replace the content of the Find Results
2 window. This window opens automatically to display your search results. To open this window manually, select
Other Windows from the View menu and choose Find Results 2 .
Display file names only When this check box is selected, the Find Results windows list the full names and paths for
all files that contain the search string. However, the results don't include the line of code where the string appears.
This check box is available for Find in Files only.
Keep modified files open after Replace All When selected, leaves open all files in which replacements have been
made, so you can undo or save the changes. Memory constraints might limit the number of files that can remain
open after a replace operation.
Cau t i on

You can use Undo only on files that remain open for editing. If this option is not selected, files that were not
already open for editing will remain closed, and no Undo option will be available in those files.

See Also
Finding and Replacing Text Find in Files Visual Studio Commands
Encodings and Line Breaks
10/18/2019 • 2 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version selector
at the top left. We recommend upgrading to Visual Studio 2019. Download it here

In Visual Studio you can use the File/Advanced Save Options settings to determine the type of line break
characters you want. You can also change the encoding of a file with the same settings.

NOTE
If you have certain types of development settings (Visual Basic, F#, Web Development) you may not see Advanced Save
Options on the menu. To change your settings (for example to General), open Tools / Impor t and Expor t Settings . For
more information, see Customizing Development Settings in Visual Studio.

In Visual Studio the following characters are interpreted as line breaks:


CRLF: Carriage return + line feed, Unicode characters 000D + 000A
LF: Line feed, Unicode character 000A
NEL: Next line, Unicode character 0085
LS: Line separator, Unicode character 2028
PS: Paragraph separator, Unicode character 2029
Text that is copied from other applications keeps the original encoding and line break characters. For
example, when you copy text from Notepad and paste it into a text file in Visual Studio, the text has the same
settings that it had in Notepad.
When you open a file that has a different line break characters, you may see a dialog box that asks whether
the inconsistent line break characters should be normalized and which type of line breaks to choose.
Outlining
10/16/2020 • 2 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version selector
at the top left. We recommend upgrading to Visual Studio 2019. Download it here

You can choose to hide some code from view by collapsing a region of code so that it appears under a plus sign
(+). You expand a collapsed region by clicking the plus sign. (Or you can press CTRL + M + M to collapse a region
and then CTRL+ M + M to expand it again.) You can also collapse an outlining region by double-clicking any line in
the region on the outlining margin, which appears just to the left of the code. You can see the contents of a
collapsed region as a tooltip when you hover over the collapsed region.
Regions in the outlining margin are also highlighted when you hover over the margin with the mouse. The default
highlighting color may seem rather faint in some color configurations. You can change it in
Tools/Options/Environment/Fonts and Colors/Collapsible Region .
When you work in outlined code, you can expand the sections you want to work on, collapse them when you are
done, and then move to other sections. When you do not wish to have outlining displayed, you can use the Stop
Outlining command to remove the outline information without disturbing your underlying code.
The Undo and Redo commands on the Edit menu affect these actions. The Copy , Cut , Paste , and drag-and-drop
operations retain outlining information, but not the state of the collapsible region. For example, when you copy a
region that is collapsed, the Paste operation will paste the copied text as an expanded region.
Cau t i on

When you change an outlined region, the outlining may be lost. For example, deletions or Find and Replace
operations may erase the end of the region.
The following commands can be found on the Edit/Outlining submenu.

C OMMAND DESC RIP T IO N

Hide Selection (CTRL + M , CTRL + H) - Collapses a selected block of code


that would not normally be available for outlining, for example
an if block. To remove the custom region, use Stop
Hiding Current (or CTRL + M, CTRL + U). Not available in
Visual Basic.

Toggle Outlining Expansion - Reverses the current hidden or expanded state of the
innermost outlining section when the cursor lies in a nested
collapsed section.

Toggle All Outlining (CTRL + M, CTRL + L) - Sets all regions to the same collapsed
or expanded state. If some regions are expanded and some
collapsed, then the collapsed regions are expanded.

Stop Outlining (CTRL + M, CTRL + P) - Removes all outlining information for


the entire document.
C OMMAND DESC RIP T IO N

Stop Hiding Current (CTRL + M, CTRL + U) - Removes the outlining information


for the currently selected user-defined region. Not available in
Visual Basic.

Collapse to Definitions (CTRL + M, CTRL + O) - Collapses the members of all types.

Collapse Block:<logical boundary> (Visual C++) Collapses a region in the function containing the
insertion point. For example, if the insertion point lies inside a
loop, the loop is hidden.

Collapse All in: <logical structures> (Visual C++) Collapses all the structures inside the function.

You can also use the Visual Studio SDK to define the text regions you want to expand or collapse. See Walkthrough:
Outlining.
Refactoring in Visual Studio
10/18/2019 • 2 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version selector
at the top left. We recommend upgrading to Visual Studio 2019. Download it here

Refactoring is the process of modifying code in order to make it easier to maintain, understand, and extend, but
without changing its behavior. Some common refactorings include:
1. splitting long functions into smaller ones
2. renaming variables, types, functions or parameters
3. reordering parameters
4. removing or reordering using directives
Because the logic of refactoring is closely tied to language syntax, each language service in Visual Studio
provides its own refactoring capabilities. For more information, see the following pages:
Refactoring in C#
Refactoring (C#)
Refactoring in Visual Basic
Refactoring and Rename Dialog Box (Visual Basic)
Refactoring in C++
Writing and refactoring code (C++)
Refactoring in F#
Refactoring support for F# is provided in Visual F# Power Tools, a third-party Visual Studio extension.

See Also
Visual Studio IDE Writing Code in the Code and Text Editor
Productivity Tips for Visual Studio
10/18/2019 • 8 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version
selector at the top left. We recommend upgrading to Visual Studio 2019. Download it here

By following these tips, you can more quickly and efficiently write, navigate, and debug your code in Visual Studio.
For more information about common keyboard shortcuts, see Tips and Tricks. For a more complete list, see
Identifying and Customizing Keyboard Shortcuts and Default Keyboard Shortcuts.
This topic includes the following sections:
Accessing Visual Studio Tools
Writing Code
Navigating Within Your Code
Finding Items Faster
Debugging Code
Managing Files, Toolbars, and Windows

Accessing Visual Studio Tools


You can more easily access the Developer Command Prompt or another tool if you pin it to the Start screen or the
taskbar.
1. From the Start screen, enter Visual Studio Tools , and then choose the Enter key.
2. In File Explorer , open the shortcut menu for the item that you want:
Build Notifications
Debuggable Package Manager
Developer Command Prompt for VS2013
Microsoft Feedback Client 2013
VS2013 ARM Cross Tools Command Prompt
VS2013 x64 Cross Tools Command Prompt
VS2013 x64 Native Tools Command Prompt
VS2013 x86 Native Tools Command Prompt
3. Choose Pin to Star t or Pin to Taskbar .

Writing Code
Write code more quickly by using the following features.
Use sample applications . You can speed up application development by downloading and installing
sample applications from the MSDN Code Gallery. You can also learn a particular technology or
programming concept by downloading and exploring a Sample Pack for that area.
Use IntelliSense . As you enter code in the editor, IntelliSense information, such as List Members,
Parameter Info, Quick Info, Signature Help, and Complete Word, appears. These features support fuzzy
matching of text; for example, the results lists for List Members includes not only entries that start with the
characters that you have entered but also entries that contain the character combination anywhere in their
names. For more information, see Using IntelliSense.
Change auto-inser tion of IntelliSense options as you enter code . By switching IntelliSense to
suggestion mode, you can specify that IntelliSense options are inserted only if you explicitly choose them.
To enable suggestion mode, choose the Ctrl + Alt + Spacebar keys, or, on the menu bar, choose Edit ,
IntelliSense , Toggle Completion Mode .
Use code snippets . You can use built-in snippets or create your own snippets.
To insert a snippet, on the menu bar, choose Edit , IntelliSense , Inser t Snippet or open the shortcut menu
in a file and choose Inser t Snippet . For more information, see Code Snippets.
Fix code errors inline . Smart Tags appear as blue or red boxes under a line of code. You can display
Smart Tag options by pointing to one of the boxes or by placing the cursor in the line of code and choosing
the Ctrl + . (period) keys.
Blue boxes suggest ways to fix errors in your code.
Figure 1: Error Smart Tags

Red boxes suggest ways to refactor your code.


Figure 2: Refactoring Smart Tags
Show and edit the definition of a code element . You can quickly show and edit the module in which a
code element, such as a member, a variable, or a local, is defined.
To open a definition in a pop-up window, highlight the element and then choose the Alt+F12 keys, or open
the shortcut menu for the element and then choose Peek Definition . To open a definition in a separate
code window, open the shortcut menu for the element, and then choose Go to Definition .

Navigating Within Your Code


You can use various techniques to find and move to specific locations in your code more quickly.
Bookmark lines of code . You can use bookmarks to navigate quickly to specific lines of code in a file.
To set a bookmark, on the menu bar, choose Edit , Bookmarks , Toggle Bookmark . You can view all of the
bookmarks for a solution in the Bookmarks window. For more information, see Setting Bookmarks in
Code.
Search for symbol definitions in a file . You can search within a solution to locate symbol definitions
and file names, but search results don’t include namespaces or local variables.
To access this feature, on the menu bar, choose Edit , Navigate To .
Browse the overall structure of your code . In Solution Explorer , you can search and browse classes
and their types and members in your projects. You can also search for symbols, view a method’s Call
Hierarchy, find symbol references, and perform other tasks. If you choose a code element in Solution
Explorer , the associated file opens in a Preview tab, and the cursor moves to the element in the file. For
more information, see Viewing the Structure of Code.

Finding Items Faster


You can search across the IDE for commands, files, and options, in addition to filtering the contents of tool
windows to show only relevant information for your current task.
Filter the contents of tool windows . You can search within the contents of many tool windows, such as
the Toolbox , the Proper ties window, and Solution Explorer , but display only items whose names
contain the characters that you specify.
Display only the errors you want to address . If you choose the Filter button on the Error List
toolbar, you can reduce the number of errors that appear in the Error List window. You can display only the
errors in the files that are open in the editor, only the errors in the current file, or only the errors in the
current project. You can also search within the Error List window to find specific errors.
Find dialog boxes, menu commands, and options . In the Quick Launch, Environment, Options Dialog
Box box, enter keywords or phrases for the items that you’re trying to find. For example, the following
options appear if you enter new project :
Figure 3: Quick Launch results list for new project
Quick Launch displays links to the New Project dialog box, the Add New Item dialog box, and the
Projects and Solutions page in the Options dialog box, among others. Quick Launch results can also
include project files and tool windows.

Debugging Code
Debugging can consume a lot of time, but the following tips can help you speed up the process.
Test the same page, application, or site in different browsers . As you debug your code, you can
easily switch among the installed web browsers, including Page Inspector (Visual Studio), without having to
open the Browse With dialog box. You can use the Debug Target list, which is on the Standard toolbar
next to the Star t Debugging button, to quickly verify which browser you’re using as you debug or view
pages.

Set temporar y breakpoints . You can create a temporary breakpoint in the current line of code and start
the debugger simultaneously. When you hit that line of code, the debugger enters break mode. For more
information, see Navigating through Code with the Debugger.
To use this feature, choose the Ctrl + F10 keys, or open the shortcut menu for the line of code on which you
want to break, and then choose Run To Cursor .
Move the execution point during debugging . You can move the current execution point to a different
section of code and then restart debugging from that point. This technique is useful if you want to debug a
section of code without having to recreate all of the steps that are required to reach that section. For more
information, see Navigating through Code with the Debugger.
To move the execution point, drag the yellow arrowhead to a location where you want to set the next
statement in the same source file, and then choose the F5 key to continue debugging.
Capture value information for variables . You can add a DataTip to a variable in your code and pin it so
that you can access the last known value for the variable after debugging has finished. For more
information, see View data values in Data Tips.
To add a DataTip, the debugger must be in break mode. Place the cursor on the variable, and then choose
the pin button on the DataTip that appears. When debugging is stopped, a blue pin icon appears in the
source file next to the line of code that contains the variable. If you point to the blue pin, the value of the
variable from the most recent debugging session appears.
Clear the Immediate window . You can erase the contents of the Immediate Window at design time by
entering >cls or >Edit.ClearAll
For more information about additional commands, see Visual Studio Command Aliases.

Managing Files, Toolbars, and Windows


At any one time, you may be working in multiple code files and moving among several tool windows as you
develop an application. You can keep organized by using the following tips.
Keep files that you frequently use visible in the editor . You can pin files to the left side of the tab
well so that they remain visible regardless of how many files are open in the editor.
To pin a file, choose the file’s tab, and then choose the Toggle Pin Status button.
Move documents and windows to other monitors . If you use more than one monitor when you
develop applications, you can work on portions of your application more easily by moving files that are
open in the editor to another monitor. You can also move tool windows, such as debugger windows, to
another monitor and tab dock document and tool windows together to create “rafts.” For more information,
see How to: Arrange and Dock Windows.
You can also manage files more easily by creating another instance of Solution Explorer and moving it to
another monitor. To create another instance of Solution Explorer , open a shortcut menu in Solution
Explorer , and then choose New Solution Explorer View .
Customize the fonts that appear in Visual Studio . You can change the font face, size, and color that’s
used for text in the IDE. For example, you can customize the color of specific code elements in the editor and
the font face in tool windows or throughout the IDE. For more information, see How to: Change Fonts and
Colors and How to: Change Fonts and Colors in the Editor.

See Also
Default Keyboard Shortcuts for Frequently Used Commands How to: Customize Menus and Toolbars Walkthrough:
Create a Simple Application Accessibility Tips and Tricks
Tips and Tricks for Visual Studio
10/16/2020 • 2 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version selector
at the top left. We recommend upgrading to Visual Studio 2019. Download it here

You can navigate in Visual Studio more easily by using the shortcuts in this topic. For more general information,
see Keyboard Shortcuts in Visual Studio. For information about how to optimize Visual Studio for accessibility, see
Accessibility Tips and Tricks.
Window Management
Window Shortcuts
Visual Studio Search
Editor Find
Code Editor
Toolbars
Debugging
Application Lifecycle Management

Window Management
C OMMAND SH O RTC UT

Drag Off Floating Tab Wells Ctrl+click for multi-select

Maximize Floating Window Double-click on title bar

Re-dock Floating Window Ctrl+double-click title bar

Close Active Document Ctrl+F4

Show Open File List Ctrl+Alt+Down

Show All Floating Windows Ctrl+Shift+M

Window Shortcuts
C OMMAND SH O RTC UT

Move/Dock Floating Windows Win+Left / Win+Right

Maximize/Minimize Windows Win+Up / Win+Down


C OMMAND SH O RTC UT

Show Jump List Win+Alt+n

Start New Instance Win+Shift+n

Switch Between Windows Win+n

Visual Studio Search


C OMMAND SH O RTC UT

Solution Explorer Search Ctrl+;

Place Focus in Search box in any tool window Alt+` when the tool window has focus

Quick Launch Ctrl+Q

Quick Launch Scope Results - @opt Options


- @cmd Commands
- @mru Most recently used
- @doc Open documents

Search in Tools Options Ctrl+E

Editor Find
C OMMAND SH O RTC UT

Quick Find Ctrl+F

Quick Find Next Result Enter

Quick Find Previous Result Shift+Enter

Quick Find Expand Drop Down Alt+Down

Dismiss Find Esc

Quick Replace Ctrl+H

Quick Replace Replace Next Alt+R

Quick Replace Replace All Alt+A

Find in Files Ctrl+Shift+F

Replace in Files Ctrl+Shift+H


Code Editor
C OMMAND SH O RTC UT

IntelliSense Suggestion Mode Ctrl+Alt+Space (Toggle)

Force Show IntelliSense Ctrl+J

Smart Tags Ctrl+.

Snippet Picker Ctrl+K,X or ?,Tab (VB)

Surround With Ctrl+K,S

Show Quick Info Ctrl+K,I

Navigate To Ctrl+,

Go To Definition F12

Peek Definition Alt+F12

Go To Definition Stack Ctrl+Shift+8 (Back), Ctrl+Shift+7 (Forward)

Navigate Highlighted References Ctrl+Shift+Up (Previous), Ctrl+Shift+Down (Next)

Editor Zoom Ctrl+Shift+> (In), Ctrl+Shift+< (Out)

Block Selection Hold Alt and drag mouse, Shift+Alt+Arrow Keys

Move Line Up/Down Alt+Up / Alt+Down

Peek Definition Alt+F12

Close the Peek Definition window Esc

Promote the Peek Definition window to a regular document Ctrl+Alt+Home


tab

Navigate between multiple Peek Definition windows Ctrl+Alt+- and Ctrl+Alt+=

Navigate between multiple Peek results F8 and Shift+F8

Toggle between the code editor window and the Peek Shift+Esc
Definition window

Toolbars
C OMMAND SH O RTC UT

Add Buttons Click toolbar overflow button


C OMMAND SH O RTC UT

Find Combo in Standard toolbar Ctrl+D

Find Textbox Command Mode Type “>”

Create new alias >alias NewAlias Command

Debugging
C OMMAND SH O RTC UT

Start Debugging F5

Stop Debugging Shift+F5

Restart Debugging Ctrl+Shift+F5

Step Over F10

Step Into F11

Step Out Shift+F11

Run To Cursor Ctrl+F10

Set Next Statement Ctrl+Shift+F10

Set and Toggle Breakpoint F9

Disable Breakpoint Ctrl+F9

Immediate Window Ctrl+Alt+I

Immediate Window Command Mode Type “>”

Immediate Window Clear Buffer >cls

Immediate Window Print Value ?varname

Application Lifecycle Management


See Keyboard shortcuts: Visual Studio Online, TFS web portal, and Team Explorer.

See Also
Visual Studio Blog
Visual Studio Tips and Tricks Blog
Visual Studio Toolbox on Channel 9
Identifying and Customizing Keyboard Shortcuts in
Visual Studio
10/18/2019 • 4 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version
selector at the top left. We recommend upgrading to Visual Studio 2019. Download it here

You can identify keyboard shortcuts for Visual Studio commands, customize those shortcuts, and export them for
others to use. Many shortcuts always invoke the same commands, but the behavior of a shortcut can vary based
on the following conditions:
Which default environment settings you chose the first time that you ran Visual Studio (for example,
General Development or Visual C#).
Whether you've customized the shortcut's behavior.
Which context you're in when you choose the shortcut. For example, the F2 shortcut invokes the
Edit.EditCell command if you're using the Settings Designer and the File.Rename command if you're using
Team Explorer.
Regardless of settings, customization, and context, you can always find and change a keyboard shortcut in
the Options dialog box. You can also look up the default keyboard shortcuts for several dozen commands
in Default Keyboard Shortcuts for Frequently Used Commands, and you can find a complete list of all
default shortcuts (based on the General Development Settings) in Default Keyboard Shortcuts.
In this topic
Identifying a keyboard shortcut
Customizing a keyboard shortcut
Sharing custom keyboard shortcuts
If a shortcut is assigned to a command in the Global context and no other contexts, that shortcut will
always invoke that command. But a shortcut can be assigned to one command in the Global context and a
different command in a specific context. If you use such a shortcut when you're in the specific context, the
shortcut invokes the command for the specific context, not the Global context.

NOTE
Your settings and edition of Visual Studio might change the names and locations of menu commands and the options that
appear in dialog boxes. This topic is based on the General Development Settings .

Identifying a keyboard shortcut


1. On the menu bar, choose Tools , Options .
2. Expand Environment , and then choose Keyboard .
3. In the Show commands containing box, enter all or part of the name of the command without spaces.
For example, you can find commands for solutionexplorer .
4. In the list, choose the correct command.
For example, you can choose View.SolutionExplorer .
5. If the command has a keyboard shortcut, it appears in the Shor tcut(s) for selected command list.

Customizing a keyboard shortcut


1. On the menu bar, choose Tools , Options .
2. Expand the Environment folder, and then choose Keyboard .
3. In the Show commands containing box, enter all or part of the name of the command without spaces.
For example, you can find commands for solutionexplorer .
4. In the list, choose the command to which you want to assign a keyboard shortcut.
5. In the Use new shor tcut in list, choose the feature area in which you want to use the shortcut.
For example, you can choose Global if you want the shortcut to work in all contexts. You can use any
shortcut that isn't mapped (as Global) in another editor. Otherwise, the editor overrides the shortcut.

NOTE
You can't assign the following keys as part of a keyboard shortcut in Global: Print Scrn/Sys Rq, Scroll Lock,
Pause/Break, Tab, Caps Lock, Insert, Home, End, Page Up, Page Down, the Windows logo key, the Application key,
any of the Arrow keys, or Enter; Num Lock, Delete, or Clear on the numeric keypad; or Ctrl+Alt+Delete.

6. In the Press shor tcut key(s) box, enter the shortcut that you want to use.

NOTE
You can create a shortcut that combines a letter with the Alt key, the Ctrl key, or both. You can also create a
shortcut that combines the Shift key and a letter with the Alt key, the Ctrl key, or both.

If a shortcut is already assigned to another command, it appears in the Shor tcut currently used by box.
In that case, choose the Backspace key to delete that shortcut before you try a different one.

7. Choose the Assign button.

NOTE
If you specify a different shortcut for a command, choose the Assign button, and then choose the Cancel button,
the dialog box closes, but the change isn't reverted.

Sharing custom keyboard shortcuts


You can share your custom keyboard shortcuts by exporting them to a file and then giving the file to others so
that they can import the data.
To export only keyboard shortcuts
1. On the menu bar, choose Tools , Impor t and Expor t Settings .
2. Choose Expor t selected environment settings , and then choose the Next button.
3. Under What settings do you want to expor t? , clear the All Settings check box, expand Options , and
then expand Environment .
4. Select the Keyboard check box, and then choose the Next button.
5. In the What do you want to name your settings file? and Store my settings file in this director y
boxes, either leave the default values or specify different values, and then choose the Finish button.
By default, your shortcuts are saved in a file in the %USERPROFILE%\Documents\Visual Studio
2013\Settings folder. The name of the file reflects the date when you exported the settings, and the
extension is .vssettings.
To import only keyboard shortcuts
1. On the menu bar, choose Tools , Impor t and Expor t Settings .
2. Choose the Impor t selected environment settings option button, and then choose the Next button.
3. Choose the No, just impor t new settings, over writing my current settings option button, and then
choose the Next button.
4. Under My Settings , choose the file that contains the shortcuts that you want to import, or choose the
Browse button to locate the correct file.
5. Choose the Next button.
6. Under Which settings do you want to impor t? , clear the All Settings check box, expand Options ,
and then expand Environment .
7. Select the Keyboard check box, and then choose the Finish button.

See Also
Accessibility Features of Visual Studio
Default Keyboard Shortcuts for Frequently Used
Commands in Visual Studio
10/16/2020 • 3 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version selector
at the top left. We recommend upgrading to Visual Studio 2019. Download it here

You can access frequently used commands in Visual Studio by choosing these default keyboard shortcuts. For a
complete list of commands that have default shortcuts, see Default Keyboard Shortcuts.

NOTE
You can look up the shortcut for any command by opening the Options dialog box, expanding the Environment node,
and then choosing Keyboard .

In this topic
Build
Edit
Project
Tools
Window
Debug
File
Refactor
View||

Build
C O M M A N DS K EY B O A RD SH O RTC UT S [ C O N T EXT S]

Build.BuildSolution Ctrl+Shift+B [Global]

Build.Cancel Ctrl+Break [Global]

Build.Compile Ctrl+F7 [Global]

Build.RunCodeAnalysisonSolution Alt+F11 [Global]

Debug
C O M M A N DS K EY B O A RD SH O RTC UT S [ C O N T EXT S]

Debug.BreakatFunction Ctrl+B [Global]

Debug.BreakAll Ctrl+Alt+Break [Global]

Debug.DeleteAllBreakpoints Ctrl+Shift+F9 [Global]

Debug.Exceptions Ctrl+Alt+E [Global]

Debug.QuickWatch Ctrl+Alt+Q [Global]

or Shift+F9 [Global]

Debug.Restart Ctrl+Shift+F5 [Global]

Debug.RunToCursor Ctrl+F10 [Global]

Debug.SetNextStatement Ctrl+Shift+F10 [Global]

Debug.Start F5 [Global]

Debug.StartWithoutDebugging Ctrl+F5 [Global]

Debug.StepInto F11 [Global]

Debug.StepOut Shift+F11 [Global]

Debug.StepOver F10 [Global]

Debug.StopDebugging Shift+F5 [Global]

Debug.ToggleBreakpoint F9 [Global]

Edit
C O M M A N DS K EY B O A RD SH O RTC UT S [ C O N T EXT S]

Edit.BreakLine Enter [Text Editor, Report Designer, Windows Forms Designer]

or Shift+Enter [Text Editor]

Edit.CollapsetoDefinitions Ctrl+M, Ctrl+O [Text Editor]

Edit.CommentSelection Ctrl+K, Ctrl+C [Text Editor]

Edit.CompleteWord Alt+Right Arrow [Text Editor, Workflow Designer]

or Ctrl+Spacebar [Text Editor, Workflow Designer]

or Ctrl+K, W [Workflow Designer]

or Ctrl+K, Ctrl+W [Workflow Designer]


C O M M A N DS K EY B O A RD SH O RTC UT S [ C O N T EXT S]

Edit.Copy Ctrl+C [Global]

or Ctrl+Insert [Global]

Edit.Cut Ctrl+X [Global]

or Shift+Delete [Global]

Edit.Delete Delete [Global, Team Explorer]

or Shift+Delete [Sequence Diagram, UML Activity Diagram,


Layer Diagram]

or Ctrl+Delete [Class Diagram]

Edit.Find Ctrl+F [Global]

Edit.FindAllReferences Shift+F12 [Global]

dit.FindinFiles Ctrl+Shift+F [Global]

Edit.FindNext F3 [Global]

Edit.FindNextSelected Ctrl+F3 [Global]

Edit.FormatDocument Ctrl+K, Ctrl+D [Text Editor]

Edit.FormatSelection Ctrl+K, Ctrl+F [Text Editor]

Edit.GoTo Ctrl+G [Global]

Edit.GoToDeclaration Ctrl+F12 [Global]

Edit.GoToDefinition F12

Edit.GoToFindCombo Ctrl+D [Global]

Edit.GoToNextLocation F8 [Global]

Edit.InsertSnippet Ctrl+K, Ctrl+X [Global]

Edit.InsertTab Tab [Report Designer, Windows Forms Designer, Text Editor]

Edit.LineCut Ctrl+L [Text Editor]

Edit.LineDownExtendColumn Shift+Alt+Down Arrow [Text Editor]

Edit.LineOpenAbove Ctrl+Enter [Text Editor]


C O M M A N DS K EY B O A RD SH O RTC UT S [ C O N T EXT S]

Edit.ListMembers Ctrl+J [Text Editor, Workflow Designer]

or Ctrl+K, Ctrl+L [Workflow Designer]

or Ctrl+K, L [Workflow Designer]

dit.NavigateTo Ctrl+, [Global]

Edit.OpenFile Ctrl+Shift+G [Global]

Edit.OvertypeMode Insert [Text Editor]

Edit.ParameterInfo Ctrl+Shift+Spacebar [Text Editor, Workflow Designer]

or Ctrl+K, Ctrl+P [Workflow Designer]

or Ctrl+K, P [Workflow Designer]

Edit.Paste Ctrl+V [Global]

or Shift+Insert [Global]

Edit.PeekDefinition Alt+F12 [Text Editor]

Edit.Redo Ctrl+Y [Global]

or Shift+Alt+Backspace [Global]

or Ctrl+Shift+Z [Global]

Edit.Replace Ctrl+H [Global]

Edit.SelectAll Ctrl+A [Global]

Edit.SelectCurrentWord Ctrl+W [Text Editor]

Edit.SelectionCancel Esc [Text Editor, Report Designer, Settings Designer, Windows


Forms Designer, Managed Resources Editor]

dit.SurroundWith Ctrl+K, Ctrl+S [Global]

Edit.TabLeft Shift+Tab [Text Editor, Report Designer, Windows Forms Editor]

Edit.ToggleAllOutlining Ctrl+M, Ctrl+L [Text Editor]

Edit.ToggleBookmark Ctrl+K, Ctrl+K [Text Editor]

Edit.ToggleCompletionMode Ctrl+Alt+Space [Text Editor]

Edit.ToggleOutliningExpansion Ctrl+M, Ctrl+M [Text Editor]

Edit.UncommentSelection Ctrl+K, Ctrl+U [Text Editor]


C O M M A N DS K EY B O A RD SH O RTC UT S [ C O N T EXT S]

Edit.Undo Ctrl+Z [Global]

or Alt+Backspace [Global]

Edit.WordDeleteToEnd Ctrl+Delete [Text Editor]

Edit.WordDeleteToStart Ctrl+Backspace [Text Editor]

File
C O M M A N DS K EY B O A RD SH O RTC UT S [ C O N T EXT S]

File.Exit Alt+F4 [Global]

File.NewFile Ctrl+N [Global]

File.NewProject Ctrl+Shift+N [Global]

File.NewWebSite Shift+Alt+N [Global]

File.OpenFile Ctrl+O [Global]

File.OpenProject Ctrl+Shift+O [Global]

File.OpenWebSite Shift+Alt+O [Global]

File.Rename F2 [Team Explorer]

File.SaveAll Ctrl+Shift+S [Global]

File.SaveSelectedItems Ctrl+S [Global]

File.ViewinBrowser Ctrl+Shift+W [Global]

Project
C O M M A N DS K EY B O A RD SH O RTC UT S [ C O N T EXT S]

Project.AddExistingItem Shift+Alt+A [Global]

Project.AddNewItem Ctrl+Shift+A [Global]

Refactor
C OMMAND K EY B O A RD SH O RTC UT [ C O N T EXT ]

Refactor.ExtractMethod Ctrl+R, Ctrl+M [Global]


Tools
C OMMAND K EY B O A RD SH O RTC UT [ C O N T EXT ]

Tools.AttachtoProcess Ctrl+Alt+P [Global]

View
C O M M A N DS K EY B O A RD SH O RTC UT S [ C O N T EXT S]

View.ClassView Ctrl+Shift+C [Global]

View.EditLabel F2 [Global]

View.ErrorList Ctrl+\, Ctrl+E [Global]

or Ctrl+\, E [Global]

View.NavigateBackward Ctrl+- [Global]

View.NavigateForward Ctrl+Shift+- [Global]

View.ObjectBrowser Ctrl+Alt+J [Global]

View.Output Ctrl+Alt+O [Global]

View.PropertiesWindow F4

View.Refresh F5 [Team Explorer, Team Foundation Build Detail Editor]

View.ServerExplorer Ctrl+Alt+S [Global]

View.ShowSmartTag Ctrl+. [Global]

or Shift+Alt+F10 [Global, HTML Editor Design View]

View.SolutionExplorer Ctrl+Alt+L [Global]

iew.TfsTeamExplorer Ctrl+\, Ctrl+M [Global]

View.Toolbox Ctrl+Alt+X [Global]

View.ViewCode Enter [Class Diagram]

or F7 [Settings Designer]

View.ViewDesigner Shift+F7 [HTML Editor Source View]

Window
C O M M A N DS K EY B O A RD SH O RTC UT S [ C O N T EXT S]

Window.ActivateDocumentWindow Esc [Global]

Window.CloseDocumentWindow Ctrl+F4 [Global]

Window.NextDocumentWindow Ctrl+F6 [Global]

Window.NextDocumentWindowNav Ctrl+Tab [Global]

Window.NextSplitPane F6 [Global]
Default Keyboard Shortcuts in Visual Studio
10/16/2020 • 13 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version
selector at the top left. We recommend upgrading to Visual Studio 2019. Download it here

You can more easily access a variety of commands and windows in Visual Studio by choosing the appropriate
keyboard shortcut. This topics lists the default shortcuts for the General Development profile, which you might
have chosen when you installed Visual Studio. No matter which profile you chose, you can identify the shortcut
for a command by opening the Options dialog box, expanding the Environment node, and then choosing
Keyboard . You can also customize your shortcuts by assigning a different shortcut to any given command.
For a list of common keyboard shortcuts and other productivity information, see Tips and Tricks and Productivity
Tips.
The sections in the following list include commands that are global in that you can access them from anywhere in
Visual Studio by using keyboard shortcuts:
Analyze
Edit
Project
Test|
Architecture
Editor Context Menus
Project and Solution Context Menus
Test Explorer
Build
File
Refactor
Tools
Class View Context Menus
Help
Solution Explorer
View
Debug
Load Test
Team
Window
Debugger Context Menus
Other Context Menus
Team Foundation Context Menus
Azure
Diagnostics Hub
Each section in the following list includes commands for which the keyboard shortcuts are specific to the context
for which the section is named.
ADO.NET Entity Data Model Designer
Layer Diagram
Settings Designer
VC Image Editor
Class Diagram
Managed Resources Editor
Solution Explorer
VC String Editor
Coded UI Test Editor
Merge Editor Window
Team Explorer
View Designer
DataSet Editor
Microsoft SQL Server Data Tools, Schema Compare
Team Foundation Build Detail Editor
Visual Studio
Difference Viewer
Microsoft SQL Server Data Tools, Table Designer
Test Explorer
Windows Forms Designer
DOM Explorer
Microsoft SQL Server Data Tools, T-SQL Editor
Text Editor
Work Item Editor
F# Interactive
Microsoft SQL Server Data Tools, T-SQL PDW Editor
UML Activity Diagram
Work Item Query View
Graph Document Editor
Page Inspector
UML Class Diagram
Work Item Results View
Graphics Diagnostics
Query Designer
UML Component Diagram
Workflow Designer
HTML Editor
Query Results
UML Use Case Diagram
XAML UI Designer
HTML Editor Design View
Report Designer
VC Accelerator Editor
XML (Text) Editor
HTML Editor Source View
Sequence Diagram
VC Dialog Editor
XML Schema Designer

Global
Analyze
C O M M A N DS K EY B O A RD SH O RTC UT S

Analyze.NavigateBackward Shift+Alt+3

Analyze.NavigateForward Shift+Alt+4

Architecture
C O M M A N DS K EY B O A RD SH O RTC UT S

Architecture.NewDiagram Ctrl+\, Ctrl+N

Build
C O M M A N DS K EY B O A RD SH O RTC UT S

Build.BuildSolution Ctrl+Shift+B

Build.Cancel Ctrl+Break

Build.Compile Ctrl+F7

Build.RunCodeAnalysisonSolution Alt+F11

Class View Context Menus


C O M M A N DS K EY B O A RD SH O RTC UT S

ClassViewContextMenus.ClassViewMultiselectProjectreferenc Alt+Enter
esItems.Properties

Debug
C O M M A N DS K EY B O A RD SH O RTC UT S

Debug.ApplyCodeChanges Alt+F10

Debug.Autos Ctrl+Alt+V, A

Debug.BreakAll Ctrl+Alt+Break

Debug.BreakatFunction Ctrl+B

Debug.Breakpoints Ctrl+Alt+B

Debug.CallStack Ctrl+Alt+C
C O M M A N DS K EY B O A RD SH O RTC UT S

Debug.DeleteAllBreakpoints Ctrl+Shift+F9

Debug.DiagnosticsHub.Launch Alt+F2

Debug.Disassembly Ctrl+Alt+D

Debug.DOMExplorer Ctrl+Alt+V, D

Debug.EnableBreakpoint Ctrl+F9

Debug.Exceptions Ctrl+Alt+E

Debug.GoToPreviousCallorIntelliTraceEvent Ctrl+Shift+F11

Debug.Graphics.StartDiagnostics Alt+F5

Debug.Immediate Ctrl+Alt+I

Debug.IntelliTraceCalls Ctrl+Alt+Y, T

Debug.IntelliTraceEvents Ctrl+Alt+Y, F

Debug.JavaScriptConsole Ctrl+Alt+V, C

Debug.Locals Ctrl+Alt+V, L

Debug.LocationToolbar.ProcessCombo Ctrl+5

Debug.LocationToolbar.StackFrameCombo Ctrl+7

Debug.LocationToolbar.ThreadCombo Ctrl+6

Debug.LocationToolbar.ToggleCurrentThreadFlaggedState Ctrl+8

Debug.LocationToolbar.ToggleFlaggedThreads Ctrl+9

Debug.Memory1 Ctrl+Alt+M, 1

Debug.Memory2 Ctrl+Alt+M, 2

Debug.Memory3 Ctrl+Alt+M, 3

Debug.Memory4 Ctrl+Alt+M, 4

Debug.Modules Ctrl+Alt+U

Debug.ParallelStacks Ctrl+Shift+D, S

Debug.ParallelWatch1 Ctrl+Shift+D, 1
C O M M A N DS K EY B O A RD SH O RTC UT S

Debug.ParallelWatch2 Ctrl+Shift+D, 2

Debug.ParallelWatch3 Ctrl+Shift+D, 3

Debug.ParallelWatch4 Ctrl+Shift+D, 4

Debug.Processes Ctrl+Alt+Z

Debug.QuickWatch Shift+F9

or

Ctrl+Alt+Q

Debug.RefreshWindowsapp Ctrl+Shift+R

Debug.Registers Ctrl+Alt+G

Debug.Restart Ctrl+Shift+F5

Debug.RunToCursor Ctrl+F10

Debug.SetNextStatement Ctrl+Shift+F10

Debug.ShowCallStackonCodeMap Ctrl+Shift+`

Debug.ShowNextStatement Alt+Num *

Debug.Start F5

Debug.StartWindowsPhoneApplicationAnalysis Alt+F1

Debug.StartWithoutDebugging Ctrl+F5

Debug.StepInto F11

Debug.StepIntoCurrentProcess Ctrl+Alt+F11

Debug.StepIntoSpecific Shift+Alt+F11

Debug.StepOut Shift+F11

Debug.StepOutCurrentProcess Ctrl+Shift+Alt+F11

Debug.StepOver F10

Debug.StepOverCurrentProcess Ctrl+Alt+F10

Debug.StopDebugging Shift+F5

Debug.StopPerformanceAnalysis Shift+Alt+F2
C O M M A N DS K EY B O A RD SH O RTC UT S

Debug.Tasks Ctrl+Shift+D, K

Debug.Threads Ctrl+Alt+H

Debug.ToggleBreakpoint F9

Debug.ToggleDisassembly Ctrl+F11

Debug.Watch1 Ctrl+Alt+W, 1

Debug.Watch2 Ctrl+Alt+W, 2

Debug.Watch3 Ctrl+Alt+W, 3

Debug.Watch4 Ctrl+Alt+W, 4

Debugger Context Menus


C O M M A N DS K EY B O A RD SH O RTC UT S

DebuggerContextMenus.BreakpointsWindow.Delete Alt+F9, D

DebuggerContextMenus.BreakpointsWindow.GoToDisassemb Alt+F9, A
ly

DebuggerContextMenus.BreakpointsWindow.GoToSourceCod Alt+F9, S
e

Diagnostics Hub
C OMMAND K EY B O A RD SH O RTC UT

DiagnosticsHub.StopCollection Ctrl+Alt+F2

Edit
C O M M A N DS

Edit.Copy Ctrl+C

or

Ctrl+Ins

Edit.Cut Ctrl+X

or

Shift+Delete
C O M M A N DS

Edit.CycleClipboardRing Ctrl+Shift+V

or

Ctrl+Shift+Ins

Edit.Delete Delete

Edit.Find Ctrl+F

Edit.FindAllReferences Shift+F12

Edit.FindinFiles Ctrl+Shift+F

Edit.FindNext F3

Edit.FindNextSelected Ctrl+F3

Edit.FindPrevious Shift+F3

Edit.FindPreviousSelected Ctrl+Shift+F3

Edit.GenerateMethod Ctrl+K, Ctrl+M

Edit.GoTo Ctrl+G

Edit.GoToDeclaration Ctrl+F12

Edit.GoToDefinition F12

Edit.GoToFindCombo Ctrl+D

Edit.GoToNextLocation F8

Edit.GoToPrevLocation Shift+F8

Edit.InsertSnippet Ctrl+K, Ctrl+X

Edit.MoveControlDown Ctrl+Down Arrow

Edit.MoveControlDownGrid Down Arrow

Edit.MoveControlLeft Ctrl+Left Arrow

Edit.MoveControlLeftGrid Left Arrow

Edit.MoveControlRight Ctrl+Right Arrow

Edit.MoveControlRightGrid Right Arrow

Edit.MoveControlUp Ctrl+Up Arrow


C O M M A N DS

Edit.MoveControlUpGrid Up Arrow

Edit.NavigateTo Ctrl+,

Edit.NextBookmark Ctrl+K, Ctrl+N

Edit.NextBookmarkInFolder Ctrl+Shift+K, Ctrl+Shift+N

Edit.OpenFile Ctrl+Shift+G

Edit.Paste Ctrl+V

or

Shift+Ins

Edit.PreviousBookmark Ctrl+K, Ctrl+P

Edit.PreviousBookmarkInFolder Ctrl+Shift+K, Ctrl+Shift+P

Edit.QuickFindSymbol Shift+Alt+F12

Edit.Redo Ctrl+Y

or

Ctrl+Shift+Z

or

Shift+Alt+Backspace

Edit.RefreshRemoteReferences Ctrl+Shift+J

Edit.Replace Ctrl+H

Edit.ReplaceinFiles Ctrl+Shift+H

Edit.SelectAll Ctrl+A

Edit.SelectNextControl Tab

Edit.SelectPreviousControl Shift+Tab

Edit.ShowTileGrid Enter

Edit.SizeControlDown Ctrl+Shift+Down Arrow

Edit.SizeControlDownGrid Shift+Down Arrow

Edit.SizeControlLeft Ctrl+Shift+Left Arrow


C O M M A N DS

Edit.SizeControlLeftGrid Shift+Left Arrow

Edit.SizeControlRight Ctrl+Shift+Right Arrow

Edit.SizeControlRightGrid Shift+Right Arrow

Edit.SizeControlUp Ctrl+Shift+Up Arrow

Edit.SizeControlUpGrid Shift+Up Arrow

Edit.StopSearch Alt+F3, S

Edit.SurroundWith Ctrl+K, Ctrl+S

Edit.Undo Ctrl+Z

or

Alt+Backspace

Editor Context Menus


C O M M A N DS K EY B O A RD SH O RTC UT S

EditorContextMenus.CodeWindow.Breakpoint.BreakpointEditl Alt+F9, L
abels

EditorContextMenus.CodeWindow.CodeMap.ShowItem Ctrl+`

EditorContextMenus.CodeWindow.Execute Ctrl+Alt+F5

EditorContextMenus.CodeWindow.GoToView Ctrl+M, Ctrl+G

EditorContextMenus.CodeWindow.ToggleHeaderCodeFile Ctrl+K, Ctrl+O

EditorContextMenus.CodeWindow.ViewCallHierarchy Ctrl+K, Ctrl+T

or

Ctrl+K, T

File
C O M M A N DS K EY B O A RD SH O RTC UT S

File.Exit Alt+F4

File.NewFile Ctrl+N

File.NewProject Ctrl+Shift+N

File.NewWebSite Shift+Alt+N
C O M M A N DS K EY B O A RD SH O RTC UT S

File.OpenFile Ctrl+O

File.OpenProject Ctrl+Shift+O

File.OpenWebSite Shift+Alt+O

File.Print Ctrl+P

File.SaveAll Ctrl+Shift+S

File.SaveSelectedItems Ctrl+S

File.ViewinBrowser Ctrl+Shift+W

Help
C O M M A N DS K EY B O A RD SH O RTC UT S

Help.AddandRemoveHelpContent Ctrl+Alt+F1

Help.F1Help F1

Help.ViewHelp Ctrl+F1

Help.WindowHelp Shift+F1

Load Test
C OMMAND K EY B O A RD SH O RTC UT

LoadTest.JumpToCounterPane Ctrl+R, Q

Other Context Menus


C OMMAND K EY B O A RD SH O RTC UT

OtherContextMenus.MicrosoftDataEntityDesignContext.Add Insert
NewDiagram

Project
C O M M A N DS K EY B O A RD SH O RTC UT S

Project.AddExistingItem Shift+Alt+A

Project.AddNewItem Ctrl+Shift+A

Project.ClassWizard Ctrl+Shift+X

Project.Override Ctrl+Alt+Ins
C O M M A N DS K EY B O A RD SH O RTC UT S

Project.Previewchanges Alt+;, Alt+C

Project.Publishselectedfiles Alt+;, Alt+P

Project.Replaceselectedfilesfromserver Alt+;, Alt+R

Project and Solution Context Menus


C O M M A N DS K EY B O A RD SH O RTC UT S

ProjectandSolutionContextMenus.Item.MoveDown Alt+Down Arrow

ProjectandSolutionContextMenus.Item.MoveUp Alt+Up Arrow

Refactor
C O M M A N DS K EY B O A RD SH O RTC UT S

Refactor.EncapsulateField Ctrl+R, Ctrl+E

Refactor.ExtractInterface Ctrl+R, Ctrl+I

Refactor.ExtractMethod Ctrl+R, Ctrl+M

Refactor.RemoveParameters Ctrl+R, Ctrl+V

Refactor.Rename Ctrl+R, Ctrl+R

Refactor.ReorderParameters Ctrl+R, Ctrl+O

Solution Explorer
C O M M A N DS K EY B O A RD SH O RTC UT S

SolutionExplorer.OpenFilesFilter Ctrl+[, O

or

Ctrl+[, Ctrl+O

SolutionExplorer.PendingChangesFilter Ctrl+[, P

or

Ctrl+[, Ctrl+P

SolutionExplorer.SyncWithActiveDocument Ctrl+[, S

or

Ctrl+[, Ctrl+S

Team
C O M M A N DS K EY B O A RD SH O RTC UT S

Team.Git.GoToGitBranches Ctrl+0, Ctrl+N

or

Ctrl+0, N

Team.Git.GoToGitChanges Ctrl+0, Ctrl+G

or

Ctrl+0, G

Team.Git.GoToGitCommits Ctrl+0, Ctrl+O

or

Ctrl+0, O

Team.TeamExplorerSearch Ctrl+'

Team Foundation Context Menus


C O M M A N DS K EY B O A RD SH O RTC UT S

TeamFoundationContextMenus.Commands.GoToBuilds Ctrl+0, Ctrl+B

or

Ctrl+0, B

TeamFoundationContextMenus.Commands.GoToConnect Ctrl+0, Ctrl+C

or

Ctrl+0, C

TeamFoundationContextMenus.Commands.GoToDocuments Ctrl+0, Ctrl+D

or

Ctrl+0, D

TeamFoundationContextMenus.Commands.GoToHome Ctrl+0, Ctrl+H

or

Ctrl+0, H

TeamFoundationContextMenus.Commands.GoToMyWork Ctrl+0, Ctrl+M

or

Ctrl+0, M
C O M M A N DS K EY B O A RD SH O RTC UT S

TeamFoundationContextMenus.Commands.GoToPendingCha Ctrl+0, Ctrl+P


nges
or

Ctrl+0, P

TeamFoundationContextMenus.Commands.GoToReports Ctrl+0, Ctrl+R

or

Ctrl+0, R

TeamFoundationContextMenus.Commands.GoToSettings Ctrl+0, Ctrl+S

or

Ctrl+0, S

TeamFoundationContextMenus.Commands.GoToWebAccess Ctrl+0, Ctrl+A

or

Ctrl+0, A

TeamFoundationContextMenus.Commands.GoToWorkItems Ctrl+0, Ctrl+W

or

Ctrl+0, W

Test
C O M M A N DS K EY B O A RD SH O RTC UT S

Test.UseCodedUITestBuilder Ctrl+\, Ctrl+C

Test.UseExistingActionRecording Ctrl+\, Ctrl+A

Test Explorer
C O M M A N DS K EY B O A RD SH O RTC UT S

TestExplorer.DebugAllTests Ctrl+R, Ctrl+A

TestExplorer.DebugAllTestsInContext Ctrl+R, Ctrl+T

TestExplorer.RepeatLastRun Ctrl+R, L

TestExplorer.RunAllTests Ctrl+R, A

TestExplorer.RunAllTestsInContext Ctrl+R, T

Tools
C O M M A N DS K EY B O A RD SH O RTC UT S

Tools.AttachtoProcess Ctrl+Alt+P

Tools.CodeSnippetsManager Ctrl+K, Ctrl+B

Tools.ForceGC Ctrl+Shift+Alt+F12, Ctrl+Shift+Alt+F12

Tools.GoToCommandLine Ctrl+/

View
C O M M A N DS K EY B O A RD SH O RTC UT S

View.AllWindows Shift+Alt+M

View.ArchitectureExplorer Ctrl+\, Ctrl+R

View.Backward Alt+Left Arrow

View.BookmarkWindow Ctrl+K, Ctrl+W

View.BrowseNext Ctrl+Shift+1

View.BrowsePrevious Ctrl+Shift+2

View.CallHierarchy Ctrl+Alt+K

View.ClassView Ctrl+Shift+C

View.ClassViewGoToSearchCombo Ctrl+K, Ctrl+V

View.CodeDefinitionWindow Ctrl+\, D

or

Ctrl+\, Ctrl+D

View.CommandWindow Ctrl+Alt+A

View.DataSources Shift+Alt+D

View.DocumentOutline Ctrl+Alt+T

View.EditLabel F2

View.ErrorList Ctrl+\, E

or

Ctrl+\, Ctrl+E

View.F#Interactive Ctrl+Alt+F
C O M M A N DS K EY B O A RD SH O RTC UT S

View.FindSymbolResults Ctrl+Alt+F12

View.Forward Alt+Right Arrow

View.ForwardBrowseContext Ctrl+Shift+7

View.FullScreen Shift+Alt+Enter

View.NavigateBackward Ctrl+-

View.NavigateForward Ctrl+Shift+-

View.NextError Ctrl+Shift+F12

View.Notifications Ctrl+W, N

or

Ctrl+W, Ctrl+N

View.ObjectBrowser Ctrl+Alt+J

View.ObjectBrowserGoToSearchCombo Ctrl+K, Ctrl+R

View.Output Ctrl+Alt+O

View.PopBrowseContex Ctrl+Shift+8

View.PropertiesWindow F4

View.PropertyPages Shift+F4

View.ResourceView Ctrl+Shift+E

View.ServerExplorer Ctrl+Alt+S

View.ShowSmartTag Shift+Alt+F10

or

Ctrl+.

View.SolutionExplorer Ctrl+Alt+L

View.SQLServerObjectExplorer Ctrl+\, Ctrl+S

View.TaskList Ctrl+\, T

or

Ctrl+\, Ctrl+T
C O M M A N DS K EY B O A RD SH O RTC UT S

View.TfsTeamExplorer Ctrl+\, Ctrl+M

View.Toolbox Ctrl+Alt+X

View.UMLModelExplorer Ctrl+\, Ctrl+U

View.ViewCode F7

View.ViewDesigner Shift+F7

View.WebBrowser Ctrl+Alt+R

View.ZoomIn Ctrl+Shift+.

View.ZoomOut Ctrl+Shift+,

Window
C O M M A N DS K EY B O A RD SH O RTC UT S

Window.ActivateDocumentWindow Esc

Window.AddTabtoSelection Ctrl+Shift+Alt+Space

Window.CloseDocumentWindow Ctrl+F4

Window.CloseToolWindow Shift+Esc

Window.KeepTabOpen Ctrl+Alt+Home

Window.MovetoNavigationBar Ctrl+F2

Window.NextDocumentWindow Ctrl+F6

Window.NextDocumentWindowNav Ctrl+Tab

Window.NextPane Alt+F6

Window.NextSplitPane F6

Window.NextTab Ctrl+Alt+PgDn

or

Ctrl+PgDn

Window.NextTabandAddtoSelection Ctrl+Shift+Alt+PgDn

Window.NextToolWindowNav Alt+F7

Window.PreviousDocumentWindow Ctrl+Shift+F6
C O M M A N DS K EY B O A RD SH O RTC UT S

Window.PreviousDocumentWindowNav Ctrl+Shift+Tab

Window.PreviousPane Shift+Alt+F6

Window.PreviousSplitPane Shift+F6

Window.PreviousTab Ctrl+Alt+PgUp

or

Ctrl+PgUp

Window.PreviousTabandAddtoSelection Ctrl+Shift+Alt+PgUp

Window.PreviousToolWindowNav Shift+Alt+F7

Window.QuickLaunch Ctrl+Q

Window.QuickLaunchPreviousCategory Ctrl+Shift+Q

Window.ShowDockMenu Alt+-

Window.ShowEzMDIFileList Ctrl+Alt+Down Arrow

Window.SolutionExplorerSearch Ctrl+;

Window.WindowSearch Alt+`

Azure
C O M M A N DS K EY B O A RD SH O RTC UT S

WindowsAzure.RetryMobileServiceScriptOperation Ctrl+Num *, Ctrl+R

WindowsAzure.ShowMobileServiceScriptErrorDetails Ctrl+Num *, Ctrl+D

ADO.NET Entity Data Model Designer


C O M M A N DS K EY B O A RD SH O RTC UT S

OtherContextMenus.MicrosoftDataEntityDesignContext.Mov Alt+Down Arrow


eProperties.Down

OtherContextMenus.MicrosoftDataEntityDesignContext.Mov Alt+PgDn
eProperties.Down5

OtherContextMenus.MicrosoftDataEntityDesignContext.Mov Alt+End
eProperties.ToBottom

OtherContextMenus.MicrosoftDataEntityDesignContext.Mov Alt+Home
eProperties.ToTop
C O M M A N DS K EY B O A RD SH O RTC UT S

OtherContextMenus.MicrosoftDataEntityDesignContext.Mov Alt+Up Arrow


eProperties.Up

OtherContextMenus.MicrosoftDataEntityDesignContext.Mov Alt+PgUp
eProperties.Up5

OtherContextMenus.MicrosoftDataEntityDesignContext.Refac Ctrl+R, R
tor.Rename

OtherContextMenus.MicrosoftDataEntityDesignContext.Rem Shift+Del
ovefromDiagram

View.EntityDataModelBrowser Ctrl+1

View.EntityDataModelMappingDetails Ctrl+2

Class Diagram
C O M M A N DS K EY B O A RD SH O RTC UT S

ClassDiagram.Collapse Num -

ClassDiagram.Expand Num +

Edit.Delete Ctrl+Del

Edit.ExpandCollapseBaseTypeList Shift+Alt+B

Edit.NavigateToLollipop Shift+Alt+L

Edit.RemovefromDiagram Delete

View.ViewCode Enter

Coded UI Test Editor


C O M M A N DS K EY B O A RD SH O RTC UT S

OtherContextMenus.UITestEditorContextMenu.CopyReferenc Ctrl+C
etoClipboard

OtherContextMenus.UITestEditorContextMenu.InsertDelayBe Ctrl+Alt+D
fore

OtherContextMenus.UITestEditorContextMenu.LocateAll Shift+Alt+L

OtherContextMenus.UITestEditorContextMenu.LocatetheUIC Ctrl+Shift+L
ontrol

OtherContextMenus.UITestEditorContextMenu.Movecode Ctrl+Alt+C
C O M M A N DS K EY B O A RD SH O RTC UT S

OtherContextMenus.UITestEditorContextMenu.Splitintoanew Ctrl+Shift+T
method

DataSet Editor
C O M M A N DS K EY B O A RD SH O RTC UT S

OtherContextMenus.ColumnContext.InsertColumn Insert

OtherContextMenus.DbTableContext.Add.Column Ctrl+L

Difference Viewer
C O M M A N DS K EY B O A RD SH O RTC UT S

Diff.IgnoreTrimWhitespace Ctrl+\, Ctrl+Spacebar

Diff.InlineView Ctrl+\, Ctrl+1

Diff.LeftOnlyView Ctrl+\, Ctrl+3

Diff.NextDifference F8

Diff.PreviousDifference Shift+F8

Diff.RightOnlyView Ctrl+\, Ctrl+4

Diff.SideBySideView Ctrl+\, Ctrl+2

Diff.SwitchBetweenLeftAndRight Ctrl+\, Ctrl+Tab

Diff.SynchronizeViewToggle Ctrl+\, Ctrl+Down Arrow

EditorContextMenus.CodeWindow.AddComment Ctrl+Shift+K

EditorContextMenus.CodeWindow.EditLocalFile Ctrl+Shift+P

DOM Explorer
C O M M A N DS K EY B O A RD SH O RTC UT S

DOMExplorer.Refresh F5

DOMExplorer.SelectElement Ctrl+B

DOMExplorer.ShowLayout Ctrl+Shift+I

F# Interactive
C OMMAND K EY B O A RD SH O RTC UT

OtherContextMenus.FSIConsoleContext.CancelInteractiveEval Ctrl+Break
uation

Graph Document Editor


C O M M A N DS K EY B O A RD SH O RTC UT S

ArchitectureContextMenus.DirectedGraphContextMenu.Adva Insert
nced.Add.AddNode

ArchitectureContextMenus.DirectedGraphContextMenu.Adva B
nced.Select.BothDependencies

ArchitectureContextMenus.DirectedGraphContextMenu.Adva I
nced.Select.IncomingDependencies

ArchitectureContextMenus.DirectedGraphContextMenu.Adva O
nced.Select.OutgoingDependencies

ArchitectureContextMenus.DirectedGraphContextMenu.New Ctrl+Shift+K
Comment
or

Ctrl+E, C

ArchitectureContextMenus.DirectedGraphContextMenu.Rem Delete
ove

ArchitectureContextMenus.DirectedGraphContextMenu.Rena F2
me

Graphics Diagnostics
C O M M A N DS K EY B O A RD SH O RTC UT S

Debug.Graphics.CaptureFrame None

Graphics.MovePixelSelectionDown Shift+Alt+Down Arrow

Graphics.MovePixelSelectionLeft Shift+Alt+Left Arrow

Graphics.MovePixelSelectionRight Shift+Alt+Right Arrow

Graphics.MovePixelSelectionUp Shift+Alt+Up Arrow

Graphics.ZoomToActualSize Shift+Alt+0

Graphics.ZoomToFitInWindow Shift+Alt+9

Graphics.ZoomIn Shift+Alt+=
C O M M A N DS K EY B O A RD SH O RTC UT S

Graphics.ZoomOut Shift+Alt+-

HTML Editor
C OMMAND K EY B O A RD SH O RTC UT

OtherContextMenus.HTMLContext.GoToController Ctrl+M, Ctrl+G

HTML Editor Design View


C O M M A N DS K EY B O A RD SH O RTC UT S

Edit.MoveControlDown Ctrl+Down Arrow

Edit.MoveControlUp Ctrl+Up Arrow

Format.Bold Ctrl+B

Format.ConverttoHyperlink Ctrl+L

Format.InsertBookmark Ctrl+Shift+L

Format.Italic Ctrl+I

Format.Underline Ctrl+U

Project.AddContentPage Ctrl+M, Ctrl+C

Table.ColumntotheLeft Ctrl+Alt+Left Arrow

Table.ColumntotheRight Ctrl+Alt+Right Arrow

Table.RowAbove Ctrl+Alt+Up Arrow

Table.RowBelow Ctrl+Alt+Down Arrow

View.ASP.NETNonvisualControls Ctrl+Shift+N

View.EditMaster Ctrl+M, Ctrl+M

View.NextView Ctrl+PgDn

View.ShowSmartTag Shift+Alt+F10

View.ViewMarkup Shift+F7

Window.PreviousTab Ctrl+PgUp
HTML Editor Source View
C O M M A N DS K EY B O A RD SH O RTC UT S

OtherContextMenus.HTMLContext.GoToController Ctrl+M, Ctrl+G

View.NextView Ctrl+PgDn

View.SynchronizeViews Ctrl+Shift+Y

View.ViewDesigner Shift+F7

Window.PreviousTab Ctrl+PgUp

Layer Diagram
C OMMAND K EY B O A RD SH O RTC UT

Edit.Delete Shift+Delete

Managed Resources Editor


C O M M A N DS K EY B O A RD SH O RTC UT S

Edit.EditCell F2

Edit.Remove Delete

Edit.RemoveRow Ctrl+Delete

Edit.SelectionCancel Escape

Resources.Audio Ctrl+4

Resources.Files Ctrl+5

Resources.Icons Ctrl+3

Resources.Images Ctrl+2

Resources.Other Ctrl+6

Resources.Strings Ctrl+1

Merge Editor Window


C O M M A N DS K EY B O A RD SH O RTC UT S

TeamFoundationContextMenus.MergeContextMenu.SetFocus Alt+1
onLeftWindow
C O M M A N DS K EY B O A RD SH O RTC UT S

TeamFoundationContextMenus.MergeContextMenu.SetFocus Alt+2
onResultWindow

TeamFoundationContextMenus.MergeContextMenu.SetFocus Alt+3
onRightWindow

Microsoft SQL Server Data Tools, Schema Compare


C O M M A N DS K EY B O A RD SH O RTC UT S

SQL.SSDTSchemaCompareCompare Shift+Alt+C

SQL.SSDTSchemaCompareGenerateScript Shift+Alt+G

SQL.SSDTSchemaCompareNextChange Shift+Alt+.

SQL.SSDTSchemaComparePreviousChange Shift+Alt+,

SQL.SSDTSchemaCompareStop Alt+Break

SQL.SSDTSchemaCompareWriteUpdates Shift+Alt+U

Microsoft SQL Server Data Tools, Table Designer


C O M M A N DS K EY B O A RD SH O RTC UT S

CommitAllEdits Shift+Alt+U

SQL.ExpandWildcards Ctrl+R, E

or

Ctrl+R, Ctrl+E

SQL.FullyqualifyNames Ctrl+R, Q

or

Ctrl+R, Ctrl+Q

SQL.MovetoSchema Ctrl+R, M

or

Ctrl+R, Ctrl+M
C O M M A N DS K EY B O A RD SH O RTC UT S

SQL.Rename F2

or

Ctrl+R, R

or

Ctrl+R, Ctrl+R

ViewFileInScriptPanel Shift+Alt+PgDn

Microsoft SQL Server Data Tools, T-SQL Editor


C O M M A N DS K EY B O A RD SH O RTC UT S

CommitAllEdits Shift+Alt+U

SQL.ExecuteWithDebugger Alt+F5

SQL.ExpandWildcards Ctrl+R, E

or

Ctrl+R, Ctrl+E

SQL.FullyqualifyNames Ctrl+R, Q

or

Ctrl+R, Ctrl+Q

SQL.MovetoSchema Ctrl+R, M

or

Ctrl+R, Ctrl+M

SQL.Rename F2

or

Ctrl+R, R

or

Ctrl+R, Ctrl+R

SQL.TSqlEditorCancelQuery Alt+Break

SQL.TSqlEditorExecuteQuery Ctrl+Shift+E

SQL.TSqlEditorResultsAsFile Ctrl+D, F

SQL.TSqlEditorResultsAsGrid Ctrl+D, G
C O M M A N DS K EY B O A RD SH O RTC UT S

SQL.TSqlEditorResultsAsText Ctrl+D, T

SQL.TSqlEditorShowEstimatedPlan Ctrl+D, E

SQL.TSqlEditorToggleExecutionPlan Ctrl+D, A

SQL.TSqlEditorToggleResultsPane Ctrl+D, R

TSqlEditorCloneQuery Ctrl+Alt+N

TSqlEditorDatabaseCombo Shift+Alt+PgDn

Microsoft SQL Server Data Tools, T-SQL PDW Editor


C O M M A N DS K EY B O A RD SH O RTC UT S

SQL.TSqlEditorCancelQuery Alt+Break

SQL.TSqlEditorExecuteQuery Ctrl+Shift+E

SQL.TSqlEditorResultsAsFile Ctrl+D, F

SQL.TSqlEditorResultsAsGrid Ctrl+D, G

SQL.TSqlEditorResultsAsText Ctrl+D, T

SQL.TSqlEditorShowEstimatedPlan Ctrl+D, E

SQL.TSqlEditorToggleExecutionPlan Ctrl+D, A

SQL.TSqlEditorToggleResultsPane Ctrl+D, R

TSqlEditorCloneQuery Ctrl+Alt+N

TSqlEditorDatabaseCombo Shift+Alt+PgDn

Page Inspector
C OMMAND K EY B O A RD SH O RTC UT

PageInspector.Minimize F12

Query Designer
C O M M A N DS K EY B O A RD SH O RTC UT S

QueryDesigner.CancelRetrievingData Ctrl+T
C O M M A N DS K EY B O A RD SH O RTC UT S

QueryDesigner.Criteria Ctrl+2

QueryDesigner.Diagram Ctrl+1

QueryDesigner.ExecuteSQL Ctrl+R

QueryDesigner.GotoRow Ctrl+G

QueryDesigner.JoinMode Ctrl+Shift+J

QueryDesigner.Results Ctrl+4

QueryDesigner.SQL Ctrl+3

Query Results
C O M M A N DS K EY B O A RD SH O RTC UT S

SQL.QueryResultsNewRow Alt+End

SQL.QueryResultsRefresh Shift+Alt+R

SQL.QueryResultsStop Alt+Break

Report Designer
C O M M A N DS K EY B O A RD SH O RTC UT S

Edit.BreakLine Enter

Edit.CharLeft Left Arrow

Edit.CharLeftExtend Shift+Left Arrow

Edit.CharRight Right Arrow

Edit.CharRightExtend Shift+Right Arrow

Edit.InsertTab Tab

Edit.LineDown Down Arrow

Edit.LineDownExtend Shift+Down Arrow

Edit.LineUp Up Arrow

Edit.LineUpExtend Shift+Up Arrow

Edit.MoveControlDown Ctrl+Down Arrow


C O M M A N DS K EY B O A RD SH O RTC UT S

Edit.MoveControlLeft Ctrl+Left Arrow

Edit.MoveControlRight Ctrl+Right Arrow

Edit.MoveControlUp Ctrl+Up Arrow

Edit.SelectionCancel Esc

Edit.SizeControlDown Ctrl+Shift+Down Arrow

Edit.SizeControlLeft Ctrl+Shift+Left Arrow

Edit.SizeControlRight Ctrl+Shift+Right Arrow

Edit.SizeControlUp Ctrl+Shift+Up Arrow

Edit.TabLeft Shift+Tab

View.ReportData Ctrl+Alt+D

Sequence Diagram
C O M M A N DS K EY B O A RD SH O RTC UT S

ArchitectureDesigner.Sequence.NavigateToCode F12

Edit.Delete Shift+Del

Settings Designer
C O M M A N DS K EY B O A RD SH O RTC UT S

Edit.EditCell F2

Edit.RemoveRow Ctrl+Delete

Edit.SelectionCancel Esc

View.ViewCode F7

Solution Explorer
C OMMAND K EY B O A RD SH O RTC UT

ClassViewContextMenus.ClassViewProject.View.ViewinPageIn Ctrl+K, Ctrl+G


spector

Team Explorer
C OMMAND K EY B O A RD SH O RTC UT

Edit.Delete Delete

File.Rename F2

TeamFoundationContextMenus.Commands.GoToTeamExplore Alt+Home
rNavigation

TeamFoundationContextMenus.Commands.GoToTeamExplore Alt+Down Arrow


rNextSectionContent

TeamFoundationContextMenus.Commands.GoToTeamExplore Alt+0
rPageContent

TeamFoundationContextMenus.Commands.GoToTeamExplore Alt+Up Arrow


rPreviousSectionContent

TeamFoundationContextMenus.Commands.GoToTeamExplore Alt+1
rSection1Content

TeamFoundationContextMenus.Commands.GoToTeamExplore Alt+2
rSection2Content

TeamFoundationContextMenus.Commands.GoToTeamExplore Alt+3
rSection3Content

TeamFoundationContextMenus.Commands.GoToTeamExplore Alt+4
rSection4Content

TeamFoundationContextMenus.Commands.GoToTeamExplore Alt+5
rSection5Content

TeamFoundationContextMenus.Commands.GoToTeamExplore Alt+6
rSection6Content

TeamFoundationContextMenus.Commands.GoToTeamExplore Alt+7
rSection7Content

TeamFoundationContextMenus.Commands.GoToTeamExplore Alt+8
rSection8Content

TeamFoundationContextMenus.Commands.GoToTeamExplore Alt+9
rSection9Content

TeamFoundationContextMenus.Commands.TeamExplorerNavi Alt+Left Arrow


gateBackward

TeamFoundationContextMenus.Commands.TeamExplorerNavi Alt+Right Arrow


gateForward

TeamFoundationContextMenus.MyWorkPageInProgress.TfsC Shift+Alt+C
ontextMyWorkPageCreateCopyWI
C OMMAND K EY B O A RD SH O RTC UT

TeamFoundationContextMenus.MyWorkPageInProgress.TfsC Shift+Alt+L
ontextMyWorkPageNewLinkedWI

View.Refresh F5

Team Foundation Build Detail Editor


C OMMAND K EY B O A RD SH O RTC UT

View.Refresh F5

Test Explorer
C OMMAND K EY B O A RD SH O RTC UT

TestExplorer.OpenTest F12

Text Editor
C O M M A N DS K EY B O A RD SH O RTC UT S

Edit.BreakLine Enter

or

Shift+Enter

Edit.CharLeft Left Arrow

Edit.CharLeftExtend Shift+Left Arrow

Edit.CharLeftExtendColumn Shift+Alt+Left Arrow

Edit.CharRight Right Arrow

Edit.CharRightExtend Shift+Right Arrow

Edit.CharRightExtendColumn Shift+Alt+Right Arrow

Edit.CharTranspose Ctrl+T

Edit.ClearBookmarks Ctrl+K, Ctrl+L

Edit.CollapseAllOutlining Ctrl+M, Ctrl+A

Edit.CollapseCurrentRegion Ctrl+M, Ctrl+S

Edit.CollapseTag Ctrl+M, Ctrl+T


C O M M A N DS K EY B O A RD SH O RTC UT S

Edit.CollapsetoDefinitions Ctrl+M, Ctrl+O

Edit.CommentSelection Ctrl+K, Ctrl+C

Edit.CompleteWord Ctrl+Space

or

Alt+Right Arrow

Edit.CopyParameterTip Ctrl+Shift+Alt+C

Edit.DecreaseFilterLevel Alt+,

Edit.DeleteBackwards Backspace

or

Shift+Bkspce

Edit.DeleteHorizontalWhiteSpace Ctrl+K, Ctrl+\

Edit.DocumentEnd Ctrl+End

Edit.DocumentEndExtend Ctrl+Shift+End

Edit.DocumentStart Ctrl+Home

Edit.DocumentStartExtend Ctrl+Shift+Home

Edit.ExpandAllOutlining Ctrl+M, Ctrl+X

Edit.ExpandCurrentRegion Ctrl+M, Ctrl+E

Edit.FormatDocument Ctrl+K, Ctrl+D

Edit.FormatSelection Ctrl+K, Ctrl+F

Edit.GotoBrace Ctrl+]

Edit.GotoBraceExtend Ctrl+Shift+]

Edit.HideSelection Ctrl+M, Ctrl+H

Edit.IncreaseFilterLevel Alt+.

Edit.IncrementalSearch Ctrl+I

Edit.InsertTab Tab

Edit.LineCut Ctrl+L
C O M M A N DS K EY B O A RD SH O RTC UT S

Edit.LineDelete Ctrl+Shift+L

Edit.LineDown Down Arrow

Edit.LineDownExtend Shift+Down Arrow

Edit.LineDownExtendColumn Shift+Alt+Down Arrow

Edit.LineEnd End

Edit.LineEndExtend Shift+End

Edit.LineEndExtendColumn Shift+Alt+End

Edit.LineOpenAbove Ctrl+Enter

Edit.LineOpenBelow Ctrl+Shift+Enter

Edit.LineStart Home

Edit.LineStartExtend Shift+Home

Edit.LineStartExtendColumn Shift+Alt+Home

Edit.LineTranspose Shift+Alt+T

Edit.LineUp Up Arrow

Edit.LineUpExtend Shift+Up Arrow

Edit.LineUpExtendColumn Shift+Alt+Up Arrow

Edit.ListMembers Ctrl+J

Edit.MakeLowercase Ctrl+U

Edit.MakeUppercase Ctrl+Shift+U

Edit.MoveSelectedLinesDown Alt+Down Arrow

Edit.MoveSelectedLinesUp Alt+Up Arrow

Edit.NextHighlightedReference Ctrl+Shift+Down Arrow

Edit.OvertypeMode Insert

Edit.PageDown PgDn

Edit.PageDownExtend Shift+PgDn
C O M M A N DS K EY B O A RD SH O RTC UT S

Edit.PageUp PgUp

Edit.PageUpExtend Shift+PgUp

Edit.ParameterInfo Ctrl+Shift+Spacebar

Edit.PasteParameterTip Ctrl+Shift+Alt+P

Edit.PeekBackward Ctrl+Alt+-

Edit.PeekDefinition Alt+F12

Edit.PeekForward Ctrl+Alt+=

Edit.PreviousHighlightedReference Ctrl+Shift+Up Arrow

Edit.QuickInfo Ctrl+K, Ctrl+I

Edit.ReverseIncrementalSearch Ctrl+Shift+I

Edit.ScrollLineDown Ctrl+Down Arrow

Edit.ScrollLineUp Ctrl+Up Arrow

Edit.SelectCurrentWord Ctrl+W

Edit.SelectionCancel Escape

Edit.SelectToLastGoBack Ctrl+=

Edit.ShowCodeLensMenu Alt+`

Edit.StopHidingCurrent Ctrl+M, Ctrl+U

Edit.StopOutlining Ctrl+M, Ctrl+P

Edit.SwapAnchor Ctrl+K, Ctrl+A

Edit.TabLeft Shift+Tab

Edit.ToggleAllOutlining Ctrl+M, Ctrl+L

Edit.ToggleBookmark Ctrl+K, Ctrl+K

Edit.ToggleCompletionMode Ctrl+Alt+Space

Edit.ToggleOutliningExpansion Ctrl+M, Ctrl+M

Edit.ToggleTaskListShortcut Ctrl+K, Ctrl+H


C O M M A N DS K EY B O A RD SH O RTC UT S

Edit.ToggleWordWrap Ctrl+E, Ctrl+W

Edit.UncommentSelection Ctrl+K, Ctrl+U

Edit.ViewBottom Ctrl+PgDn

Edit.ViewBottomExtend Ctrl+Shift+PgDn

Edit.ViewTop Ctrl+PgUp

Edit.ViewTopExtend Ctrl+Shift+PgUp

Edit.ViewWhiteSpace Ctrl+R, Ctrl+W

Edit.WordDeleteToEnd Ctrl+Delete

Edit.WordDeleteToStart Ctrl+Backspace

Edit.WordNext Ctrl+Right Arrow

Edit.WordNextExtend Ctrl+Shift+Right Arrow

Edit.WordNextExtendColumn Ctrl+Shift+Alt+Right Arrow

Edit.WordPrevious Ctrl+Left Arrow

Edit.WordPreviousExtend Ctrl+Shift+Left Arrow

Edit.WordPreviousExtendColumn Ctrl+Shift+Alt+Left Arrow

Edit.WordTranspose Ctrl+Shift+T

EditorContextMenus.CodeWindow.ExecuteInInteractive Alt+Enter

EditorContextMenus.CodeWindow.ExecuteLineInInteractive Alt+'

OtherContextMenus.HTMLContext.ViewinPageInspector Ctrl+K, Ctrl+G

TeamFoundationContextMenus.Annotate.TfsAnnotateMoveN Alt+PgDn
extRegion

TeamFoundationContextMenus.Annotate.TfsAnnotateMovePr Alt+PgUp
eviousRegion

UML Activity Diagram


C OMMAND K EY B O A RD SH O RC T UT

Edit.Delete Shift+Del
UML Class Diagram
C OMMAND K EY B O A RD SH O RC T UT

Edit.DeleteFromModel Shift+Del

UML Component Diagram


C OMMAND K EY B O A RD SH O RC T UT

Edit.DeleteFromModel Shift+Del

UML Use Case Diagram


C OMMAND K EY B O A RD SH O RC T UT

Edit.DeleteFromModel Shift+Del

VC Accelerator Editor
C O M M A N DS K EY B O A RD SH O RC T UT S

Edit.NewAccelerator Insert

Edit.NextKeyTyped Ctrl+W

VC Dialog Editor
C O M M A N DS K EY B O A RD SH O RC T UT S

Edit.MoveControlDown Down Arrow

Edit.MoveControlLeft Left Arrow

Edit.MoveControlRight Right Arrow

Edit.MoveControlUp Up Arrow

Edit.ScrollColumnLeft Ctrl+Left Arrow

Edit.ScrollColumnRight Ctrl+Right Arrow

Edit.ScrollLineDown Ctrl+Down Arrow

Edit.ScrollLineUp Ctrl+Up Arrow

Edit.SizeControlDown Shift+Down Arrow

Edit.SizeControlLeft Shift+Left Arrow


C O M M A N DS K EY B O A RD SH O RC T UT S

Edit.SizeControlRight Shift+Right Arrow

Edit.SizeControlUp Shift+Up Arrow

Format.AlignBottoms Ctrl+Shift+Down Arrow

Format.AlignCenters Shift+F9

Format.AlignLefts Ctrl+Shift+Left Arrow

Format.AlignMiddles F9

Format.AlignRights Ctrl+Shift+Right Arrow

Format.AlignTops Ctrl+Shift+Up Arrow

Format.ButtonBottom Ctrl+B

Format.ButtonRight Ctrl+R

Format.CenterHorizontal Ctrl+Shift+F9

Format.CenterVertical Ctrl+F9

Format.CheckMnemonics Ctrl+M

Format.SizetoContent Shift+F7

Format.SpaceAcross Alt+Right Arrow

or

Alt+Left Arrow

Format.SpaceDown Alt+Up Arrow

or

Alt+Down Arrow

Format.TabOrder Ctrl+D

Format.TestDialog Ctrl+T

Format.ToggleGuides Ctrl+G

VC Image Editor
C O M M A N DS K EY B O A RD SH O RTC UT S

Image.AirbrushTool Ctrl+A
C O M M A N DS K EY B O A RD SH O RTC UT S

Image.BrushTool Ctrl+B

Image.CopyandOutlineSelection Ctrl+Shift+U

Image.DrawOpaque Ctrl+J

Image.EllipseTool Alt+P

Image.EraseTool Ctrl+Shift+I

Image.FilledEllipseTool Ctrl+Shift+Alt+P

Image.FilledRectangleTool Ctrl+Shift+Alt+R

Image.FilledRoundedRectangleTool Ctrl+Shift+Alt+W

Image.FillTool Ctrl+F

Image.FlipHorizontal Ctrl+H

Image.FlipVertical Shift+Alt+H

Image.LargerBrush Ctrl+=

Image.LineTool Ctrl+L

Image.MagnificationTool Ctrl+M

Image.Magnify Ctrl+Shift+M

Image.NewImageType Insert

Image.NextColor Ctrl+]

or

Ctrl+Right Arrow

Image.NextRightColor Ctrl+Shift+]

or

Ctrl+Shift+Right Arrow

Image.OutlinedEllipseTool Shift+Alt+P

Image.OutlinedRectangleTool Shift+Alt+R

Image.OutlinedRoundedRectangleTool Shift+Alt+W

Image.PencilTool Ctrl+I
C O M M A N DS K EY B O A RD SH O RTC UT S

Image.PreviousColor Ctrl+[

or

Ctrl+Left Arrow

Image.PreviousRightColor Ctrl+Shift+[

or

Ctrl+Shift+Left Arrow

Image.RectangleSelectionTool Shift+Alt+S

Image.RectangleTool Alt+R

Image.Rotate90Degrees Ctrl+Shift+H

Image.RoundedRectangleTool Alt+W

Image.ShowGrid Ctrl+Alt+S

Image.ShowTileGrid Ctrl+Shift+Alt+S

Image.SmallBrush Ctrl+.

Image.SmallerBrush Ctrl+-

Image.TextTool Ctrl+T

Image.UseSelectionasBrush Ctrl+U

Image.ZoomIn Ctrl+Shift+.

or

Ctrl+Up Arrow

Image.ZoomOut Ctrl+Shift+,

or

Ctrl+Down Arrow

VC String Editor
C OMMAND K EY B O A RD SH O RTC UT

Edit.NewString Insert

View Designer
C O M M A N DS K EY B O A RD SH O RTC UT S

QueryDesigner.CancelRetrievingData Ctrl+T

QueryDesigner.Criteria Ctrl+2

QueryDesigner.Diagram Ctrl+1

QueryDesigner.ExecuteSQL Ctrl+R

QueryDesigner.GotoRow Ctrl+G

QueryDesigner.JoinMode Ctrl+Shift+J

QueryDesigner.Results Ctrl+4

QueryDesigner.SQL Ctrl+3

Visual Studio
C OMMAND K EY B O A RD SH O RTC UT

OtherContextMenus.ORDesignerContext.HideMethodsPane Ctrl+1

Windows Forms Designer


C O M M A N DS K EY B O A RD SH O RTC UT S

Edit.BreakLine Enter

Edit.CharLeft Left Arrow

Edit.CharLeftExtend Shift+Left Arrow

Edit.CharRight Right Arrow

Edit.CharRightExtend Shift+Right Arrow

Edit.DocumentEnd End

Edit.DocumentEndExtend Shift+End

Edit.DocumentStart Home

Edit.DocumentStartExtend Shift+Home

Edit.InsertTab Tab

Edit.LineDown Down Arrow

Edit.LineDownExtend Shift+Up Arrow


C O M M A N DS K EY B O A RD SH O RTC UT S

Edit.LineUp Up Arrow

Edit.LineUpExtend Shift+Down Arrow

Edit.MoveControlDown Ctrl+Down Arrow

Edit.MoveControlLeft Ctrl+Left Arrow

Edit.MoveControlRight Ctrl+Right Arrow

Edit.MoveControlUp Ctrl+Up Arrow

Edit.SelectionCancel Escape

Edit.SizeControlDown Ctrl+Shift+Down Arrow

Edit.SizeControlLeft Ctrl+Shift+Left Arrow

Edit.SizeControlRight Ctrl+Shift+Right Arrow

Edit.SizeControlUp Ctrl+Shift+Up Arrow

Edit.TabLeft Shift+Tab

Work Item Editor


C O M M A N DS K EY B O A RD SH O RTC UT S

Edit.CreateCopyofWorkItem Shift+Alt+C

Edit.RefreshWorkItem F5

Team.NewLinkedWorkItem Shift+Alt+L

Work Item Query View


C O M M A N DS K EY B O A RD SH O RTC UT S

Edit.CreateCopyofWorkItem Shift+Alt+C

Edit.Indent Shift+Alt+Right Arrow

Edit.Outdent Shift+Alt+Left Arrow

Team.NewLinkedWorkItem Shift+Alt+L

Team.Refresh F5

Window.Toggle Shift+Alt+V
Work Item Results View
C O M M A N DS K EY B O A RD SH O RTC UT S

Edit.CreateCopyofWorkItem Shift+Alt+C

Edit.Indent Shift+Alt+Right Arrow

Edit.Outdent Shift+Alt+Left Arrow

Team.GotoNextWorkItem Shift+Alt+N

Team.GotoPreviousWorkItem Shift+Alt+P

Team.NewLinkedWorkItem Shift+Alt+L

Team.Refresh F5

Window.Toggle Shift+Alt+V

Workflow Designer
C O M M A N DS K EY B O A RD SH O RTC UT S

Edit.CompleteWord Ctrl+K, W

or

Ctrl+K, Ctrl+W

or

Ctrl+Spacebar

or

Alt+Right Arrow

Edit.DecreaseFilterLevel Alt+,

Edit.IncreaseFilterLevel Alt+.

Edit.ListMembers Ctrl+K, L

or

Ctrl+K, Ctrl+L

or

Ctrl+J
C O M M A N DS K EY B O A RD SH O RTC UT S

Edit.ParameterInfo Ctrl+K, P

or

Ctrl+K, Ctrl+P

or

Ctrl+Shift+Spacebar

Edit.QuickInfo Ctrl+K, I

or

Ctrl+K, Ctrl+I

WorkflowDesigner.Collapse Ctrl+E, Ctrl+C

or

Ctrl+E, C

WorkflowDesigner.CollapseAll or

WorkflowDesigner.ConnectNodes Ctrl+E, Ctrl+F

or

Ctrl+E, F

WorkflowDesigner.CreateVariable Ctrl+E, Ctrl+N

or

Ctrl+E, N

WorkflowDesigner.ExpandAll Ctrl+E, Ctrl+X

or

Ctrl+E, X

WorkflowDesigner.ExpandInPlace Ctrl+E, Ctrl+E

or

Ctrl+E, E

WorkflowDesigner.GoToParent Ctrl+E, Ctrl+P

or

Ctrl+E, P
C O M M A N DS K EY B O A RD SH O RTC UT S

WorkflowDesigner.MoveFocus Ctrl+E, Ctrl+M

or

Ctrl+E, M

WorkflowDesigner.NavigateThroughDesigner Ctrl+Alt+F6

WorkflowDesigner.Restore Ctrl+E, Ctrl+R

or

Ctrl+E, R

WorkflowDesigner.ShowHideArgumentDesigner Ctrl+E, Ctrl+A

or

Ctrl+E, A

WorkflowDesigner.ShowHideImportsDesigner Ctrl+E, Ctrl+I

or

Ctrl+E, I

WorkflowDesigner.ShowHideOverviewMap Ctrl+E, Ctrl+O

or

Ctrl+E, O

WorkflowDesigner.ShowHideVariableDesigner Ctrl+E, Ctrl+V

or

Ctrl+E, V

WorkflowDesigner.ToggleSelection Ctrl+E, Ctrl+S

or

Ctrl+E, S

WorkflowDesigner.ZoomIn Ctrl+Num +

WorkflowDesigner.ZoomOut Ctrl+Num -

XAML UI Designer
C O M M A N DS K EY B O A RD SH O RTC UT S

Design.FitAll Ctrl+0

Design.ShowHandles F9
C O M M A N DS K EY B O A RD SH O RTC UT S

Design.ZoomIn Ctrl+Alt+=

Design.ZoomOut Ctrl+Alt+-

Format.EditText F2

Format.ResetLayout.All Ctrl+Shift+R

View.EdgeLeftMoveLeft Ctrl+Shift+,

View.EdgeLeftMoveRight Ctrl+Shift+.

View.EdgeRightMoveLeft Ctrl+Shift+Alt+,

View.EdgeRightMoveRight Ctrl+Shift+Alt+.

Run project code Ctrl+F9

XML (Text) Editor


C O M M A N DS K EY B O A RD SH O RTC UT S

XML.StartXSLTDebugging Alt+F5

XML.StartXSLTWithoutDebugging Ctrl+Alt+F5

XML Schema Designer


C O M M A N DS K EY B O A RD SH O RTC UT S

GraphView.BottomtoTop Alt+Up Arrow

GraphView.LefttoRight Alt+Right Arrow

GraphView.RighttoLeft Alt+Left Arrow

GraphView.ToptoBottom Alt+Down Arrow

OtherContextMenus.GraphView.RemovefromWorkspace Delete

XsdDesigner.ShowContentModelView Ctrl+2

XsdDesigner.ShowGraphView Ctrl+3

XsdDesigner.ShowStartView Ctrl+1

See Also
Image Editor for Icons Using IntelliSense
Using IntelliSense
10/18/2019 • 4 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version
selector at the top left. We recommend upgrading to Visual Studio 2019. Download it here

IntelliSense is the general term for a number of features: List Members, Parameter Info, Quick Info, and
Complete Word. These features help you to learn more about the code you are using, keep track of the
parameters you are typing, and add calls to properties and methods with only a few keystrokes.
Many aspects of IntelliSense are language-specific. For more information about IntelliSense for different
languages, see the topics listed under See Also.

List Members
A list of valid members from a type (or namespace) appears after you type a trigger character (for example, a
period ( . ) in managed code or :: in C++). If you continue typing characters, the list is filtered to include only
the members that begin with those characters.
After selecting an item, you can insert it into your code by pressing TAB or by typing a space. If you select an
item and type a period, the item appears followed by the period, which brings up another member list. When
you select an item but before you insert it, you get Quick Info for the item.
In the member list, the icon to the left represents the type of the member, such as namespace, class, function, or
variable. For a list of icons, see Class View and Object Browser Icons. The list may be quite long, so you can press
PAGE UP and PAGE DOWN to move up or down in the list.

You can invoke the List Members feature manually by typing CTRL+J, clicking Edit/IntelliSense/List
Members , or clicking the List Members button on the editor toolbar. When it is invoked on a blank line or
outside a recognizable scope, the list displays symbols in the global namespace.
To turn List Members off by default (so that it does not appear unless specifically invoked), go to
Tools/Options/All Languages and deselect Auto list members . If you want to turn off List Members only
for a specific language, go to the General settings for that language.
You can also change to suggestion mode, in which only the text you type is inserted into the code. For example,
if you enter an identifier that is not in the list and press TAB, in completion mode the entry would replace the
typed identifier. To toggle between completion mode and suggestion mode, press CTRL+ALT+SPACEBAR or click
Edit/IntelliSense/Toggle Completion Mode .
Parameter Info
Parameter Info gives you information about the number, names, and types of parameters required by a method,
attribute generic type parameter (in C#), or template (in C++).
The parameter in bold indicates the next parameter that is required as you type the function. For overloaded
functions, you can use the UP and DOWN arrow keys to view alternative parameter information for the function
overloads.

When you annotate functions and parameters with XML Documentation comments, the comments will display
as Parameter Info. For more information, see Supplying XML Code Comments.
You can manually invoke Parameter Info by clicking Edit IntelliSense/Parameter Info , typing
CTRL+SHIFT+SPACE, or clicking the Parameter Info button on the editor toolbar.

Quick Info
Quick Info displays the complete declaration for any identifier in your code.

When you select a member from the List Members box, Quick Info also appears.

You can manually invoke Quick Info by clicking Edit/IntelliSense/Quick Info , typing CTRL+I, or clicking the
Quick Info button on the editor toolbar.
If a function is overloaded, IntelliSense may not display information for all forms of the overload.
You can turn Quick Info off In C++ by setting Tools/Options/Text Editor/C/C++/Advanced/Auto Quick
Info to false .

Complete Word
Complete Word completes the rest of a variable, command, or function name once you have entered enough
characters to disambiguate the term. You can invoke Complete Word by clicking Edit/IntelliSense/Complete
Word , typing CTRL+SPACE, or clicking the Complete Word button on the editor toolbar.

IntelliSense Options
IntelliSense options are on by default. To turn them off, click Tools/Options/Text Editor and deselect
Parameter information or Auto list members if you do not want the List Members feature.

Troubleshooting IntelliSense
The IntelliSense options may not work as you expect in certain cases.
The cursor is below a code error. You might not be able to use IntelliSense if an incomplete function or other
error exists in the code above the cursor because IntelliSense might not be able to parse the code elements. You
can resolve this problem by commenting out the applicable code.
The cursor is in a code comment. You can't use IntelliSense if the cursor is in a comment in your source file.
The cursor is in a string literal. You can't use IntelliSense if the cursor is in the quotation marks around a
string literal, as in the following example:

MessageBox( hWnd, "String literal|") )

The automatic options are turned off. By default, IntelliSense works automatically, but you can disable it.
Even if automatic statement completion is disabled, you can invoke an IntelliSense feature.

See Also
Visual Basic-Specific IntelliSense Visual C# IntelliSense JavaScript IntelliSense Supplying XML Code Comments
Visual Basic-Specific IntelliSense
10/18/2019 • 2 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version
selector at the top left. We recommend upgrading to Visual Studio 2019. Download it here

The Visual Basic source code editor offers the following IntelliSense features:
Syntax tips
Syntax tips display the syntax of the statement that you are typing. This is useful for statements such as
Declare.

Automatic Completion
Completion on various keywords
For example, if you type goto and a space, IntelliSense will display a list of the defined labels in a drop-
down menu. Other supported keywords include Exit , Implements , Option , and Declare .
Completion on Enum and Boolean

When a statement will refer to a member of an enumeration, IntelliSense will display a list of the members
of the Enum . When a statement will refer to a Boolean , IntelliSense will display a true-false drop-down
menu.
Completion can be turned off by default by deselecting Auto list members from the General property
page in the Visual Basic folder.
You can manually invoke completion by invoking List Members, Complete Word, or ALT+RIGHT ARROW.
For more information, see Using IntelliSense.

IntelliSense in Zone
IntelliSense in Zone assists Visual Basic developers who need to deploy applications through ClickOnce and are
constrained to partial trust settings. This feature:
Enables you to choose the permissions the application will run with.
Display APIs in the chosen Zone as available in List Members, and display APIs that require additional
permissions as unavailable.
For more information, see Code Access Security for ClickOnce Applications.

See Also
Using IntelliSense
Filtered Completion Lists in Visual Basic
10/18/2019 • 2 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version selector
at the top left. We recommend upgrading to Visual Studio 2019. Download it here

In Visual Basic, IntelliSense completion lists have two tab controls located near the bottom of the lists. The
Common tab, which is selected by default, displays items that are most often used to complete the statement that
you are writing. The All tab displays all items that are available for automatic completion, including those that are
also on the Common tab.

See Also
Using IntelliSense Visual Basic-Specific IntelliSense
Visual C# IntelliSense
10/18/2019 • 8 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version
selector at the top left. We recommend upgrading to Visual Studio 2019. Download it here

Visual C# IntelliSense is available when coding in the editor, and while you debugging in the Immediate Mode
command window.

Completion Lists
The IntelliSense completion lists in Visual C# contain tokens from List Members, Complete Word, and more. It
provides quick access to:
Members of a type or namespace,
Variables, commands, and functions names,
Code snippets,
Language Keywords,
Extension Methods
The Completion List in C# is also smart enough to filter out irrelevant tokens and pre-select a token based
on context. For more information, see Filtered Completion Lists in C# and Pre-selected Completion List
Items in C#.
Code Snippets in Completion Lists
In Visual C#, the completion list includes code snippets to help you easily insert predefined bodies of code into
your program. Code snippets appear in the completion list as the snippet's Shortcut Element (Intellisense Code
Snippets). For more information about code snippets that are available in Visual C# by default, see Visual C# Code
Snippets.
Language Keywords in Completion Lists
In Visual C#, the completion list also includes language keywords. For more information about C# language
keywords, see C# Keywords.
Extension Methods in Completion Lists
In Visual C#, the completion list includes Extension Methods that are in scope.

NOTE
The completion list does not display all extension methods for String objects.

Extension methods use a different icon than instance methods. For a listing of list icons, see Class View and Object
Browser Icons. When an instance method and extension method with the same name are both in scope, the
completion list displays the extension method icon.
Filtered Completion Lists
IntelliSense removes unnecessary members from the completion list by using filters.
Visual C# filters the completion lists that appear for these items:
Interfaces and base classes. IntelliSense automatically removes items from the interface and base class
completion lists, in both class declaration base and interface lists and constraint lists. For example, enums
do not appear in the completion list for base classes, because enums cannot be used for base classes. The
completion list of base classes only contains interfaces and namespaces. If you select an item in the list and
then type a comma, IntelliSense removes base classes from the completion list because Visual C# does not
support multiple inheritance. The same behavior occurs for constraint clauses also.
Attributes : When you apply an attribute to a type, the completion list is filtered so that the list only
contains those types that descend from the namespaces that contain those types, such as Attribute.
as and is operators.
Catch clauses.
Object Initializers: Only members that can be initialized will appear in the completion list.
new keyword : When you type new and then press the SPACEBAR, a completion list appears. An item is
automatically selected in the list, based on the context in your code. For example, items are automatically
selected in the completion list for declarations and for return statements in methods.
as and is Operators: A filtered completion list is displayed automatically when you press the SPACEBAR
after you have typed the as or is keyword.
Events: When you type the keyword event , the completion list only contains delegate types.
Parameter help automatically sorts to the first method overload that matches the parameters as you enter
them. If multiple method overloads are available, you can use the up and down arrows to navigate to the
next possible overload in the list.

Most recently used members


IntelliSense remembers the members that you have recently selected in the pop-up List Members box for
automatic object name completion. The next time you use Member List, the most recently used members are
shown at the top. The history of most recently used members is cleared between each session in the IDE.

override
When you type override and then press SPACEBAR, IntelliSense displays all of the valid base class members that
you can override in a pop-up list box. Typing the return type of the method after override will prompt IntelliSense
to only show methods that return the same type. When IntelliSense cannot find any matches, it will display all of
the base class members.

Automatic Code Generation


Add using
The Add using IntelliSense operation enables you to maintain your focus on the code you are writing rather than
requiring you to shift your focus to another part of the code.
To initiate the Add using operation, position the cursor on a type reference that cannot be resolved. For example,
when you create a console application and then add XmlTextReader to the body of the Main method, a smart tag
will appear under the rightmost character of XmlTextReader , since it appears as a type reference that cannot be
resolved.
You can then invoke the Add using by selecting it from Resolve submenu of the IntelliSense menu or the context
menu, or by invoking Add using through the smart tag. The smart tag is only visible when the cursor is positioned
on, or adjacent to, the unbound type.

Organize usings
The Organize Usings options sort and remove using and extern declarations without changing the behavior
of the source code. Over time, source files may become bloated and difficult to read because of unnecessary and
unorganized using directives. The Organize Usings options compact source code by removing unused using
directives and improves readability by sorting them.
To see the available options in the Visual Studio IDE, on the Edit menu, point to IntelliSense , and then point to
Organize Usings . The IDE provides the following options to organize and remove usings directives:
Implement Interface
IntelliSense provides an option to help you implement an interface while working in the Code Editor. Normally, to
implement an interface properly you must create a method declaration for every member of the interface in your
class. Using IntelliSense, after you type the name of an interface in a class declaration, a smart tag is displayed. The
smart tag gives you the option to implement the interface automatically, using explicit or implicit naming. Under
explicit naming, the method declarations carry the name of the interface; under implicit naming, the method
declarations do not indicate the interface to which they belong. An explicitly named interface method can only be
accessed through an interface instance, and not through a class instance. For more information, see Explicit
Interface Implementation.
Implement Interface will generate the minimum number of method stubs that is required to satisfy the interface. If
a base class implements parts of the interface, then those stubs are not regenerated.
Implement abstract base class
IntelliSense provides an option to help you implement members of an abstract base class automatically while
working in the Code Editor. Normally, to implement members of an abstract base class requires creating a new
method definition for each method of the abstract base class in your derived class. Using IntelliSense, after typing
the name of an abstract base class in a class declaration, a smart tag is displayed. The smart tag gives you the
option to implement the base class methods automatically.
The method stubs that are generated by the Implement Abstract Base Class feature are modeled by the code
snippet defined in the file MethodStub.snippet. Code Snippets are modifiable. For more information, see
Walkthrough: Creating a Code Snippet.
Generate from usage
The Generate From Usage feature enables you to use classes and members before you define them. You can
generate a stub for any class, constructor, method, property, field, or enum that you want to use but have not yet
defined. You can generate new types and members without leaving your current location in code. This minimizes
interruption to your workflow.
A wavy underline appears under each undefined identifier. When you rest the mouse pointer on the identifier, an
error message appears in a tooltip.
To display the appropriate options, you can use one of the following procedures:
Click the undefined identifier. A short underline appears under the leftmost character. Rest the mouse
pointer on the short underline, and a smart tag (an icon) appears. Click the smart tag.
Click the undefined identifier, and then press CTRL+. (period).
Right-click the undefined identifier, and then click Generate .
The options that appear can include the following:
Generate proper ty stub
Generate field stub
Generate method stub
Generate class
Generate new type (for a class, struct, interface, or enum)

Generate event handlers


In the Code Editor, IntelliSense can help you hook up methods (event handlers) to event fields.
When you type the += operator after an event field in a .cs file, IntelliSense prompts you with the option to press
the TAB key. This inserts a new instance of a delegate that points to the method handling the event.

If you press TAB, IntelliSense automatically finishes the statement for you and displays the event handler reference
as selected text in the Code Editor. To complete the automatic event hookup, IntelliSense prompts you to press the
TAB key again to create an empty stub for the event handler.

NOTE
If a new delegate that is created by IntelliSense references an existing event handler, IntelliSense communicates this
information in the tooltip. You can then modify this reference; the text is already selected in the Code Editor. Otherwise,
automatic event hookup is complete at this point.

If you press TAB, IntelliSense stubs out a method with the correct signature and puts the cursor in the body of your
event handler.

NOTE
Use the Navigate Backward command on the View menu (CTRL+-) to go back to the event hookup statement.

The following task shows how IntelliSense automatically hooks up an event handler named button1_Click to an
event field named button1.Click .

See Also
Visual Studio IDE
Walkthrough: Test-First Support with the Generate
From Usage Feature
10/18/2019 • 9 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version selector
at the top left. We recommend upgrading to Visual Studio 2019. Download it here

This topic demonstrates how to use the Generate From Usage feature, which supports test-first development.
Test-first development is an approach to software design in which you first write unit tests based on product
specifications, and then write the source code that is required to make the tests succeed. Visual Studio supports
test-first development by generating new types and members in the source code when you first reference them in
your test cases, before they are defined.
Visual Studio generates the new types and members with minimal interruption to your workflow. You can create
stubs for types, methods, properties, fields, or constructors without leaving your current location in code. When you
open a dialog box to specify options for type generation, the focus returns immediately to the current open file
when the dialog box closes.
The Generate From Usage feature can be used with test frameworks that integrate with Visual Studio. In this topic,
the Microsoft Unit Testing Framework is demonstrated.

NOTE
Your computer might show different names or locations for some of the Visual Studio user interface elements in the following
instructions. The Visual Studio edition that you have and the settings that you use determine these elements. For more
information, see Personalizing the IDE.

To create a Windows Class Library project and a Test project


1. In Visual C# or Visual Basic, create a new Windows Class Library project. Name it GFUDemo_VB or GFUDemo_CS
, depending on which language you are using.
2. In Solution Explorer , right-click the solution icon at the top, point to Add , and then click New Project . In
the New Project dialog box, in the Project Types pane on the left, click Test .
3. In the Templates pane, click Unit Test Project and accept the default name of UnitTestProject1. The
following illustration shows the dialog box when it appears in Visual C#. In Visual Basic, the dialog box looks
similar.
New
Project dialog box
4. Click OK to close the New Project dialog box.
5. In your class project, in Solution Explorer , right-click the References entry and click Add Reference .
6. In the Reference Manager dialog box, select Projects and then select your unit test project.
7. Click OK to close the Reference Manager dialog box.
8. In the Class1 file, immediately after the last of the existing using statements, add a using statement for the
test project:
In Visual Basic, add Using UnitTestProject1

In C#, add using UnitTestProject1;

9. Save your solution. You are now ready to begin writing tests
To generate a new class from a unit test
1. The test project contains a file that is named UnitTest1. Double-click this file in Solution Explorer to open it
in the Code Editor. A test class and test method have been generated.
2. Locate the declaration for class UnitTest1 and rename it to AutomobileTest . In C#, if a UnitTest1()
constructor is present, rename it to AutomobileTest() .

NOTE
IntelliSense now provides two alternatives for IntelliSense statement completion: completion mode and suggestion
mode. Use suggestion mode for situations in which classes and members are used before they are defined. When an
IntelliSense window is open, you can press CTRL+ALT+SPACEBAR to toggle between completion mode and
suggestion mode. See Using IntelliSense for more information. Suggestion mode will help when you are typing
Automobile in the next step.

3. Locate the TestMethod1() method and rename it to DefaultAutomobileIsInitializedCorrectly() . Inside this


method, create a new instance of a class named Automobile , as shown in the following illustrations. A wavy
underline appears, which indicates a compile-time error, and a smart tag appears under the type name. The
exact location of the smart tag varies, depending on whether you are using Visual Basic or Visual C#.
Visual Basic

Visual C#
4. Rest the mouse pointer over the smart tag to see an error message that states that no type named
Automobile is defined yet. Click the smart tag or press CTRL+. (CTRL+period) to open the Generate From
Usage shortcut menu, as shown in the following illustrations.

Visual Basic

Visual C#
5. Now you have two choices. You could click Generate 'Class Automobile' to create a new file in your test
project and populate it with an empty class named Automobile . This is a quick way to create a new class in a
new file that has default access modifiers in the current project. You can also click Generate new type to
open the Generate New Type dialog box. This provides options that include putting the class in an existing
file and adding the file to another project.
Click Generate new type to open the Generate New Type dialog box, which is shown in the following
illustration. In the Project list, click GFUDemo_VB or GFUDemo_CS to instruct Visual Studio to add the file
to the source code project instead of the test project.

Generate New Type dialog box


6. Click OK to close the dialog box and create the new file.
7. In Solution Explorer , look under the GFUDemo_VB or GFUDemo_CS project node to verify that the new
Automobile.vb or Automobile.cs file is there. In the Code Editor, the focus is still in
AutomobileTest.DefaultAutomobileIsInitializedCorrectly . You can continue to write your test with a
minimum of interruption.
To generate a property stub
1. Assume that the product specification states that the Automobile class has two public properties named
Model and TopSpeed . These properties must be initialized with default values of "Not specified" and -1
by the default constructor. The following unit test will verify that the default constructor sets the properties
to their correct default values.
Add the following line of code to DefaultAutomobileIsInitializedCorrectly .

Assert.IsTrue((myAuto.Model == "Not specified") && (myAuto.TopSpeed == -1));

Assert.IsTrue((myAuto.Model = "Not specified") And (myAuto.TopSpeed = -1))

Because the code references two undefined properties on Automobile , a smart tag appears. Click the smart
tag for Model and then click Generate proper ty stub . Generate a property stub for the TopSpeed
property also.
In the Automobile class, the types of the new properties are correctly inferred from the context.
The following illustration shows the smart tag shortcut menu.

Visual Basic

Visual C#
To locate the source code
1. Use the Navigate To feature to navigate to the Automobile.cs or Automobile.vb source code file so that you
can verify that the new properties have been generated.
The Navigate To feature enables you to quickly enter a text string, such as a type name or part of a name,
and go to the desired location by clicking the element in the result list.
Open the Navigate To dialog box by clicking in the Code Editor and pressing CTRL+, (CTRL+comma). In the
text box, type automobile . Click the Automobile class in the list, and then click OK .
The Navigate To window is shown in the following illustration.
Navigate To window
To generate a stub for a new constructor
1. In this test method, you will generate a constructor stub that will initialize the Model and TopSpeed
properties to have values that you specify. Later, you will add more code to complete the test. Add the
following additional test method to your AutomobileTest class.

[TestMethod]
public void AutomobileWithModelNameCanStart()
{
string model = "Contoso";
int topSpeed = 199;
Automobile myAuto = new Automobile(model, topSpeed);
}

<TestMethod()> Public Sub AutomobileWithModelNameCanStart()


Dim model As String = "Contoso"
Dim topSpeed As Integer = 199
Dim myAuto As New Automobile(model, topSpeed)
End Sub

2. Click the smart tag under the new class constructor and then click Generate constructor stub . In the
Automobile class file, notice that the new constructor has examined the names of the local variables that are
used in the constructor call, found properties that have the same names in the Automobile class, and
supplied code in the constructor body to store the argument values in the Model and TopSpeed properties.
(In Visual Basic, the _model and _topSpeed fields in the new constructor are the implicitly defined backing
fields for the Model and TopSpeed properties.)
3. After you generate the new constructor, a wavy underline appears under the call to the default constructor in
DefaultAutomobileIsInitializedCorrectly . The error message states that the Automobile class has no
constructor that takes zero arguments. To generate an explicit default constructor that does not have
parameters, click the smart tag and then click Generate constructor stub .
To generate a stub for a method
1. Assume that the specification states that a new Automobile can be put into a Running state if its Model and
TopSpeed properties are set to something other than the default values. Add the following lines to the
AutomobileWithModelNameCanStart method.

myAuto.Start();
Assert.IsTrue(myAuto.IsRunning == true);
myAuto.Start()
Assert.IsTrue(myAuto.IsRunning = True)

2. Click the smart tag for the myAuto.Start method call and then click Generate method stub .
3. Click the smart tag for the IsRunning property and then click Generate proper ty stub . The Automobile
class now contains the following code.

public class Automobile


{
public string Model { get; set; }
public int TopSpeed { get; set; }

public Automobile(string model, int topSpeed)


{
this.Model = model;
this.TopSpeed = topSpeed;
}

public Automobile()
{
// TODO: Complete member initialization
}

public void Start()


{
throw new NotImplementedException();
}

public bool IsRunning { get; set; }


}

Public Class Automobile


Sub New(ByVal model As String, ByVal topSpeed As Integer)
_model = model
_topSpeed = topSpeed
End Sub
Sub New()
' TODO: Complete member initialization
End Sub

Property Model() As String


Property TopSpeed As Integer
Property IsRunning As Boolean
Sub Start()
Throw New NotImplementedException
End Sub
End Class

To run the tests


1. On the Unit Test menu, point to Run Unit Tests , and then click All Tests . This command runs all tests in all
test frameworks that are written for the current solution.
In this case, there are two tests, and they both fail, as expected. The DefaultAutomobileIsInitializedCorrectly
test fails because the Assert.IsTrue condition returns False . The AutomobileWithModelNameCanStart test fails
because the Start method in the Automobile class throws an exception.
The Test Results window is shown in the following illustration.
Test Results window
2. In the Test Results window, double-click on each test result row to go to the location of each test failure.
To implement the source code
1. Add the following code to the default constructor so that the Model , TopSpeed and IsRunning properties
are all initialized to their correct default values of "Not specified" , -1 , and True ( true ).

public Automobile()
{
this.Model = "Not specified";
this.TopSpeed = -1;
this.IsRunning = true;
}

Sub New()
Model = "Not specified"
TopSpeed = -1
IsRunning = True
End Sub

2. When the Start method is called, it should set the IsRunning flag to true only if the Model or TopSpeed
properties are set to something other than their default value. Remove the NotImplementedException from
the method body and add the following code.

public void Start()


{
if (this.Model != "Not specified" || this.TopSpeed != -1)
this.IsRunning = true;
else
this.IsRunning = false;
}

Sub Start()
If Model <> "Not specified" Or TopSpeed <> -1 Then
IsRunning = True
Else
IsRunning = False
End If
End Sub

To run the tests again


1. On the Test menu, point to Run , and then click All Tests in Solution . This time the tests pass. The Test
Results window is shown in the following illustration.

Test Results window

See Also
Generate From Usage Writing Code Using IntelliSense Unit Test Your Code
JavaScript IntelliSense
1/10/2020 • 10 minutes to read

NOTE
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version
selector at the top left. We recommend upgrading to Visual Studio 2019. Download it here

IntelliSense helps you write code faster and with fewer errors by providing information while you code. As you
work with client script in the JavaScript editor, IntelliSense lists the objects, functions, properties, and parameters
that are available based on your current context. You can select a coding option from the pop-up list provided by
IntelliSense to complete the code.
IntelliSense makes it easier to complete the following tasks:
Find member information.
Insert language elements directly into your code.
Maintain your context without having to leave the code editor.
Support custom IntelliSense