Home
Wiley Visual Basic 2005 Programmer's Reference
Contents
1. 80 WindowsApplication1 Microsoft Visual Studio BEES File Edit View Project Build Debug Data Tools Window Community Help a a oF id a amp g v AnyCPU i ail Rebuild WindowsApplication1 it Bt gt 3 2 Clean WindowsApplication1 x BS ee er i ip Publish WindowsApplication1 a z Eat Configuration Manager fe WindowsApplication1 g a My Project 3 ES Form1 vb an Error List hx _1 0 Warnings i 0 Messages D File Line Column Project z B Error List 2j Task List Comman E Output jimmedia 4 Data Sources Slsolution Explorer Item s Saved 7 Figure 1 17 The Build menu lets you compile projects 19 Chapter 1 Following is a description of commands associated with the Build menu 20 Q Build WindowsApplication This command compiles the currently selected project in this case the project WindowsApplication1 Visual Studio examines the project s files to see if any have changed since the last time it compiled the project If any of the files have changed Visual Studio recompiles those files to update the result Rebuild WindowsApplication This command recompiles the currently selected project from scratch The Build WindowsApplication1 command compiles only the files that you have modified since they were last built This command rebuilds every file Clean WindowsApplication This command removes temporary and intermediate files that were creat
2. 20 HoverOverVariable Debugging Microsoft Visual Studio BEE File Edit View Project Build Debug Tools Window Community Help BB Gud am 9 c EE ae P ieu Ss CS tex a 5 ARR e le ELI ORS Baspeasds Rr prali Form1 vb X E CG lx a 3 Form1 Events gt Load gt 2 e Ee Fo z E 10 Public Class Formi es HoverOverVariable o 25 2 My Project o g 3E Private Sub Formi_Load ByVal sender As System Objec E Form1 vb EA 4 Dim arr 99 As Integer 5 For s Integer 0 To 99 s i a ti if Next arr Length 100 a m Limiet S A 8 Debug Uriz o 0 k Length 9i End Sub vit 1 10 End Class 9 2 4 11 cn 9 4 16 Properties ix 9 5 25 a 3 6 36 Form1 vb File Properties ag v 7 49 a E Ien Build Action A 9 12 144 Custom Tool LJ ca oe SS ee X o 013 169 Custom Tool N Bookmark File Location Line Nun 14 196 FileName __ Form1 vb Build Action How the file relates to the build and gt Command Window Immediate Window A Bookmarks H Error List Output oniran pro conas Ready Figure 1 56 You can hover the mouse over a variable at run time to see its value IDE If a variable has properties that are references to other objects you can hover over their plus signs to expand those objects You can continue following the plus signs to drill into the variable s object hierar chy as deeply as you like Intellisense I
3. Properties ix Form1_Load Attributes ws 2 US ch5 NS 5 Figure 1 7 The View menu lets you show and hide IDE windows and toolbars 10 IDE Following is a description of commands associated with the View menu m m Code The Code command opens the selected file in a code editor window For example to edit a form s code you can click on the form in the Solution Explorer and then select View Code Designer The Designer command opens the selected file in a graphical editor if one is defined for that type of file For example if the file is a form Visual Studio opens it in a graphical form editor If the file is a class module or a code module the View menu hides this command because Visual Studio doesn t have a graphical editor for those file types Open Opens the selected item with its default editor Open With Opens the selected item with an editor of your choosing For example you could open a form s code with a text editor Standard windows The next several commands shown in Figure 1 7 display the standard IDE windows Solution Explorer Class View Resource View Server Explorer Properties Window Bookmark Window Object Browser Toolbox Start Page and Property Manager These com mands are handy if you have hidden one of the windows and want to get it back The most use ful of these windows are described later in this chapter Web Browser The Web Browser
4. 33 Chapter 1 8 WindowsApplication4 Microsoft Visual Studio File Edit View Project Build Debug Data Format Tools eter Peter en oe ar x x i ee aA Preview Data J Add New Data Source Error List lx D J File Line Column Project r Error List E Task List gt Command Output Immediate Figure 1 36 The Data menu holds commands that deal with datasets The following list describes commands shown in Figure 1 36 Window Community Help 4 ts v 5 Solution Explorer Windo 2 X Pelee a ie WindowsApplication4 Sa My Project app config booksDataSet xsd E Form1 vb EJ Data Sources 3 Solution Explorer Properties lx OleDbConnection1 System Data Ole ApplicationSet Hame OleDbConnectior ConnectionStrit ConnectionTim 15 Database sf ConnectionString Information used to connect to a Data Source Q Show Data Sources This command displays the Data Sources window where you can work with the program s data sources For example you can drag and drop tables and fields from this window onto a form to create controls bound to the data Q Preview Data This command displays a dialog that lets you load data into a DataSet and view it at design time Q Add New Data Source This command displays the Data Source Configurati
5. Ga R R A gt Ri Toolbox E 2 Add Component Solution Explorer Windo 4 X 6 g Add Module Declarations a R A vg Add Class el WindowsApplication1 i Add Hew Item CtrlsShift A aa My Project E Add Existing Item SLAR ALI p 08d ByVal senden EE Fort vb Exclude From Project Show All Files Add Reference GData Sources Solution Explorer Add Web Reference Properties lx Y WindowsApplication1 Properties gt Form Attributes b 2 4 User Tasks CEE COM a False COM Visible True v Description Serializable False COM Class Expose Class to COM 4 Error List Jj Task List H Command Output jimmediate Ln5 Col 12 Ch 12 Figure 1 9 The Project menu lets you add files and references to the currently selected project Add New Item WindowsApplication1 1 1x Templates Visual Studio installed templates E Dialog Explorer Form G MDI Parent Form E About Box A Login Form E Splash Screen 2 Class 3 Module yg Interface H Component Class vg COM Class u DataSet J SOL Database Report 2 crystal Report FI User Control nherited Form nherited User Control A Custom Control A Web Custom Control EuResources File H Settings File Ye Code File 9 Class Diagram E XML File a XML Schema g XSLT File 5 Text File 9 HTML Page 94 Bitmap File Curs
6. Menus amp Toolbars __ D File Line Column Project i eel ShortcutsEnabl True Ss Size 96 20 Rh a FE ta Fo TabStop True gi 3 Tag ag ga a Text zi Components Text Printing KH r The text associated with the control aa gt Error List E Task List Command E Output jImmediate Ready C7 16 40 T 96 x 20 p Figure 1 37 The Format menu contains commands for formatting and arranging controls on a form m Align This submenu contains commands that align the controls you have selected in various ways It contains the commands Lefts Centers Rights Tops Middles Bottoms and to Grid For example the Lefts command aligns the controls so their left edges line up nicely The to Grid command snaps the controls to the nearest grid position This is useful if you have moved some controls off of the alignment grid possibly by using one of the other Align commands or by changing a control s Location property in the Properties window Make Same Size This submenu contains commands that change the size of the controls you have selected It contains the commands Width Height Both and Size to Grid The Size to Grid command adjusts the selected controls widths so that they are a multiple of the align ment grid size The other commands give the selected controls the same width height or both Horizontal Spacing This submenu contains commands that change the spacing between
7. New Breakpoint This submenu contains the Break At Function command This command dis plays a dialog that lets you specify a function where the program should break Delete All Breakpoints This command removes all breakpoints from the entire solution Enable All Breakpoints This command reenables any disabled breakpoints The Enable All Breakpoints command is available if any breakpoints are currently disabled Note that you can right click a line of code that contains a disabled breakpoint and select Enable Breakpoint to enable only that breakpoint Disable All Breakpoints This command temporarily disables all the solution s breakpoints The breakpoints are still defined but they don t interrupt the program s execution The Disable All Breakpoints command is available if any breakpoints are currently enabled Note that you can right click a line of code that contains a breakpoint and select Disable Breakpoint to disable only that breakpoint The Debug Windows Submenu The Debug menu s Windows submenu shown in Figure 1 26 contains commands that display debugging related windows The following list briefly describes these commands The two sections that follow describe some of the more complicated windows in greater detail 26 Q Breakpoints This command displays the Breakpoints window shown in Figure 1 27 This dia log shows the breakpoints their locations and their conditions Check or uncheck the boxes
8. This chapter describes Visual Studio s integrated development environment IDE It explains the most important windows menus and toolbars that make up the environment and shows how to customize them to suit your personal preferences It also explains some of the tools that provide help while you are writing Visual Basic applications Even if you are an experienced Visual Basic programmer you should at least skim this material The IDE is extremely complex and provides hundreds if not thousands of commands menus toolbars windows context menus and other tools for editing running and debugging Visual Basic projects Even if you have used the IDE for a long time there are sure to be some features that you have overlooked This chapter describes some of the most important of those features and you may discover something useful that you ve never noticed before Even after you ve read this chapter you should periodically spend some time wandering through the IDE to see what you ve missed Every month or so spend a few minutes exploring the menus and right clicking on things to see what their context menus contain As you become a more profi cient Visual Basic programmer you will find uses for tools that you may have previously dis missed or failed to understand It is important to remember that the Visual Studio IDE is extremely customizable You can move hide or modify the menus toolbars and windows create your own toolbars do
9. Figure 1 15 The Projects and Solutions folder s VB Defaults page lets you set default values for Option Explicit and Option Strict The final compiler directive Option Compare can take the values Binary or Text If you set Option Compare to Binary Visual Basic compares strings using their binary representations If you set Option Compare to Text Visual Basic compares strings using a case insensitive method that depends on your computer s localization settings Option Compare Binary is faster but may not always produce the result you want If you select a solution and then invoke the Project menu s Properties command Visual Studio displays the Solution Properties Pages dialog shown in Figure 1 16 Select an item on the left to view and modify the corresponding values on the right Build 18 The Build menu shown in Figure 1 17 contains commands that let you compile projects within a solution IDE Solution WindowsApplication1 Property Pages RES Configuration N A yi Platform N A v Configuration Manager E Common Properties Current selection Startup Project Single startup project Project Dependencies Debug Source Files WindowsApplication1 gt Configuration Properties C Multiple startup projects Configuration WindowsApplicationt None Windows4pplication2 None Figure 1 16 The Solution Properties Pages dialog lets you set solution properties
10. Processes CtrkAlt Z Step Out Shift F11 C o Guickwatcn Ctralt 0 Show output from Debug Toggle Breakpoint F9 WindowsApplicationl vshos Hew Breakpoint gt ssembly GAC_MSIL System Deployment 2 0 Windowsa pplicationl vshos ssembly GAC_MSIL System xXm1 2 0 0 0__b WindowsApplicationl vshos a Delete All Breakpoints Ctri Shift F9 ssembly GAC_MSIL Microsoft VisualBasic The thread lt No Name gt 0x Windowsa pplicationl vshos 9 Ref JulyCTPSre Ch01 Windowsapplicationl WindowsApplicationl vshost exe Managed Loaded C WINDOWS assembly GAC_MSIL System Runtime Remotii WindowsApplicationl vshost exe Managed Loaded C WINDOWS assembly GAC_MSIL Accessibility 2 0 0 0 a T sondosd l 10jdx3 uonnjos y E eq eb Disable All Breakpoints gt Command Window Immediate Window 7 Bookmarks Error List E Output Ready Ln5 Col 5 Ch5 INS 5 Figure 1 26 The Debug menu s Windows submenu contains commands that display debugging related windows Breakpoints Eg New X J5 columns Name Condition Hit Count Address we UA no condition break always currently 0 WindowsApplication1 Form1 Form1_Load Object S o _ Form1 vb line 4 character 9 no condition break always currently 0 WindowsApplication1 Form1 Form1_Load Object S o Form1 vb line 5 character 5 no condition break always currently 0 WindowsAppl
11. Visual Studio comes with hundreds of snippets for performing standard tasks Before you start working on a complicated piece of code you should take a look at the snippets that are already available to you In fact it would be worth your time to use the Snippet Manager available from the Tools menu to take a good look at the available snippets right now before you start a new project There s little point in you reinventing methods for calculating statistical values if someone has already done it and given you the code Snippets are stored in simple text files with XML tags so it is easy to share snippets with other develop ers Go to this book s Web page www vb helper com vbprogref htm to contribute snippets and to download snippets contributed by others IDE 7 UselntelliSense Microsoft Visual Studio iol x File Edit View Project Build Debug Data Tools Window Community Help a a ga aaao do a D debug Any CPU gt i 22 F S 2 0 FPR we as M lo oO gt SS 5 X _ Form1 vb Form1 vb Design x Pes A F Form1 Events gt F Load gt g 3 10 Public Class Form1 S E 3E Private Sub Formi_Load ByVal sender As System Object ByVal e As System Eventi 4 Dim i As Integer 3 2 5 i 12 e g 6 S Fh End Sub i 7 Te S Option Strict On disallows implicit conversions from 3 i End Class String to Integer ES 8 R2 Replace 1
12. aA A EL R Form1 System Windows Forms Foi S da m a c Eum 1 a f He al ii A ee Showlcon True val S J _1 0 Warnings ShowlnTaskbar True 3 3 a 3 D File Line Column Project E Size 300 178 r Tm y e i SizeGripStyle Auto S SnapToGrid True a ae na 0 gt StartPosition WindowsDefault Tag ss abl amp Text Form1 ch amp TonMoct Falco z w 1 aE Text A a KH r The text associated with the control Stonmon to Error List Jj Task List gt Command Output Immediate Ready Ee Figure 1 1 Initially the IDE looks more or less like this Chapter 1 The key pieces of the IDE are labeled with numbers in Figure 1 1 The following list briefly describes each of these pieces Q 1 Menus The menus contain standard Visual Studio commands These generally manipu late the current solution and the modules it contains although you can customize the menus as needed Visual Studio changes the menus and their contents depending on the object you cur rently have selected In Figure 1 1 a Form Designer marked with the number 4 is open so the IDE is displaying the menus for editing forms 2 Toolbars Toolbars contain tools that you can use to perform frequently needed actions The same commands may be available in menus but they are easier and faster to use in tool bars The IDE defines several standard toolbars such as Formatting Debug and Image Editor You
13. f End Set 13 F End Property 14 15 16 17i End Class 18 ba 4 F Zj Task List gt Command Window 4 Error List Bookmarks Output Immediate Window Ready Ln4 Col 27 Ch 27 INS D Figure 1 62 Values that you should replace in a snippet are highlighted Creating Snippets To create a new snippet you need to build an XML file containing the property tags to define the snippet and any replacements that the user should make The following code shows the Create a public prop erty snippet used in the previous section The outer CodeSnippets and CodeSnippet tags are stan dard and you should not change them Use the Title tag in the Header section to describe the snippet Inside the Snippet tag build a Declarations section describing any literal text that the user should replace This example defines DataType Description DefaultValue and PropertyName symbols Each literal definition includes an ID and can include a ToolTip and Description After the declarations the Code tag contains the snippets source code The syntax lt CDATA gt tells XML processors to include any characters including carriage returns between the lt CDATA and the gt in the enclosing tag 63 Chapter 1 lt CodeSnippets xmlns http schemas microsoft com VisualStudio 2005 CodeSnippet gt lt CodeSnippet Format 1 0 0 gt lt Header gt lt Title gt Create a public property lt Title gt lt Header gt
14. lt Snippet gt lt Declarations gt lt Literal gt lt ID gt DataType lt ID gt lt ToolTip gt The property s data type lt ToolTip gt lt Default gt Integer lt Default gt lt Literal gt lt Literal gt lt ID gt Description lt ID gt lt ToolTip gt The property s description lt ToolTip gt lt Default gt An Integer property lt Default gt lt Literal gt lt Literal gt lt ID gt DefaultValue lt ID gt lt ToolTip gt The property s default value lt ToolTip gt lt Default gt 0 lt Default gt lt Literal gt lt Literal gt lt ID gt PropertyName lt ID gt lt ToolTip gt The property s name lt ToolTip gt lt Default gt MyProperty lt Default gt lt Literal gt lt Declarations gt lt Code Language VB gt lt CDATA Description Private m PropertyName As DataType DefaultValues Public Property PropertyName As DataType Get Return m_ PropertyName End Get Set ByVal value As DataType m_ PropertyNames value End Set End Property lt Code gt lt Snippet gt lt CodeSnippet gt lt CodeSnippets gt Save the snippet s XML definition in a snippet directory To add the directory to the list of usable snippet locations select the Tool menu s Code Snippets Manager command to display the tool shown in Figure 1 63 Click the Add button browse to the new snippet directory and click OK Now the direc tory and the snippets that it contains will be available in the Insert Snip
15. the cursor s current line Right click and select Set Next Statement to make the program jump to a new location You can also drag the yellow arrow indicating the next statement to a new location in the left margin There are some restrictions on where you can move the execution position For example you cannot jump out of one routine and into another You can discover other run time features by exploring the editor at run time Right click on different parts of the editor to see which commands are available in that mode 65 Chapter 1 Summary 66 The Visual Studio integrated development environment provides many tools for writing and debugging applications It provides code snippets that make saving and reusing code easy It lets you add remove and disable complex breakpoints that check conditions and hit counts and that can perform customized actions You can use regions and bookmarks to organize and find pieces of code and you can step through the code line by line at execution time The IDE is extremely flexible You can show hide and rearrange windows add and remove items from menus and toolbars and write macros to automate simple chores Context menus attached to all sorts of objects provide help tools and other features that make sense for their particular objects and under dif ferent situations This chapter describes some of the most useful parts of the IDE but listing every last nook and cranny would be tedious
16. As Integer 5 For i As Integer O To 99 6 erni siti Next arr Length 100 8 q a es gt 8 Debug Wri 0 jr Length 9i F End Sub vit 1 10i End Class 2 4 11 3 9 213 is 5 25 z o 6 36 Form1 vb File Properties w v7 49 SSS a CAE compitc 12 144 Custom Tool Ld co g a S X o 13 169 Custom Tool N Bookmark File Location Line Nun 4 l 196 File Hame Form1 vb z Build Action How the file relates to the build and gt Command Window i jImmediate Window Bookmarks E Error List E Output dopiomant procnasnt Ready 4 Figure 1 57 IntelliSense displays a list of properties and methods that you might be trying to type 57 Chapter 1 After you finish typing a method and its opening parenthesis IntelliSense displays information about the method s parameters Figure 1 58 shows parameter information for a form object s SetBounds method This method takes four parameters x y width and height IntelliSense shows a brief description of the current parameter x As you enter parameter values Intellisense moves on to describe the other parameters IntelliSense also indicates whether there are overloaded versions of the method In Figure 1 58 IntelliSense is describing the first version of two available versions You can use the up and down arrows on the left to move through the list of overloaded versions Code Coloring and Highlighting 58 The code editor displays different types of code
17. Build Debug Data Format Tools Window Community Help l Projeen p amsn o any cru z Open gt Web Site Bt St os Ge ae Ma Be Se Add gt File Ctrl x Bete cee er i 4 Close Project From Existing Code BlIARIBAHN amp E Close Project hs 1 x EE WindowsApplication1 O F etme Si A eT teen LARA are An ane aia Project la Save Formi vb Ctr S 5 nt ee Save Form1 vb As i Save All Ctrl Shift s Export T late es eth ll were Data Sources Solution Explorer 4 Properties ix n Form1 System Windows Forms Foi ae ag nt Project parae et Showlcon True al Exit ShowlnTaskbar True Size 300 178 SizeGripStyle Auto SnapToGrid True StartPosition WindowsDefaulti Tag Text Form1 TonMoct Foleo hd Text The text associated with the control Error List E Task List gt Command Output Immediate ZA Figure 1 2 The File menu holds commands that deal with the solution and its files Following is a description of the commands contained in the File menu and its submenus Q New The New submenu shown in Figure 1 2 contains commands that let you create a new Visual Basic project Web site project generally ASP NET or a Web Service or file text file bitmap Visual Basic class icon and many others The Project From Existing Code command cre ates a new project and puts all of the files in a directory in it optionally including subdirectories New File
18. E gt Debug Any CPU g X WindowsApplication1 Form1 vb Form1 vb Design _ 7 vx a i 3 TE Application B S A Configuration Active Debug Pe Platform Active Any CPU he 1 Compile Build output path F Debug 2 binDebug Browse o Ref ae Advanced Compile Options S m Resources All configurations hr 2 Settings Option explicit Option strict Option compare Signing Jon gt On gt Binary a lig Y Condition Notification IE Security AROA 7 ls Implicit conversion TE Publish Late binding call could fail at run time cm Implicit type object assumed Use of variable prior to assignment Function Operator without return value Warning hies 4 P a Error List E Task List gt Command Window E Output EJimmediate Window Alt F9 was pressed Waiting for second key of chord Z Figure 1 14 The Compile tab contains important properties for controlling code generation The second compiler option is Option Strict When this option is turned off Visual Studio allows your code to implicitly convert from one data type to another even if the types are not always compatible For example Visual Basic will allow the following code to try to copy the string s into the integer i If the value in the string happens to be a number as in the first case this works If the string is not a number as in the second case this fails at run time Dim i As Integer Dim s A
19. Mobile Global A AdRotator System Web ULWebControls System Web 2 0 0 0 Global A AppearanceEditorP System Web ULWebControl System Web 2 0 0 0 Global A o Assemblyinstaller System Configuration Install System Configuratio Global A BackgroundWorker System ComponentModel System 2 0 0 0 Global A BehaviorEditorPart System Web ULWebControl System Web 2 0 0 0 Global A BindingNavigator System Windows Forms System Windows Fo Global A 4 gt Filter Clear AccessDataSource B Browse Language Invariant Language Invariant Country Version 2 0 0 0 Cancel Reset Figure 1 53 Use the Choose Toolbox Items dialog to select the tools in the Toolbox The Visual Basic Code Editor 52 Visual Studio includes editors for many different kinds of documents including several different kinds of code For example it has Hypertext Markup Language HTML Extensible Markup Language XML and Visual Basic editors These editors share some common features such as displaying comments and keywords in different colors As a Visual Basic developer you will use the Visual Basic code editor frequently so you should spend a few minutes learning about its specialized features Figure 1 54 shows the code editor displaying some Visual Basic code at run time To make referring to the code lines easier this figure displays line numbers To display line numbers invoke the Tools menu s Options comm
20. The New submenu s File command displays the dialog shown in Figure 1 3 The IDE uses integrated editors to let you edit the new file For example the simple bitmap editor lets you set a bitmap s size change its number of colors and draw on it When you close the file Visual Studio asks if you want to save the file and lets you decide where to put it Note that this doesn t automatically add the file to your current project You can save the file and use the Project Add Existing Item command if you want to do so Open The Open submenu contains commands that let you open a project or solution Web site or file The Convert command displays the Convert dialog shown in Figure 1 4 From this dialog you can launch the Visual Basic 2005 Upgrade Wizard which can help you convert Visual Basic 6 programs to Visual Basic 2005 Close This command closes the current editor In Figure 1 2 Form1 is open in the form designer editor This command would close this editor m Ooo vo IDE New File Categories Templates Visual Studio installed templates Web Visual C 5 Text File e HTML Page Script Aj Style Sheet E XML File A XML Schema a XSLT File 4 Bitmap File uf Icon File I Cursor File Eanative Resource Template ay Visual C Class va Visual J Class Ye Visual Basic Class 4 blank text file Open E Cancel Figure 1 3 The File New File command displays this dialog to let you sele
21. WindowsApplication1 Forml SearchDatabase indicating that this thread is executing the SearchDatabase rou tine in the Form1 module in program WindowsApplication1 The arrow on the left indicates that this is the currently active thread Threads Eg _ Wame __ Location Priority Suspend 3580 0 1260 lt No Name gt Highest 0 1292 lt No Name gt Normal 0 3664 lt No Name gt Normal 0 2064 lt No Name gt Normal 0 1892 lt No Name gt Normal 0 2392 lt No Name gt Normal 0 p 4068 lt No Name gt WindowsApplication3 Form1 SearchDatabase Normal jo id Figure 1 31 The Threads window displays information about the program s threads of execution Right click a thread and select Freeze to suspend it Select Thaw to make it resume execution Double click a thread or right click it and select Switch To Thread to activate that thread Modules This command displays the Modules window shown in Figure 1 32 This window displays information about the DLL and EXE files used by the program It shows each module s file name and path It indicates whether the module is optimized whether it is your code ver sus an installed library and whether debugging symbols are loaded Scrolled off the right edge 29 Chapter 1 of Figure 1 32 the window shows each module s load order lower numbered modules are loaded first the module s version timestamp and the process using the module Click on a col
22. delimiters are highlighted the editor provides drag and drop editing scroll bars are visible long lines are automatically wrapped line numbers are displayed and the editor provides smart indentation The Basic VB Specific subsection lets you specify options such as whether the editor uses outlining whether it displays procedure separators and suggested corrections for errors Database Tools Contains database parameters such as default lengths for fields of various types Debugging Contains debugging settings such as whether the debugger displays messages as modules are loaded and unloaded whether it should make you confirm when deleting all breakpoints and whether it should allow Edit and Continue Device Tools Contains options for development on devices such as Smartphones Pocket PCs or Windows CE HTML Designer Contains options for configuring HTML Designer These options determine such settings as whether the designer starts in source or design view and whether it displays Smart Tags for controls in design view Windows Form Designer Contains settings that control the Form Designer For example this section lets you determine whether the designer uses a snap to grid or snap lines Window The Window menu contains commands that control Visual Studio s windows Which commands are enabled depends on the type of window that has the focus Figure 1 48 shows this menu when the Toolbox has the focus 45 Ch
23. of the code at the same time This command changes to Remove Split when you use it Q Dockable Floating Tabbed Document Secondary windows such as the Toolbox Solution Explorer and Properties windows can be displayed as dockable as floating or as tabbed docu ments A dockable window can be attached to the edges of the IDE or docked with other sec ondary windows A floating window stays in its own independent window even if you drag it to a position where it would normally dock A tabbed document window is displayed in the main editing area in the center of the IDE with the forms classes and other project files Q Auto Hide Puts a secondary window in Auto Hide mode The window disappears and its title is displayed at the IDE s nearest edge When you click on the title or hover over it the win dow reappears so that you can use it If you click on another window this window hides itself again automatically 46 QO Hide Removes the window Q Auto Hide All Makes all secondary windows enter Auto Hide mode IDE Q New Horizontal Tab Group Splits the main document window horizontally so that you can view two different documents at the same time Q New Vertical Tab Group Splits the main document window vertically so that you can view two different documents at the same time Q Close All Documents Closes all documents Q Reset Window Layout Resets the window layout to a defaul
24. on the left to enable or disable breakpoints Right click a breakpoint to edit its location condition hit count and action Use the dialog s toolbar to create a new function breakpoint delete a breakpoint delete all breakpoints enable or disable all breakpoints go to a breakpoint s source code and change the columns displayed by the dialog Right click on a breakpoint to change its condition a condition that determines whether the breakpoint is activated hit count a count that determines whether the breakpoint is activated and When Hit action to take when acti vated See the section The Breakpoints Window later in this chapter for more detail IDE 2 WindowsApplication1 Debugging Microsoft Visual Studio BEES File Edit View Project Build Debug Tools Window Community Help ee ee en ee Ri bu a 0 SCs He Continue F5 Output i P iG R e ar E J Script Explorer Ctrl Alt l gt Form1 vb Form1 vb Design Pee tI Shift F5 Watch gt x 1 EE z 3 Form1 Events Detach All Autos Ctri Alt V A 5 1O Public Class Fo Terminate All E Locals CtrAlt V L x a haa 2 il Restart Ctrl Shift F5 immediate Ctr Alt l 3E Private Sub j 1 em Eventi E Attach to Process EY Call Stack Ctr Altec 4 Message 8 si L End Sub Exceptions Ctri Alt E Threads Ctri Alt H 6 4End Class Step Into F11 Modules Ctri Alt U l Step Over F10
25. submenu lets you display and manage a Web Browser within the IDE When the Web Browser is visible the IDE displays a Web toolbar that lets you enter a URL jump to one of your favorite links or add the current page to your Web favorites The Web Browser is particular useful for debugging Web applications because it lets you see what Web pages will look like before you publish them Other Windows The Other Windows submenu lists other standard menus that are not listed in the View menu itself These include the Macro Explorer Document Outline Task List Error List Command Window Output Code Definition Window and Object Test Bench It also includes find results windows that list the results of searches you make using the Edit Find and Replace commands Tab Order If a form contains controls the Tab Order command displays the tab order on top of each control You can click on the controls in the order you want them to have to set their tab order s quickly and easily Toolbars The Toolbars submenu lets you toggle the currently defined toolbars to hide or dis play them This submenu lists the standard toolbars in addition to any custom toolbars you have created Full Screen The Full Screen command hides all toolbars and windows except for any editor windows that you currently have open It also hides the Windows taskbar so that the IDE occu pies as much space as possible This gives you the most space possible for working with
26. umn to sort the modules by that column Optimized User Code Symbol Status B mscorlib dll C WINDOWS assembly GAC_32 mscorlib 2 0 0 Yes No Skipped loading Bi Microsoft VisualStudio HostingP C WINDOWS assembly GAC_MSIL Microsoft Yes No Skipped loading Bi System Windows Forms dll C WINDOWS assembly GAC_MSIL System Wi Yes No Skipped loading B System dll C WINDOWS assembly GAC_MSIL Systemi2 0 Yes No Skipped loading Bi System Drawing dll C WINDOWS assembly GAC_MSIL System Dr Yes No Skipped loading Bi Microsoft VisualStudio HostingP C WINDOWS assembly GAC_MSIL Microsoft Yes No Skipped loading a WindowsApplication1 vshost exe C WB Prog Ref CeSrc Ch01 WindowsApplicati Yes No Skipped loading B System Deployment dil C WINDOWS assembly GAC_MSIL System De Yes No Skipped loading l Microsoft VisualBasic dll C WINDOWS assembly GAC_MSIL Microsoft Yes Ho Skipped loading 2 WindowsApplication1 EXE C VB Prog Ref CeSrc Ch01 WindowsAppilicati Symbols loaded B System Runtime Remoting dll C WINDOWS assembly GAC_MSIL System Ru Yes Ho Skipped loading a Figure 1 32 The Modules window displays information about the modules used by the program Q Processes This window lists processes that are attached to the Visual Studio session This includes any programs launched by Visual Studio and processes that you attached to using the Debug menu s Attach to Process comm
27. wavy error underline and a suggestion indicator because it knows a way to fix this error If you hover over the suggestion indicator the editor displays a tooltip describing the problem and an error icon If you click the icon Visual Studio displays a dialog describing the error and listing the actions that you may want to take Figure 1 60 shows the suggestion dialog for the error in Figure 1 59 If you click the text over the revised sample code or if you double click the sample code the editor makes the change 59 Chapter 1 8 UselntelliSense Microsoft Visual Studio oix File Edit View Project Build Debug Data Tools Window Community Help a a GHU yama D Debug Any CPU gt TR aj Elg E PREEN Al Form1 vb Form1 vb Design x F Form1 Events 7 Load gt 16 Public Class Formi JE Private Sub Formi_Load ByVal sender As System Object ByVal e As System Eventi Dim i As Integer i 12 1ojdx3 uonnjos R In n End Sub L End Class s snos eg E xoqjooy S ip oO Sensedoid a _ aMMa Ready Ln 6 Col 9 Ch9 Figure 1 59 If the code editor can figure out what s wrong it displays a suggestion indicator Code Snippets 60 A code snippet is a piece of code that you might find useful in many applications It is stored in a snip pet library so that you can quickly insert it into a new application
28. window to the corresponding edge of the other window The center icon places the dropped window in a tab within the other window If you look closely at Figure 1 51 you can see a little image of a document with two tabs on the bottom in this icon When you drag the mouse over one of the docking icons the IDE displays a dark gray rectangle to give you an idea of where the window will land if you drop it In Figure 1 51 the mouse is over the main document window s right docking icon so the grayed rectangle shows the dropped window taking up the right half of the main document window If you drop a window somewhere other than on a docking icon the window becomes free floating Once you drop a window on the main document area it becomes a tabbed document and you cannot later pull it out To free the window select it and use the Window menu s Dockable or Floating command 49 Chapter 1 72 WindowsApplication Microsoft Visual Studio File Edit View Project Build Debug Data Tools Window Community Help iar a Gi s amp B 9 C B B D debug Any CPU gt j Ahe AEEA Data Sources Juba Your project currently has no data sources associated with it Add a new data source then data bind items by dragging Add New Data Source Error List 2j Task List Comman Output Immediate Ln4 Col9 ch9 INS 4 Figure 1 51 Use the IDE s docking icons to help you doc
29. you don t want and create new customized toolbars to suit your needs Then you can find the original standard toolbars if you decide you need them later The section Customize later in this chapter has more to say about rearranging the IDE s components This chapter describes the Visual Studio IDE Before you can understand how to use the IDE to manage Visual Basic projects and solutions however you should know what projects and solutions are Projects and Solutions A project is a group of files that produces some specific output This output may be a compiled exe cutable program a dynamic link library DLL of classes for use by other projects or a custom control for use on other Windows forms A solution is a group of one or more projects that should be managed together For example suppose that you are building a server application that provides access to your order database You are also building a client program that each of your sales representatives will use to query the server application Because these two projects are closely related it might make sense to manage them in a single solution When you open the solution you get instant access to all the files in both projects Both projects and solutions can include associated files that are useful for building the application but that do not become part of a final compiled product For example a project might include the applica tion s proposal and architecture document
30. 1 30 This win dow lists the routines that have called other routines to reach the program s current point of IDE execution In this example the program is at the line 20 in function SearchDatabase That function was called by function FindEmployee at line 17 and that function was called by the Form_Load event handler Double click on a line to jump to the corresponding code in the pro gram s call stack This technique lets you move up the call stack to examine the code that called the routines that are running This can be a very effective technique when you need to find out what code is calling a particular routine Call Stack xi Name Language WindowsApplication3 EXE WindowsApplication3 Form1 SearchDatabase Line 20 0x5 bytes WindowsApplication3 EXE WindowsApplication3 Form1 FindEmployee Line 17 0x9 bytes Basic WindowsApplication3 EXE WindowsApplication3 Form1 Form1_Load Object sender WindowsApplication3 Form1 System Basic Figure 1 30 The Call Stack window shows which routines have called which to get to the program s current point of execution Threads This command displays the Threads window shown in Figure 1 31 A thread is a sep arate execution path that is running A multithreaded application can have several threads run ning to perform more than one task at the same time The Threads window lets you control the threads priority and suspended status The last line has the location
31. 2 with Cint 12 y Private Sub Forml_Load ByVal sender As Syst Dim i As Integer i CInt 12 j i2 End Sub ce i gt IV Expand All Previews o a J Task List gt Command Window 4 Error List A Bookmarks a Output Immediate Window Ready Ln6 Col 9 Ch9 INS 4 Figure 1 60 The error suggestion dialog proposes likely solutions to an error The following sections explain how to use snippets in your applications and how to create new snippets Using Snippets To insert a snippet right click where you want to insert the code and select Insert Snippet to make the editor display a list of snippet categories Double click a category to find the kinds of snippets that you want If you select a snippet a tooltip pops up to describe it Figure 1 61 shows the editor preparing to insert the snippet named Create a public property from the VbProgRef CodeSnippets category 61 Chapter 1 3 UsingSnippets Microsoft Visual Studio iol x File Edit View Project Build Debug Data Tools Window Community Help Taea E IE NT B 9 2 Bld 7 i TR ha ae Z SE SIO SPS Aaa _ Form1 vb Form1 vb Design x ig Form 7 JES Wectarations 7 Public Class Formi Insert Snippet VbProaRet CodeShippets gt i End Class xoqool gt l bon seainos epeq f sondos ee 101dx3 uonnjos 4 Task List gt Command Window F Error Li
32. Also notice that comments before a subroutine are not collapsed with the subroutine You can make reading collapsed code easier by placing a short descriptive comment before each routine Tooltips 56 If you hover the mouse over a variable at design time the editor displays a tooltip describing the vari able For example if you hover over an integer variable named num_actions the tooltip would display Dim num_actions As Integer If you hover over a subroutine or function call the tooltip displays information about that method For example if you hover over the RandomizeArray subroutine which takes an array of integers as a parameter the tooltip says Private Sub RandomizeArray arr As Integer At run time if you hover over a variable the tooltip displays the variable s value If the variable is com plex such as an array or structure the tooltip displays the variable s name and a plus sign If you click or hover over the plus sign the tooltip expands to show the variable s members In Figure 1 56 the mouse hovered over variable arr The editor displayed a plus sign and the text arr Length 100 When the mouse hovered over the plus sign the editor displayed the values shown in the figure Moving the mouse over the up and down arrows at the top and bottom of the list makes the values scroll
33. Cycle Clipboard Ring The clipboard ring contains the last several items that you copied into the clipboard This command copies the previous clipboard ring item to the current location By using this command repeatedly you can cycle through the items until you find the one you want IDE 8 WindowsApplication1 Microsoft Visual Studio BEE File Edit View Project Build Debug Data Tools Window Community Help ql E Undo Ctri Z E gt Debug Any CPU E Toolb K Solution Explorer Windo 2 X Polar amp Cut Ctrl x Class Formi 25 WindowsApplication1 P 3 Copy Ctrl C a My Project vate ES Form1 vb a Paste Ctr Sub Formi_Load ByVal sender Cycle Clipboard Ring Ctrl Shift V had Sub X Delete Del ass Select All Ctri A Find and Replace b Quick Find Ctrl F Ei l Y j Data Sources Solution Explorer Go To Ctr G A Quick Replace Ctri H ET a t Re Ae Properties hx Insert File As Text Find in Files Ctri Shift F a F Load Attrib ba Advanced gt Si Replace in Files Ctri Shift H orm Load Miiributes Bookmarks gt k Find Symbol Alt F12 ject a E Outlining gt Intellisense gt Hext Method Previous Method 2 Error List Jj Task List gt Command E Output jImmediate Ready Ln3 Col5 Ch5 INS 4 Figure 1 6 The Edit menu holds commands that deal with manipulating text and other objects m F
34. IDE s top or bottom edge or vertically on the IDE s left or right edge If you drop a toolbar away from the IDE s edges it becomes a floating window not docked to the IDE You can use the menu commands described earlier in this chapter to determine which toolbars are visi ble to determine what they contain and to make custom toolbars of your own Many menu commands are also available in standard toolbars For example the Debug toolbar contains many of the same commands that are in the Debug menu If you use a set of menu commands frequently you may want to display the corresponding toolbar to make using the commands easier Secondary Windows You can rearrange secondary windows such as the Toolbox and Solution Explorer almost as easily as you can rearrange toolbars Click and drag the window s title area to move it As the window moves the IDE displays little blue icons to help you dock the window as shown in Figure 1 51 This figure probably looks somewhat confusing but it s fairly easy to use The IDE displays four docking icons near the edges of the IDE You can see these icons near the edges of Figure 1 51 If you drop the window on one of these icons the window docks to the corresponding edge of the IDE When you drag the window over another window the IDE displays docking icons for the other window In Figure 1 51 these are the five icons near the mouse in the middle of the screen The four icons on the sides dock the
35. Location Lets you change the breakpoint s line number Usually it is easier to click in the margin to remove the old breakpoint and then create a new one Q Condition Lets you place a condition on the breakpoint For example you can make the breakpoint stop execution only when the variable num_employees has a value greater than 100 Q Hit Count Lets you set a hit count condition on the breakpoint For example you can make the breakpoint stop execution when it has been reached a certain number of times Q When Hit Lets you specify the action that the breakpoint performs when it triggers For example it might display a message in the Output window or run a macro To add or remove a bookmark place the cursor on a line and then click the Toggle Bookmark tool You can find this tool which looks like the blue and white bookmark icon in the Text Editor toolbar under the mouse in Figure 1 54 and at the top of the Bookmarks window Other bookmark tools let you move to the next or previous bookmark the next or previous bookmark in the current folder or the next or previous bookmark in the current document The final bookmark command clears all bookmarks Outlining 54 By default the code editor displays an outline view of code If you look at the first line in Figure 1 54 you ll see a box with a minus sign in it just to the right of the line number That box represents the out lining for the Form1 class If you click thi
36. Save My Settings on Shutdown 4 gt a Error List Jj Task List J Command Window E Output J Immediate Window Ready 2 Figure 1 8 The View menu s Property Pages command displays an application s property pages Project The Project menu shown in Figure 1 9 contains commands that let you add and remove items to and from the project Which commands are available depends on the currently selected item Following is a description of commands associated with the Project menu Q 12 New items The first several commands let you add new items to the project These com mands are fairly self explanatory For example the Add Class command adds a new class mod ule to the project Later chapters explain how to use each of these file types Add New Item The Add New Item command displays the dialog shown in Figure 1 10 The dialog lets you select from a wide assortment of items such as text files bitmap files and class modules Add Existing Item The Add Existing Item command lets you browse for a file and add it to the project Exclude From Project This command removes the selected item from the project Note that this does not delete the item s file it just removes it from the project IDE 2 WindowsApplication1 Microsoft Visual Studio BEE File Edit View Project Build Debug Data Tools Window Community Help Gls al LAMSON RoR verus Any cru R A ae 8 Add User Control
37. SinFolder 3 DevStudio6Editor SS MakeAddin 3 Utilities 3 vsDebugger 3 VSEditor 1 1S ae Gos i Figure 1 41 The Macro Explorer lets you edit run and delete macros 39 Chapter 1 Sometimes when you perform a series of programming tasks many times there are better ways to approach the problem than writing a macro For example you may be able to make your program repeat the steps inside a loop Or you may be able to extract the common code into a subroutine and then call it repeatedly rather than repeating the code many times In these cases your application doesn t need to contain a long sequence of repetitive code that may be hard to debug and maintain Macros are generally most useful when you must write similar pieces of code that cannot be easily extracted into a routine that can be shared by different parts of the application For example suppose that you need to write event handlers for several dozen Text Box controls You could record a macro while you write one of them Then you could edit the macro to make it generate the others in a loop using different control names for each event handler You could place the bulk of the event handling code in a separate subroutine that each event handler would call That would avoid the need for exten sive duplicated code In fact you could even use the AddHandler statement to make all the contr
38. ace Notice that the line numbers skip values for any collapsed lines For example the RandomizeIntegerArray subroutine is collapsed on line 39 This subroutine contains 15 lines including the Sub statement so the next visible line is labeled 54 2 EditorStuff Microsoft Visual Studio BEES File Edit View Project Build Debug Data Tools Window Community Help O e Gua s 2 Bl 9 B B P Debug Any CPU gt 5 o s oa n 2L SWE et S SIO HPGeaadads S Formt vb X g F ig Formt gt JES Deciarations gt 3 E 3 Region Randomization Functions H 23 Randomize an array of integers 8 E Private Sub RandomizelIntegeradrray o 3 S 54 amp l 55 Randomize an array of strings o rg 56 4 Private Sub RandomizeStringarray S i3 3 ES Randomize an array of doubles x Private sub RandomizeDoublearray Sel S End Region Randomization Functions s 903m uti lity Functic ng Utility Functions 93 94 End Class 95 96H Module HelperRoutines 97 Public Sub LogError 107 End Module 10 109iF Namespace ImageResources 4 gt La Error List S Task List gt _ Command Window 3 Bookmarks E Output E Immediate Window Ready Ln 1 Col 1 Ch 1 INS Z Figure 1 55 The code editor outlines namespaces classes and their methods modules and their methods and regions 55 Chapter 1
39. and The Breakpoints Window 30 A breakpoint is a line of code that you have flagged to stop execution When the program reaches that line execution stops and Visual Studio displays the code in a code editor window This lets you examine or set variables see which routine called the one containing the code and otherwise try to figure out what the code is doing The Breakpoints window lists all the breakpoints you have defined for the program This is useful for a couple of reasons First if you define a lot of breakpoints it can be hard to find them all later While other commands let you disable enable or remove all of the breakpoints at once there are times when you may need to find a particular breakpoint A common debugging strategy is to comment out broken code add new code and set a breakpoint near the modification so that you can see how the new code works When you have finished testing the code you probably want to remove either the old or new code so you don t want to blindly remove all of the program s breakpoints The Breakpoints window lists all of the breakpoints and if you double click a breakpoint in the list you can easily jump to the code that holds it The Breakpoints window also lets you modify the breakpoints you have defined Check or uncheck the boxes on the left to enable or disable breakpoints Use the dialog s toolbar to enable or disable all break points clear all breakpoints or jump to a breakpoin
40. and navigate to the Text Editor Basic General page and check the Line Numbers box IDE 8 Fibonacci Debugging Microsoft Visual Studio oix File Edit View Project Build Debug Tools Window Community Help B B Sa sa Ml 9 0 ml z F E EEA r E E EEEE gt Form1 vb Xx ai A 4g Formt gt JES Deciarations gt z A 10 Public Class Form o x oi af i S 3E Private Sub btnCalculate Click ByVal sender As System Object ByVal e As Syste Cm gt 4 Dim N As Long Long Parse txtN Text ee 5 5 Din EEEE Fibo N Fei D 6 lblResult Text result ToString 4 Fb End Sub S 9H Private Function Fibo ByVal n As Long s Long x Vv 10 ee Ss Return n S 11 Return Fibo n 1 Fibo n 2 ES 2t m Lj 13 i a 14 Private Sub Randomizeadrray Leal wile 45 z a 8 Bookmarks l X i oala gla a5 Bookmark File Location Line Humber V O Bookmark1 C VB Prog Ref JulyCTPSre Ch01 FibonacciForm1 vb 13 gt Command Window immediate Window MA Bookmarks F Error List Output Ready Ln 13 Col 1 Ch1 INS 4 Figure 1 54 The Visual Basic code editor provides many features including line numbers and icons that indicate breakpoints and bookmarks Margin Icons The gray margin to the left of the line numbers contains icons giving information about the correspond ing lines of code The following table desc
41. and Solutions Source Control Text Editor Database Tools Debugging Devine Tonls E F Window layout Tabbed documents C Multiple documents Recent files 10 items shown in Window menu 4 items shown in recently used lists V Show status bar JV Close button affects active tool window only Auto Hide button affects active tool window only Animate environment tools z d Restore File Associations mee Figure 1 47 The Options dialog lets you specify IDE options 44 IDE The following list describes the Options dialog s most important categories Q Environment Contains general IDE settings such as whether the IDE uses an Multiple Document Interface MDI or Single Document Interface SDI interface the number of items listed in the MRU lists and how often the IDE saves AutoRecover information The Fonts and Colors subsection lets you determine the colors used by the editors for different types of text For example comments are shown in green by default but you can change this color Projects and Solutions Contains the default settings for Option Explicit Option Strict and Option Compare Source Control Contains entries that deal with the source code control system for example Source Safe Text Editor Contains entries that specify the text editors features For example you can use these pages to determine whether
42. and not terribly useful Rather than reading about the IDE further you would be better off experimenting with it Spend a few hours really examining all of the menus Create a snippet with some replacement values and then insert it into your code Step through a small program and try the Immediate and Command windows While you do all this and while you re developing real applications right click on things to see what sort of context menus they provide The IDE is packed with so many tools that it is sometimes hard to find the one you want Because context menus are tied closely to the objects that you click to display them they often provide more appropriate and focused commands than the toolbars or menus After you have used the IDE for a while and are comfortable with it customize it to match your prefer ences Build custom toolbars and menus to make using your favorite tools easier When you have the tools that you use most at your fingertips you will see just how productive Visual Studio can be Once you have become familiar with the IDE you can start building applications One way to begin is to design the application s user interface the forms labels text boxes and other controls that the user sees and manipulates to control the application Chapter 2 Controls in General describes controls in gen eral terms It explains what controls are how you can add them to a form and how you can control and interact with them at desi
43. apter 1 al A A ES 33 el co He es ml Ee al 13 13 a Poono 2 v a I b G ia a soer pl Es tht Data Ready Si Ctl oe aj o e a l A to M 8 WindowsApplication1 Microsoft Visual Studio File Edit View Project Build Debug Data Tools Window Community Help Be O o B age Hk olo de s ge Form1 vb Design Ez Form1 on Tabbed Document Auto Hide Hide Auto Hide All Close All Documents Reset Window Layout 2 4 es 5 ib Solution Explorer Windo 2 x x ala cA 5 WindowsApplication1 Sa My Project E Form1 vb 1 Form1 vb Design Windows Error List ix D File Line Column Project gt Error List E Task List gt Command Output Immediate J Data Sources 3 Solution Explorer Properties lx WindowsApplication1 Project Propi Policy File Project File WindowsApplicatio Policy File The policy actions file Figure 1 48 The Window menu displays commands that control Visual Studio s windows The following list briefly describes these commands Q New Window Creates a new window displaying the contents of the current code window Q Split Splits a code window into two panes that can display different parts
44. ation Manager BES Active solution configuration Active solution platform Debug Any CPU gt Project contexts check the project configurations to build or deploy Configuration Platform CO WindowsApplication1 Debug Any CPU x Close Figure 1 19 The Configuration Manager lets you manage project builds Release configurations use more optimizations than Debug configurations so they provide smaller faster executable programs They do not include support for debugging however so you cannot debug a program compiled for release In the Active solution configuration drop down select the lt New gt entry to create a new configura tion When you select this entry Visual Studio displays the New Solution Configuration dialog shown in Figure 1 20 Enter the name you want to give the configuration select the existing configuration from which it should copy default values and click OK New Solution Configuration 21x Name Copy settings from Empty gt v IV Create new project configurations oma Figure 1 20 The New Solution Configuration dialog lets you create new configurations The Active solution configuration drop down also contains an item labeled lt Edit gt If you select this entry Visual Studio displays a dialog where you can rename or remove configurations 21 Chapter 1 Use the drop downs and check boxes in the grid to select features for the solution s pro
45. awsAnnlicatinnt Farn1 System Window 2 Close Help Figure 1 24 The QuickWatch dialog lets you examine an object s properties and optionally set a new watch on it If you double click on a property s value you can change it within the dialog If you click the Add Watch button the debugger adds the expression to the Watch window shown in Figure 1 25 You can also highlight a variable s name in the code and drag and drop it into a Watch window to create a watch very quickly Right click a watch in this window and select Delete Watch to remove it 25 Chapter 1 Hame Value Type A txtDirectory Text hg String E txtDirectory textAlign tem Windows Forms Horizontal4lignment Figure 1 25 The Watch window lets you easily track expression values Toggle Breakpoint This command toggles whether the current code line contains a breakpoint When execution reaches a line with an active breakpoint execution pauses so you can examine the code and program variables You can also toggle a line s breakpoint by clicking on the mar gin to the left of the line in the code editor In Figure 1 21 line number 4 displays a circle con taining an arrow on the left indicating that it has a breakpoint the circle and that it is the current line of execution the arrow The following line also contains a breakpoint and line 7 contains a disabled breakpoint indicated by a hollow circle in the left margin
46. bar Hover over a menu to open the menu so that you can drop the com mand in it Customize BES Toolbars Commands Categories Commands Add NET Framework Launch Condition Add Action Class Diagram Community Add Assembly Crystal Reports Add Custom Action Data Add Dialog Database Diagram Add File Launch Condition Add File Search Add File Type Add Internet Information Services Launcl Add Launch Condition xl Rearrange Commands To add a command drag the command from the Commands list and drop the command on the target toolbar or menu Figure 1 43 The Customize dialog s Commands tab lets you add commands to toolbars and menus To create a new menu select the New Menu item in the list on the left Then drag and drop the New Menu entry from the right list onto the IDE s menu area To make a command that executes a macro you have created select the Macros category in the list on the left Find the macro you want to use in the list on the right and drag it onto a toolbar or menu To remove a command from a toolbar or menu right click it and select Delete Alternatively you can click and drag the command somewhere that it cannot be placed For example you can drop it on the Customize dialog or most places in the IDE other than on a menu or toolbar code editors the Properties window the Toolbox The mouse cursor changes to a box with an X beside it when the mouse is over one of these ar
47. bar the command displays only a button Ironically a new button s default style is not Default Style When you create a new toolbar or menu command the button initially displays only text You need to use the Default Style command to make the button use this style Text Only Always makes the command display only text Text Only in Menus makes a command in a toolbar display a button and a command in a menu display text Image and Text makes the command display both an icon and text whether it is in a toolbar or a menu Finally the Begin a Group command makes the IDE insert a group separator before the button The Customize dialog s Rearrange Commands button displays a dialog that lets you rearrange the com mands in an existing menu or toolbar and change the appearance of those commands It s usually easier to just click and drag the commands on its menu or toolbar however The Customize dialog s Keyboard button displays the dialog shown in Figure 1 46 You can use this dis play to view and edit keyboard shortcuts Enter words in the Show commands containing text box to filter the commands When you click on a command the dialog displays any keyboard shortcuts associated with it To make a new shortcut click on the Press shortcut key s text box and press the keys that you want to use as a shortcut The Shortcut currently used by drop down lists any commands that already use the shortcut you entered To mak
48. bmenu lets you expand or collapse sections of code and turn outlining on and off IntelliSense The IntelliSense gives access to IntelliSense features For example its List Members command makes IntelliSense display the current object s properties methods and events View The View menu shown in Figure 1 7 contains commands that let you hide or display different windows and toolbars in the Visual Studio IDE 3 WindowsApplication1 Microsoft Visual Studio Har EG gt oeo a a X v i mg Ral A ag fe gt Ready a View Project Build Debug Data Tools Window Community Help Any CPU Designer gt 9 ie gt Res Open Ea I Xx Open With ytd t lt sisSYS Server Explorer Ctri Alt S Formi Solution Explorer Ctr Alt L ub Formi Load ByVal sender Bookmark Window Ctri K Ctrl w Class View Ctri Shift C Code Definition Window Ctri Ctrl D Object Browser Ctri Alt J Error List Ctri Ctri E Output CtrhAlt 0 Properties Window F4 Task List Ctri Ctrl T Toolbox Ctri Alt X Find Results Other Windows Toolbars Full Screen Shift Alt Enter Navigate Backward Ctr i 0 Messages Line Column Project E E fommand Output Immediate Ln3 Col5 7 amp Z Solution Explorer Windo 2 x BA e Bea fe WindowsApplication1 Sa My Project ES Form1 vb qlData Sources 3 Solution Explorer
49. can also build your own custom toolbars to hold your favorite tools Visual Studio changes the toolbars displayed to match the object you currently have selected 3 Toolbox The Toolbox contains tools appropriate for the item that you currently have selected and for the project type that you are working on In Figure 1 1 a Form Designer is selected in a Windows Forms application so the Toolbox contains tools appropriate for a Form Designer These include Windows Forms controls and components plus tools in the other Toolbox tabs Crystal Reports Data and Components plus the General tab is scrolled off the bottom of the Toolbox You can add other customized tabs to the Toolbox to hold your favorite controls and components Other project types may display other tools For example a Web proj ect would display Web controls and components instead of Windows Forms components 4 Form Designer A Form Designer lets you modify the graphical design of a form Select a control tool from the Toolbox and click and drag to place an instance of the control on the form Use the Properties window marked with the number 6 to change the new control s properties In Figure 1 1 no control is selected so the Properties window shows the form s properties 5 Solution Explorer The Solution Explorer lets you manage the files associated with the cur rent solution For example in Figure 1 1 you could select Form1 vb in the Project Explorer and the
50. cel Figure 1 34 The Breakpoint Hit Count dialog lets you make a breakpoint s activation depend on the number of times the code has reached it From the drop down list you can select the options break always break when the hit count is equal to break when the hit count is a multiple of or break when the hit count is greater than or equal to If you select any but the first option you can enter a value in the text box and the program will pause execution when the breakpoint has been reached the appropriate number of times For example if you select the option break when the hit count is a multiple of and enter 2 into the text box then execu tion will pause every other time it reaches the breakpoint Right click a breakpoint and select When Hit to display the When Breakpoint Is Hit dialog shown in Figure 1 35 This dialog lets you specify the actions that Visual Basic takes when the breakpoint is acti vated Check the Print a message box to make the program display a message in the Output window Check the Run a macro box to make the program execute a VBA macro Check the Continue execu tion box to make the program continue running without stopping 31 Chapter 1 When Breakpoint Is Hit ixi Specify what to do when the breakpoint is hit IV Print a message Function FUNCTION Thread TID STNAME You can include the value of a variable or other expression in the me
51. ceptsReturn False AcceptsTab False AccessibleDes Accessiblellam x DataBindings 4 gt The data bindings for the control Zh Error List Jj Task List gt Command Output jImmediate ua Figure 1 49 The Community menu contains commands that give access to Microsoft s Visual Basic developer community 47 Chapter 1 For other Visual Basic community resources see the community support topic in the MSDN help or visit the Web page http msdn microsoft com library en us vsintro7 html vxoriAdditionalResources ForVisualStudioDevelopers asp Also see the Visual Studio 2005 Home Page at http msdn microsoft com vs2005 default aspx Microsoft may move these pages but you should be able to find them if you search Microsoft s Web site for Additional Resources for Visual Studio Developers and Visual Studio 2005 Help The Help menu shown in Figure 1 50 displays the usual assortment of help commands You should be familiar with most of these from previous experience ia a oH ea Ot i amp ET EL ie TE ee x E Ey ii j Ready 8 WindowsApplication1 Microsoft Visual Studio File Edit View Project Build Debug Data Format Tools Window Community Aae aA O B D Debug Any CPU a R ll Gs FE oo OS e et et at EH Gl G _ Form1 vb D
52. ck undock or rearrange the toolbars and windows and change the behavior of the built in text editors change their indentation colors for different kinds of text and so forth These capabilities let you display the features you need the most and hide those that are unneces sary for a particular situation If you need to use the Properties window you can display it If you want to make room for a very wide form you can make it short and wide and move it to the bot tom of the screen If you have a collection of favorite tools and possibly some you have written yourself you can put them all in one convenient toolbar Or you can have several toolbars for working with code forms in general and database forms in particular This chapter describes the basic Visual Studio development environment as it is initially installed Because Visual Studio is so flexible your development environment may not look like the one described here After you ve moved things around a bit to suit your personal preferences your menus and toolbars may not contain the same commands described here and other windows may be in different locations or missing entirely Chapter 1 To avoid confusion you should probably not customize the IDE s basic menus and toolbars too much Removing the help commands from the Help menu and adding them to the Edit menu will only cause confusion later It s less confusing to leave the menus more or less alone Hide any toolbars
53. ct the new file s type Available Converters z4 Eg Java Language Conversion Assistant 3 0 Visual Basic 2005 Upgrade Wizard Converts a Visual Basic 6 0 project to a Visual Basic 2005 project Addto current solution Create new solution OK q Figure 1 4 The File Open Convert command displays this dialog to help you convert Visual Basic 6 applications to Visual Basic 2005 Close Project This command closes the entire project and all of the files it contains If you have a solution open this command is labeled Close Solution Save Form1 vb This command saves the currently open file in this example Form1 vb Save Form1 vb As This command lets you save the currently open file in a new file Save All This command saves all modified files Export Template This command displays the dialog shown in Figure 1 5 The Export Template Wizard lets you create project or item templates that you can use later Chapter 1 Edit Export Template Wizard 21x am Choose Template Type This wizard will allow you to export a project or project item from the current solution to a template which future projects can then be based upon Which type of template would you like to create Project template A project template will allow a user to create a new project based on your exported project A user will be able to utilize your template from the New Project dialog box for client pro
54. e the assignment click the Assign button 43 Chapter 1 Options Environment General Add intMacros Security AutoRecover Documents Find and Replace Fonts and Colors E Help Import and Export Settings International Settings Keyboard Startup Task List Web Browser Projects and Solutions Source Control Text Editor Database Tools Debugging Device Tools Apply the following additional keyboard mapping scheme Default v Reset Show commands containing Debug SetCurrentThread Debug extstatement Debug SetRadix Debug ShowNextStatement Shortcuts for selected command Ctrl Shift F 10 Global ina Remove Use new shortcut in Press shortcut keys ova Aloo Shortcut currently used by cont Figure 1 46 The Options dialog s Keyboard section lets you view and modify keyboard shortcuts Options The Tools menu s Options command displays the dialog shown in Figure 1 47 This dialog contains a huge number of pages of options that configure the Visual Studio IDE The Customize dialog s Keyboard button described in the previous section uses the same dialog with the Keyboard item selected in the list on the left Options E HA Environment General Add inMacros Security AutoRecover Documents Find and Replace Fonts and Colors Help Import and Export Settings International Settings Keyboard Startup Task List Web Browser Projects
55. eas Modifying the IDE s standard menus and toolbars can cause confusion later You may later discover that you need a command that you have removed from a menu and it may take you quite a while to find it again A better approach to modifying standard commands is to create a new custom toolbar or menu Add the commands you want to use to the new toolbar and then hide the standard toolbar that you are replacing Later you can restore the hidden standard toolbar if necessary 41 Chapter 1 42 If you right click a command in a menu or toolbar while the Customize dialog is open Visual Studio dis plays the pop up menu shown in Figure 1 44 Click the Name text box and enter a new name to change the text displayed in the menu or toolbar Reset po o Delete Hame MyMacros Modu Copy Button Image Paste Button Image Reset Button Image Edit Button Image Change Button Image gt Default Style Text Only Always Text Only in Menus Image and Text Begin a Group Figure 1 44 Right click menu and toolbar commands to change their appearances Use the Copy Button Image command to copy the button s image to the clipboard Use Paste Button Image to paste a copied image onto a button Usually you will use these two commands to copy the image from an existing button to one you are adding However the Paste Button Image command will paste any graphical image from the clipboard For example you can open a bitmap usin
56. ebug window change depending on several conditions such as the type of file you have open whether the program is running the line of code that contains the cursor and whether that line contains a breakpoint This section discusses the menu items shown in Figure 1 21 You will see other menus items under different circumstances The following list briefly describes the Debug menu s commands m m Windows This submenu s commands display other debugging related windows This sub menu is described in more detail in the following section The Debug Windows Submenu Continue This command resumes program execution The program runs until it finishes it reaches another breakpoint or you stop it Break All This command stops execution of all programs running within the debugger This may include more than one program if you are debugging more than one application at the same time This can be useful for example if two programs work closely together Stop Debugging This command halts the program s execution and ends its debugging ses sion The program stops immediately so it does not get a chance to execute any cleanup code Detach All This command detaches the debugger from any processes to which it is attached Note that this does not stop those processes Terminate All This command terminates any processes to which the debugger is attached Restart This command stops the currently running
57. ect to Database lution Explorer Windo ACLARE e WindowsApplication1 My Project Choose Toolbox Items f El Form1 vb Connect to Server Code Snippets Manager Ctrl K Ctrl B Add in Manager al r Z4 Record TemporaryMacro Ctrl Shift R ActiveX Control Test Container Save TemporaryMacro Create GUID p Pi T C t Dotfuscator Community Edition Data Sources Solution Explorer g Macro Explorer Alt F8 Error Lookup Macros IDE Alt F11 ATLIMFC Trace Tool Load Macro Project Spy lt External Tools TabSt Ti New Macro Project aj Device Emulator Manager op Import and Export Settings Text Components a Aa z ustomize i Options text associated with the control n X B Error List 2j Task List gt Command Output Immediate Ready 2 Figure 1 40 The Macros submenu contains commands for recording and executing macros Select the Macro Explorer command to display the window shown in Figure 1 41 If you right click on a macro the resulting pop up menu lets you run edit rename or delete the macro Notice the Macro Explorer s predefined Samples section which contains example macros that you can use or modify for your own use 0 ore x Macros E a MyMacros 3 Module1 a w ValidateName 3 RecordingModule J TemporaryMacro amp a Samples lt 3 AddDirAs
58. ed while building the application leaving only the source files and the final result exe and dll files Publish WindowsApplication1 This command displays the Publish Wizard shown in Figure 1 18 It can walk you through the process of making your application available for distribution on a local file file share FTP site or Web site Publish Wizard 21x Where do you want to publish the application 2 Specify the location to publish this application http Awww vb helper comVindowsApplicationt Browse You may publish the application to a web site FTP server or file path Examples Disk path c deploy myapplication File share serverimyapplication FTP server ftp ftp microsoft com myapplication Web site http www microsoft commyapplication Previous Finish Cancel Figure 1 18 The Publish Wizard helps you deploy an application Configuration Manager The Configuration Manager command displays the dialog shown in Figure 1 19 You can use this dialog to indicate the type of build you want to use for each project debug or release and the platforms you want to target for example Itanium x64 or x86 You can also use the Build check boxes shown in the figure to determine which projects get built You can use this feature to skip compilation of some projects within the solution If you find that some parts of a solution are not compiling check the Configuration Manager IDE Configur
59. erName Session ALCXMNTR EXE x86 FLEXO Rod 0 BackWWeb 137903 1396 Updates from HP Agent x86 FLEXO Rod 0 explorer exe 328 CYB Prog RefWulyCTPSrciCh01 Fibonacci x86 FLEXO Rod 0 hphmon05 exe 336 x86 FLEXO Rod 0 hpqtrald exe 1336 x86 FLEXO Rod 0 hpsysdrv exe 1948 x86 FLEXO Rod 0 jusched exe 1952 x86 FLEXO Rod 0 kbd exe 496 x86 FLEXO Rod 0 tmsg exe 716 x86 FLEXO Rod 0 mmtask exe 1084 x86 FLEXO Rod 0 mspaint exe 996 arrow bmp Paint x86 FLEXO Rod 0 msnaint exe 2124 57198 faN121_ bmn Paint XBR FLFXOWRnod n xl I Show processes from all users Show processes in all sessions Refresh Cancel Figure 1 22 The Attach to Process dialog lets you attach the debugger to running processes Exceptions HEI Break when an exception is ser unhandled Name Thrown ie C Exceptions Cancel Common Language Runtime Exceptions LI Managed Debugging Assistants Native Run Time Checks H Win32 Exceptions SES Be bbb He Find Reset All Delete Figure 1 23 The Exceptions dialog lets you determine how Visual Basic handles uncaught exceptions 24 IDE Step Into This command makes the debugger execute the current line of code If that code invokes a function subroutine or some other procedure the point of execution moves into that procedure It is not always obvious whether a line of code invokes a procedure For example a line of code that sets an object
60. esign v JO x o HowDol Ctr F1 Q Search Ctri Alt F3 Contents Ctri Alt F1 _ Index Ctri Alt F2 Sx Help Favorites ry Dynamic Help Index Results Customer Feedback Options Register Product Check for Updates 22 Technical Support About Microsoft Visual Studio i CE HX D File Line Column Project r DataBindings AcceptsReturn False AcceptsTab False AccessibleDes Accessiblellam DataBindings The data bindings for the control Figure 1 50 The Help menu contains commands that give you help Error List E Task List gt Command Output Immediate One new item in the Help menu is the How Do I command This command opens the help system and displays a page full of links to common programming topics These topics lead to a hierarchical series of categorized tutorials on various programming topics For example the Visual Basic gt Language gt Basics gt Data Types gt Data Type Summary topic describes the Visual Basic data types their storage requirements and their ranges of allowed values 48 IDE Toolbars Visual Studio s toolbars are easy to rearrange Grab the four gray dots on a toolbar s left or upper edge and drag the toolbar to its new position If you drag a toolbar to one of Visual Studio s edges it will dock there either horizontally on the
61. f you start typing a line of code the editor tries to anticipate what you will type For example if you type Me then the editor knows that you are about to use one of the current object s properties or methods IntelliSense displays a list of the properties and methods that you might be trying to select As you type more of the property or method IntelliSense scrolls to show the choices that match what you have typed In Figure 1 57 the code includes the text me Set so IntelliSense is displaying the current object s meth ods that begin with the string Set While the IntelliSense window is visible you can use the up and down arrows to scroll through the list While IntelliSense is displaying the item that you want to use you can press the Tab key to accept that item Press the Escape key to close the Intellisense window and type the rest manually 0 HoverOverVariable Debugging Microsoft Visual Studio oix File Edit View Project Build Debug Tools Window Community Help TEET Ga 9 EE z e iz iP Mt m gt SpE Hex ria H R p E pa _ Formt vb x Bee Ix E A 7 Form1 Events gt 7 Load gt a E z E Ee Ee z 16 Public Class Formi e HoverOver Variable r pase 2 Sa My Project e 3H Private Sub Formi_Load ByVal sender As System Objec E Form1 vb CS 4 Dim arr 99
62. g Microsoft Paint press Ctrl A to select the whole image and press Ctrl C to copy it to the clipboard Then you can use the Paste Button Image command to paste the image into a button Note that the buttons are 16 by 16 pixels If the image you copy is larger Visual Studio shrinks it to fit Select the Reset Button Image command to restore the button to its default image For a command tied to a macro this erases the image Select the Edit button image command to display the simple button editor shown in Figure 1 45 If you click on a pixel that is not the selected foreground color black in Figure 1 45 the editor changes the pixel to the foreground color If you hold the mouse down and drag it the editor gives the pixels you cross that color too If you click on a pixel that is already the foreground color the editor erases the pixel and any others that you drag over If you click the Change Button Image command a menu containing several dozen standard images pops out Click one to assign that image to the button A useful technique is to start with one of these images and then edit it to customize it for your command IDE Button Editor Eg Picture Figure 1 45 You can use Visual Studio s simple button editor to change a command s button The pop up menu s Default Style command makes the command use a style that depends on whether it is in a menu or toolbar In a menu the command displays a button and text In a tool
63. gn time and run time
64. hile there is some overlap between these two windows they serve two mostly different purposes The Command window can issue commands to the Visual Studio IDE Typically these are commands that appear in menus or toolbars or that could appear in menus and toolbars For example the following command uses the Debug menu s QuickWatch command to open a QuickWatch window for the vari able first_name gt Debug QuickWatch first_name IDE One particularly useful command is Tools Alias This command lists command aliases defined by the IDE For example it indicates that is the alias for Debug Print and that is the alias for Debug QuickWatch The Command window includes some IntelliSense support If you type the name of a menu for exam ple Debug or Tools IntelliSense will display the commands available within that menu While the Command window issues commands to the IDE the Immediate window executes Visual Basic statements For example suppose that you have written a subroutine named CheckPrinter Then the following statement in the Immediate window executes that subroutine CheckPrinter Executing subroutines in the Immediate window lets you quickly and easily test routines without writ ing user interface code to handle all possible situations You can call a subroutine or function passing it different parameters to see what happens If you set breakpoints within the routine the debugger will pause there Similarly you can al
65. ication1 Form1 Form1_Load Object S Figure 1 27 The Breakpoints window helps you manage breakpoints Q Output This command displays the Output window This window displays compilation results and output produced by Debug and Trace statements Q Script Explorer This command displays the Script Explorer which can help you debug script code written in VBScript or JScript Q Watch The Watch submenu contains the commands Watch 1 Watch 2 Watch 3 and Watch 4 These commands display four different watch windows When you create a watch using the 27 Chapter 1 28 Debug menu s QuickWatch command described earlier the new watch is placed in the Watch 1 window shown in Figure 1 25 You can click and drag watches from one watch window to another to make a copy of the watch in the second window You can also click on the Name col umn in the empty line at the bottom of a watch window and enter an expression to watch One useful IDE trick is to drag watch windows 2 3 and 4 onto Watch 1 so that they all become tabs on the same window Then you can easily use the tabs to group and examine four sets of watches Autos This command displays the Autos window shown in Figure 1 28 This window dis plays the values of local and global variables used in the current line of code and in the three lines before and after it x Name Value Type vi 10 Integer E SF txtDirectory Text System Window
66. ign g oor Debuaging S uiten xX ra Z 7 Form Events _ EE Detach all Autos CtrkAlt V A al 3 19 ic Class Formi Terminate All El Locals Create L 9 2 El Restart Ctrl Shift F5 Immediate CtrAlt S oF Private Sub For 5 Attach to Process GA Cal stack re Wentargs f8 5 L End Sub Exceptions Ctri Alt E l Threads CtrAIt H A 6 Lc1ass step into F1 Modules Ctr att u 7 Step Over F10 a Processes Ctrl Alt Z 3 4 Step Out Shift F11 z owe EESTE curama Show output from Debug Toggle Breakpoint F9 a4 windoweApplcation vehos gg NeW Breakpoint ER ge anre ra aaar o E Windows pplicationl vshos a Delete All Breakpoints Ctri Shift F9 aAssembly GAC_MSIL Microsoft VisualBasic om ae Uae tae Disable All Breakpoints F WindowsApplicationl vshost exe Managed Loaded C VB Prog Ref JulyCTPSrce Ch01 Windowsapplicationl WindowsApplicationl vshost exe Managed Loaded C WINDOWS assembly GAC_MSIL System Runtime Remotii uE gt Command Window Immediate Window 7 Bookmarks 4 Error List E Output Ready Ln3 Col5 Ch5 INS Z Figure 1 21 The Debug menu contains commands for debugging an application 22 IDE Effectively using these debugging techniques can make finding problems in the code much easier so you should spend some time learning how to use these tools They can mean the difference between finding a tricky error in minute hours or days The commands visible in the D
67. ind and Replace Quick Find This command displays a find dialog where you can search the project for specific text A drop down lets you indicate whether the search should include only the current document all open documents the current project or the entire solution Options let you determine such things as whether the text must match case or whole words Find and Replace Quick Replace This command displays the same dialog as the Quick except with some extra controls It includes a text box where you can specify replacement text and but tons that let you replace the currently found text or all occurrences of the text Find and Replace Find in Files This command is similar to Quick Find except that it displays its results as a list in a new window Double click on an entry in the list to view the occurrence in its file Find and Replace Replace in Files This command is similar to Quick Replace except that it dis plays its results as a list in a new window Go To This command lets you jump to a particular line number in the current file Advanced The Advanced submenu contains commands for performing more complex docu ment formatting such as converting text to upper or lowercase controlling word wrap and commenting and uncommenting code Chapter 1 Q Bookmarks The Bookmarks submenu lets you add remove and clear bookmarks and move to the next or previous bookmark Outlining The Outlining su
68. items in different colors You can change the colors used for different items by selecting the Tools menu s Options command and opening the Environment Fonts and Colors option page To avoid confusion however you should probably leave the colors alone unless you have a good reason to change them 0 EditorStuff Microsoft Visual Studio BEES File Edit View Project Build Debug Data Tools Window Community Help aly Gd 4 fm 9 7 Any CPU 5 Q ae 2 OP Gada X Formt vb z xA A Form1 Events 7 Load arr g S amp 10 Public Class Formi als E A x E 3E Private Sub Formi_Load ByVal sender As System Object ByVal e As System Eventi 4 Make an array holding the numbers 1 through 100 3 2 5 Dim numbers 99 As Integer j 6 For i As Integer 0 To numbers Length 1 ip E 7 numbers i i 8 8 Next i 9 Me SetBounds il a 10 a1lof2 SetBounds x As Integer y As Integer width As Integer height As Integer a xt x The new Syst 12 Renao EI 13 14 Display the result 15 For i s Integer 0 To numbers Length 1 16 lstNumbers Items Add numbers i 17 Next i 18 End Sub 19 20 Randomize an array of integers 2115 Private Sub Randomizeadrray ByVal arr As Integer 4 gt j Task List gt Command Window 4 Error List Bookmarks _ E Output j Immediate Window Ready Ln9 Col 22 Ch 22 INS Z Fig
69. jects For exam ple if the solution contains several projects you could flag some to compile using the Debug configura tion and others to compile using the Release configuration If you then rebuilt the solution you would be able to debug some of the projects but not all of them This approach may be useful if you want to give some of the projects to customers in their release versions while you keep working on others If you uncheck a project s Build box that project is excluded from any builds If you build the solution it is not compiled Visual Studio writes its results into the Output window and counts the skipped project in its final summary line The following line shows an example where one project was compiled and one skipped Build 1 succeeded or up to date 0 failed 1 skipped Debug The Debug menu shown in Figure 1 21 contains commands that help you debug a program These commands help you run the program in the debugger move through the code set and clear breakpoints and generally follow the code s execution to see what it s doing and hopefully what it s doing wrong 8 WindowsApplication1 Debugging Microsoft Visual Studio File Edit View Project Build Debug Tools Window Community Help eerie P i gt n ajo Slee Output R TEE T ll Script Explorer Ctrl Alt Il xl Form1 vb Form1 vb Des
70. jects and from the New Website dialog box for websites C ltem template An item template will allow a user to add your item to one of their existing project Your template will be available to the user from the Add New Item dialog box From which project would you like to create a template WindowsApplication1 What type of project or item does this template create z Einist Cancel Figure 1 5 The File Export Template command displays this dialog to help you create project or items templates that you can easily use in other projects Page Setup and Print The Page Setup and Print commands let you configure printer settings and print the current document These commands are enabled only when it makes sense to print the current file For example if you are viewing a source code file or a configuration file which is XML text you can use these commands If you are viewing bitmap or a form in design mode these commands are disabled Recent Files and Recent Projects The Recent Files and Recent Projects submenus let you quickly reopen files projects and solutions that you have opened recently The Edit menu shown in Figure 1 6 contains commands that deal with manipulating text and other objects These include standard commands such as the Undo Redo Copy Cut and Paste commands that you ve seen in other Windows applications Following is a description of other commands associated with the Edit menu Q
71. k windows Sometimes the IDE is so cluttered with windows that it s hard to figure out exactly where the window will be dropped It s usually fairly easy to just move the mouse around a bit and watch the grayed rect angle to see what s happening The windows in the Microsoft Document Explorer used by the MSDN Library and other external help files provides the same arranging and docking tools for managing its subwindows such as Index Contents Help Favorites Index Results and Search Results Toolbox The Toolbox window displays a series of sections containing tools for the currently active document These tools are grouped into sections called tabs although they don t look much like the tabs on most doc uments In Figure 1 52 the Toolbox displays tools for the form designer grouped into the All Windows Forms Common Controls Containers Menus amp Toolbars Data Components Printing Dialogs and General tabs In this figure the Toolbox was enlarged greatly to show most of its contents Most develop ers keep this window much smaller and docked on the left edge of the IDE 50 Toolbox R hk R hk R Ly h Figure 1 52 The Toolbox window can display tools by name or icon You can customize the Toolbox by right clicking on it and selecting one of the commands in the context menu The following list briefly describes these commands Q Q List View Toggles the current tab to display tools either as a list
72. ll the available services j r BAG URL X J co Web services found at this URL Start Browsing for Web Services 4dd Reference z Cancel Figure 1 12 Use the Add Web Reference dialog to add references to Web Services 15 Chapter 1 In Figure 1 13 the Toolbox Solution Explorer Properties window Errors List and other secondary win dows have been hidden to make more room for the large Properties page You can see these other win dows icons lurking along the left right and bottom edges of the figure Click the tabs on the left to view and modify different types of application settings You can leave many of the property values alone and many are set in other ways For example by default the Assembly name and Root namespace values shown in Figure 1 13 are set to the name of the project when you first create it There are three properties on the Compile tab shown in Figure 1 14 that deserve special mention First Option Explicit determines whether Visual Basic requires you to declare all variables before using them Leaving this option turned off can sometimes lead to subtle bugs For example the following code is intended to print a list of even numbers between 0 and 10 Unfortunately a typographical error makes the Debug WriteLine statement print the value of the variable j not i Because j is never initialized the code prints out a bunch of blank values If you set Option Stric
73. ls menu s most useful commands m m Attach to Process This command displays the dialog shown in Figure 1 22 to let you attach the debugger to a running process Select the process to which you want to attach and click Attach Connect to Device This command lets you connect to a physical device or emulator such as Pocket PC or Smartphone devices or emulators You can use the devices and emulators to test software you are writing for devices other than the Windows platform where you are building the application Connect to Database This command displays the Connection Properties dialog where you can define a database connection The connection is added to the Server Explorer window You can later use the connection to define data adapters and other objects that use a database connection Code Snippets Manager This command displays the Code Snippets Manager which you can use to add and remove code snippets Choose Toolbox Items This command displays a dialog that lets you select the tools displayed in the Toolbox For instance by default the 0leDbDataAdapater and OleDbConnection com ponents are not included in the Toolbox You can use this command to add them if you will use them frequently Add in Manager This command displays the Add in Manager which lists the add in projects registered on the computer You can use the Add in Manager to enable or disable these add ins Macros The Macros sub
74. lutter IDE brings additional chances for confusion It will be less confusing to shrink the Visual Basic IDE to an icon and open the file using an external editor such as Word or WordPad If you won t use a file very often with the project don t add it to the project IDE Overview Figure 1 1 shows the IDE immediately after starting a new project The IDE is extremely configurable so it may not look much like Figure 1 1 after you have rearranged things to your own liking If you don t have a reason to modify the IDE s basic arrangement you should probably leave it alone Then when you read a magazine article that tells you to use the Project menu s Add Reference com mand the command will be where it should be Using the standard IDE layout also reduces confusion when you need to consult with another developer It s a lot easier to share tips about using the Format menu if you haven t removed that menu from the IDE 8d WindowsApplication1 Microsoft Visual Studio BEES File Edit View Project Build Debug Data Format Tools Window Community Help aly il GF el g l l 5 gt Debug Any CPU 2 P 2 S m A l ales a A ry S St i TEF y Form1 vb Design yx Solution Explore 5 indo v 2 X fa 2 crnina eal WindowsApplication1 lt a My Project E Form1 vb 9 a S g i aah pl Data Sources Solution Explorer aS Properties 6 Ax
75. menu contains commands that help you create edit and execute macros See the section Macros later in this chapter for details ActiveX Control Test Container This command displays the ActiveX Control Test Container which lets you test and debug ActiveX controls You can use it to change the control s proper ties call its methods and raise its events Create GUID This command displays the Create GUID dialog shown in Figure 1 39 to let you create a new globally unique identifier GUID pronounced to rhyme with squid Select the GUID format that you need and click New GUID to generate a new GUID Click Copy to copy the result to the clipboard Dotfuscater Community Edition This command launches the displays the Dotfuscater Community Edition a tool that you can use to make the intermediate language IL code generated by Visual Basic more obscure and harder to reverse engineer Error Lookup This command displays a small dialog where you can enter an error code and see a description of the error ATL MEFC Trace Tool If you are building Active Template Library ATL or Microsoft Foundation Classes MFC projects this command displays a tool that lets you view debug trace messages Spy This command launches the Spy tool which lets you view the messages sent to the application External Tools This command displays a dialog that lets you add and remove commands from the Tools menu For example
76. n click the View Code button the icon third from the right at the top of the Solution Explorer to open the form s code editor You can also right click an object in the Solution Explorer to get a list of appropriate commands for that object 6 Properties The Properties window lets you change an object s properties at design time When you select an object in a form designer or in the Solution Explorer the Properties window displays that object s properties To change a property s value simply click the property and enter the new value 7 Error List The Error List window shows errors and warnings in the current project For example if a variable is used and not declared this list will say so If you look at the bottom of Figure 1 1 you ll notice that the Toolbox and Error List windows each have a series of tabs The Toolbox s other tab displays the Document Outline window which displays an out line view of a project showing its forms and components The Error List window s Output tab shows output printed by the application Usually an application interacts with the user through its forms and dialogs but it can display information here to help you debug the code The Output window also shows informational messages generated by the IDE For IDE example when you compile an application the IDE sends messages here to tell you what it is doing and whether it succeeded The following sections describe the major piece
77. of names or a series of icons Show All Shows or hides less commonly used tool tabs such as XML Schema Dialog Editor DataSet Login WebParts Report Items Device Controls and many others Choose Items displays the dialog shown in Figure 1 53 Use the NET Framework Components tab to select NET tools and use the COM Components tab to select COM tools Click the Browse button to locate tools that are not in either list Sort Items Alphabetically Sorts the items within a Toolbox tab alphabetically Reset Toolbox Restores the Toolbox to a default configuration This removes any items you may have added by using the Choose Items command Add Tab Creates a new tab where you can place your favorite tools You can drag tools from one tab to another Hold down the Ctrl key while dragging to add a copy of the tool to the new tab without removing it from the old tab 51 Chapter 1 O Delete Tab Deletes a tab Q Rename Tab Lets you rename a tab Q Move Up Move Down Moves a tab up or down in the Toolbox You can also click and drag the tabs to new positions Choose Toolbox Items BE Mame tamespace Assembly llame Directory AccessDataSource System Web ULWebControls System Web 2 0 0 0 Global A O abopc Microsoft VisualBasic Com Microsoft VisualBasi Global A O ADODCArray Microsoft VisualBasic Com Microsoft VisualBasi Global A AdRotator System Web ULMobileContr System Web
78. olbar contains many of the same commands that are in the Debug menu If you use a set of menu commands fre quently you may want to display the corresponding toolbar to make using the commands easier Visual Studio also provides many commands through context menus For example if you right click on a project in the Solution Explorer the context menu includes an Add Reference command that displays the Add Reference dialog just as if you had invoked Project Add Reference Often it is easier to find a command by right clicking an object related to whatever you want to do than it is to wander through the menus The following sections describe the general layout of the standard menus You might want to open the menus in Visual Studio as you read these sections so you can follow along Note that Visual Studio displays different menus and different commands in menus depending on what editor is active For example when you have a form open in the form editor Visual Studio displays a Format menu that you can use to arrange controls on the form When you have a code editor open the Format menu is hidden because it doesn t apply to code File The File menu shown in Figure 1 2 contains commands that deal with creating opening saving and closing projects and project files Chapter 1 2 WindowsApplication1 Microsoft Visual Studio BEES File Edit View Project
79. ols The Tools menu shown in Figure 1 38 contains miscellaneous tools that do not fit particularly well in the other menus It also contains a few duplicates of commands in other menus and commands that 36 modify the IDE itself 8 WindowsApplication1 Microsoft Visual Studio File Edit View Project Build Debug Data Format a G oH s43aB 9 C 2 8 it i amp SI ult al 283 GE one x T t t Toolbox X _ Form1 vb Design EA t qL a N A o Eo Ba al E k G e Ew i D File l y i ee amp 4 Ea wie oe Tools a 6 Window Community Help Bm x Connect to Device Connect to Database Connect to Server Code Snippets Manager Ctri K Ctrl B Choose Toolbox Items Add in Manager Macros ActiveX Control Test Container Create GUID Dotfuscator Community Edition Error Lookup ATLMFC Trace Tool Spy External Tools Device Emulator Manager Import and Export Settings Customize Options The text associated with the control Ri lorer Windo 2 x HABA sApplication1 Project m1 vb ces Solution Explorer ME Enabl True a 96 20 True Figure 1 38 The Tools menu contains miscellaneous commands and commands that modify the IDE IDE The following list describes the Too
80. ols use the same event handler Then you wouldn t even need to write all of the separate event handlers Macros are also useful for manipulating the IDE and performing IDE related tasks For example you can write macros to show and hide your favorite toolbars or to change whether the current file is opened read only Customize 40 The Tools menu s Customize command displays the dialog shown in Figure 1 42 On the Toolbars tab check the boxes next to the toolbars that you want to be visible Click New to create a new toolbar where you can add your favorite tools You can leave the toolbar floating or drag it to the edge of the IDE and dock it If you drag it to the top it joins the other toolbars Customize 21x Toolbars Commands Toolbars HTML Source Editing m Image Editor Y Layout 7 Menu Bar Rename L Query Designer C Recorder Delete Report Borders C Report Formatting iene EER L Table Designer C Text Editor C View Designer T XML Data x Use large icons V Show ScreenTips on toolbars I Show shortcut keys in ScreenTips Keyboard Figure 1 42 The Customize dialog s Toolbar tab lets you determine which toolbars are visible IDE Click the Commands tab to see a list of categories as shown in Figure 1 43 Select a category on the left Then click and drag a command from the list on the right If you drop the command on a toolbar the command is added to the tool
81. on Wizard which walks you through the process of adding a data source to the project Q Add Query This command is available when you are designing a form and have selected a data bound control such as a DataGridView or bound TextBox This command opens a dialog where you can specify a query to add to the form This places a ToolStrip on the form contain ing TooStripButton that populates the bound control by executing the query Format The Format menu shown in Figure 1 37 contains commands that arrange controls on a form The fol lowing list describes the Format menu s submenus 34 2 WindowsApplication1 Microsoft Visual Studio BEE File Edit View Project Build Debug Data Format Tools Window Community Help ITET TES r st e A ST oth alt 52 G1 a oi Meke Sme Size 24 Centers 5 Toolbox Ix Form1 vb Design Horizontal Spacing gt S Rights Solution Explorer Windo X Wear a Vertical Spacing gt Tit Tops al 4 a ELE Eo 7 Formi Center in Form gt Middles 25 WindowsApplication1 m st HE BRET FS i i He fi i i zal Onder gt ut Bottoms Sa My Project 3 i EE Form1 vb ial ig LS 1d Lock Controls BP to Grid r m A O E Se ee i es a 7 0 b E E ee E n m R to Data Sources Solution Explorer m B Properties lx a J al Error List lx Common Controls z a _ 0 Warnings i 0 Messages z Za
82. or File El Icon File a Application Configuration File 2 Transactional Component B Installer Class B Windows Service A blank Windows Form Name Form2 vb emea Figure 1 10 The Project menu s Add New Item command lets you add a wide variety of items to the project 13 Chapter 1 14 Q Show All Files The Show All Files command makes Solution Explorer list files that are nor mally hidden These include resource files corresponding to forms hidden partial classes such as designer generated form code resource files and files in the obj and bin directories that are automatically created by Visual Studio when it compiles your program Normally you don t need to work with these files so they are hidden Select this command to show them Select the command again to hide them Add Reference The Add Reference command displays the dialog shown in Figure 1 11 Select the category of the external object class or library that you want to find For a NET component select the NET tab For a Component Object Model COM component such as an ActiveX library or control built using Visual Basic 6 select the COM tab Select the Projects tab to add a reference to another Visual Studio project Click the Browse tab to manually locate the file you want to reference Add Reference 21x NET com Projects Browse Recent 7 0 3300 0 AspNetMMCExt 2 0 0 0 CppCodeProvider 6 0 0 0 CrystalDecisions CrystalRepo
83. pet pop ups 64 IDE Code Snippets Manager 21x Language Location C Program Files Microsoft Visual Studio 8 VB Snippets 033tapplication i Application Compiling Resources anc a Jj collections and arrays LI common code patterns Jj Connectivity and Networking LI Crystal Reports jj Data Designer features and ADO NET LJ Data Types defined by Visual Basic LJ File system Processing Drives Folder Lj Math LI My Code Snippets LI Security LI Windows Forms Applications LI Windows Operating System v b Add Remove Import Search Online Cancel Figure 1 63 The Code Snippets Manager lets you add and remove snippet directories A H 0 4 The Code Editor at Run Time The code editor behaves slightly differently at run time and design time Many of its design time fea tures still work Breakpoints bookmarks IntelliSense and snippets still work At run time the editor adds new tools for controlling the program s execution Right click on a value and select Add Watch or QuickWatch to examine and monitor the value Use the Stop Into Step Over and Step Out commands on the Debug menu or toolbar to make the program walk through the code Right click on a statement and select Show Next Statement to move the cursor to the next statement that the program will execute Select Run To Cursor to make the program continue running until it reaches
84. process and restarts the startup project Attach to Process This command displays the dialog shown in Figure 1 22 to let you attach the debugger to a running process Select the process to which you want to attach and click Attach Exceptions This command displays the dialog shown in Figure 1 23 If you check a Thrown box the debugger stops whenever the selected type of error occurs If you check a User unhandled box the debugger stops when the selected type of error occurs and the program does not catch it with error handling code For example suppose that your code calls a sub routine that causes a divide by zero exception Use the dialog to select Common Language Runtime Exceptions System System DivideByZeroException use the Find button to find it quickly If you check the Thrown box the debugger stops in the subroutine when the divide by zero exception occurs even if the code is contained in an error handler If you check the User unhandled box the debugger stops only if no error handler is active when the error occurs 23 Chapter 1 Attach to Process 21x Transport Detaut v Qualifier FLEXO bd Browse r Transport Information The default transport lets you select processes on this computer or a remote computer running the Microsoft Visual Studio Remote Debugging Monitor MSYSMON EXE Attach to Automatic Native code Select r Available Processes Process Title Type Us
85. ribes the icons on lines 4 through 11 Line 4 5 6 7 10 11 Icon Yellow arrow Red circle Hollow red circle Red circle with plus sign Red diamond Blue and white rectangle Meaning Indicates that execution is paused at this line Indicates a breakpoint Indicates a disabled breakpoint Indicates a breakpoint with a condition or hit count test Indicates a breakpoint that executes an action when reached Indicates a bookmark 53 Chapter 1 These icons can combine to indicate more than one condition For example line 12 shows a blue and white rectangle to indicate a bookmark a hollow red diamond to indicate a disabled breakpoint that performs an action and a plus sign to indicate that the breakpoint has a condition or hit count test Note that the editor marks some of these lines in other ways than just an icon It highlights the currently executing line with a yellow background It marks lines that hold enabled breakpoints with white text on a red background To add or remove a simple breakpoint click in the gray margin To make a more complex breakpoint click in the margin to create a simple breakpoint Then right click the breakpoint icon and select one of the context menu s commands The following list describes these commands Q Delete Breakpoint Removes the breakpoint Q Disable Breakpoint Disables the breakpoint When the breakpoint is disabled this command changes to Enable Breakpoint Q
86. rts Engine 10 2 360 CrystalDecisions ReportSource 10 2 360 CrystalDecisions Shared 10 2 360 CrystalDecisions Web 10 2 360 CrystalDecisions Windows Forms 10 2 360 cscompmgd 6 0 0 0 CustomMarshalers 2 0 0 0 EnvDTE 8 0 0 0 envdte 8 0 0 0 EnvDTE80 8 0 0 0 Figure 1 11 Use the Add Reference dialog to add references to external libraries Scroll through the list of references until you find the one you want and select it You can use Shift Click and Ctrl Click to select more than one library at the same time When you have made your selections click OK to add the references to the project After you have added a ref erence to the project your code can refer to the reference s public objects For example if the file IDE MyMathLibrary d11 defines a class named MathTool1s and that class defines a public function Fibonacci a project with a reference to this DLL could use the following code Dim math_tools As New MyMathLibrary MathTools MsgBox Fib 5 amp math_tools Fibonacci 5 m Add Web Reference The Add Web Reference command displays the dialog shown in Figure 1 12 You can use this dialog to find Web Services and add references to them so your project can invoke them across the Internet WindowsApplication1 Properties This command displays the application s property pages shown in Figure 1 13 Add Web Reference 21x Navigate to a web service URL and click Add Reference to add a
87. s Forms TextBox A txtDirectory Text String x 150 0 Single 9 y 0 0 Single Figure 1 28 The Autos window displays the variables used in the current code statement and the three statements before and the three after Locals This command displays the Locals window shown in Figure 1 29 The Locals window displays the values of variables defined in the local context To change a value click on it and enter the new value Click the plus and minus signs to the left of a value to expand or collapse it For example the Me entry shown in Figure 1 29 is an object with lots of properties that have their own values Click the plus sign to expand the object s entry and view its properties Those properties may also be objects so you may be able to expand them further Hame Value Type ga eme wWindowsApplication1 Form1 WindowsApplication1 Form1 A ge System EventArgs System EventArgs vi 10 Integer vi 10 Integer 4 sender wWindowsApplication1 Form1 Object yx 150 0 Single 9 y 0 0 Single Figure 1 29 The Locals window displays the values of variables defined in the local context Immediate This command displays the Immediate window where you can type and execute ad hoc Visual Basic statements The section The Command and Immediate Windows later in this chapter describes this window in a bit more detail Call Stack This command displays the Call Stack window shown in Figure
88. s These are not included in the compiled code but it is useful to associate them with the project When you open the project Visual Studio lists those documents along with the program files If you double click one of these documents Visual Studio opens the file using an appropriate application For example if you double click a file with a doc extension Visual Studio normally opens it with Microsoft Word To associate one of these files with a project or solution right click the project in the Solution Explorer more on the Solution Explorer shortly Select the Add command s Add New Item entry and use the resulting dialog to select the file you want to add Often a Visual Basic solution contains a single project If you just want to build a small executable pro gram you probably don t need to include other programming projects in the solution Another common scenario is to place Visual Basic code in one project and to place documentation such as project specifications and progress reports in another project within the same solution This keeps the documentation handy whenever you are working on the application but keeps it separate enough that it doesn t clutter the Visual Studio windows when you want to work with the code While you can add any file to a project or solution it s not a good idea to load dozens of unrelated files While you may sometimes want to refer to an unrelated file while working on a project the extra c
89. s String s eror EZES This works s Hello METES nals ine abibsy If you set Option Strict to On the IDE warns you that the two data types are incompatible so you can easily resolve the problem while you are writing the code You can still use conversion functions such as CInt Int and Integer Parse to convert a string into an Integer but you must take explicit action to do so This makes you think about the code and reduces the chances that the conversion is just an acci dent This also helps you use the correct data types and avoid unnecessary conversions that may make your program slower 17 Chapter 1 To avoid confusion and long debugging sessions you should always set Option Explicit On and Option Strict On You can turn them on for a project using the project page To make them on by default for new projects open the Tools menu and select Options Open the Projects and Solutions folder select the VB Defaults page and turn the options on as shown in Figure 1 15 Options zixl General Default project settings Add indMacros Security AutoRecover Option Explicit On v Documents Option Strict on x Find and Replace Fonts and Colors Option Compare Binary gt E Help Import and Export Settings International Settings Keyboard Startup Task List Web Browser El Projects and Solutions General Build and Run VB Defaults C Directories VC Project Settings E Source Control zl me
90. s box the editor collapses the class s definition and displays it as a box containing a plus sign If you then click the new box the editor expands the class s definition again The gray line leading down from the box leads to other code items that are outlined and that you can expand or collapse to give you the least cluttered view of the code you want to examine Near the bot tom of Figure 1 54 you can see that the RandomizeArray subroutine has been collapsed The ellipsis and rectangle around the routine name provided an extra indication that this code is hidden IDE The editor automatically creates outlining entries for namespaces classes and their methods and mod ules and their methods You can also use the Region statement to group a section of code for outlining For example you can place several related subroutines in a region so you can collapse and expand the routines as a group Figure 1 55 shows more examples of outlining Line 37 begins a region named Randomization Functions that contains three collapsed subroutines Notice that the corresponding End Region statement includes a comment giving the region s name This is not required but it makes the code easier to understand when you are looking at the end of a region Line 90 contains a collapsed region named Utility Functions Line 96 starts a module named HelperRoutines that contains one collapsed subroutine Finally Line 109 holds the collapsed ImageResources namesp
91. s of the IDE in more detail Menus The IDE s menus contain standard Visual Studio commands These are generally commands that manip ulate the project and the modules it contains Some of the concepts are similar to those used by any Windows application File New File Save Help Contents but many of the details are specific to Visual Studio programming so the following sections describe them in a bit more detail The menus are customizable so you can add remove and rearrange the menus and the items they con tain This can be quite confusing however if you later need to find a command that you have removed from its normal place in the menus Some developers place extra commands in standard menus particu larly the Tools menu but it is generally risky to remove standard menu items Usually it is safest to leave the standard menus alone and make custom toolbars to hold customizations For more information on this see the section Customize later in this chapter Many of the menus most useful commands are also available in other ways Many provide shortcut key combinations that make using them quick and easy For example Ctrl N opens the New Project dialog just as if you had selected the File New Project menu command If you find yourself using the same command very frequently look in the menu and learn its keyboard shortcut to save time later Many menu commands are also available in standard toolbars For example the Debug to
92. s property may be simply setting a value or invoking a property procedure Step Over This command makes the debugger execute the current line of code If that code invokes a function subroutine or some other procedure the debugger calls that routine but does not step into it so you don t need to step through its code However if a breakpoint is set inside that routine execution will stop at the breakpoint Step Out This command makes the debugger run until it leaves the routine it is currently executing Execution pauses when the program reaches the line of code that called this routine QuickWatch This command displays a dialog that gives information about the selected code object Figure 1 24 shows the dialog displaying information about a TextBox control named txtDirectory If you look closely you can see some of the control s properties including TabIndex TabStop Tag and Text QuickWatch BEES txtDirectory TextLength X Add Watch Value Hame Value Type E TabIndex a Integer m ef TabStop True Boolean ef Tag Nothing Object m A Text a String m A Text e String amp text Nothing String r text lign Left 0 System Window p E TextAlign Left 0 System Window r textBoxFlags Nothing System Collectic r e M gy threadCallbackMessage a Integer am Top 16 Integer E Sr TopLevelControl WindowsApplication1 Form1 System Window FLSA TonlevelControlinternal Wind
93. so set the values of global variables and then call routines that use them The follow ing Immediate window commands set the value of the m_PrinterName variable and then calls the CheckPrinter subroutine m_PrinterName LP_REMOTE CheckPrinter You can execute much more complex statements in the Command and Immediate windows For exam ple suppose that your program uses the following statement to open a file for reading Dim fs As FileStream File OpenRead _ C Program Files Customer Orders Summary amp _ datetime Now ToString yymmdd amp dat Suppose that the program is failing because some other part of the program is deleting the file You can type the following code all on one line into the Immediate window to see if the file exists As you step through different pieces of the code you can use this statement again to see if the file has been deleted System IO File Exists C Program Files Customer Orders Summary amp _ DateTime Now ToString yymmdd amp dat The window evaluates the complicated string expression to produce a file name It then uses the System IO File Exists command to determine whether the file exists and displays True or False accordingly Data The Data menu shown in Figure 1 36 contains commands that deal with data and data sources Some of the commands in this menu are only visible and enabled if you are designing a form and that form con tains the proper data objects
94. ssage by placing it in curly braces such as The value of x is x To insert a curly brace use To insert a backslash use W The following special keywords will be replaced with their current values ADDRESS Current Instruction SCALLER Previous Function Name CALLSTACK Call Stack SFUNCTION Current Function Name PID Process Id SPNAME Process Name TID Thread Id STNAME Thread Name JV Run a macro IV Continue execution Cancel Figure 1 35 The When Breakpoint Is Hit Condition dialog lets you determine what actions Visual Basic takes when the breakpoint is activated The Command and Immediate Windows 32 The Command and Immediate windows both allow you to execute commands while the program is stopped in the debugger One of the more useful commands in each of these windows is the Debug Print statement For example the command Debug Print x displays the value of the variable x You can use a question mark as an abbreviation for Debug Print The following text shows how the command might appear in the Command window Here the gt symbol is the command prompt provided by the window and 123 is the result the value of variable x In the Immediate window the statement would not include the gt character PX 128 The command gt immed tells the Command window to open the Immediate window Conversely the command gt cmd tells the Immediate window to open the Command window W
95. st 3 Bookmarks E Output Immediate Window Ready Ln2 Col 1 Ch1 INS 4 Figure 1 61 When you select a code snippet a pop up describes it Double click on the snippet to insert it into your code The snippet may include values that you should replace in your code These replacement values are highlighted with a light green background and the first value is initially selected If you hover the mouse over one of these values a tooltip appears to describe the value You can use the Tab key to jump between replacement values Figure 1 62 shows the inserted code for this example The text An Integer Property is highlighted and selected Other selected text includes Integer 0 and MyProperty The mouse is hovering over the value An Integer Property so the tooltip explains that value s purpose 62 IDE 2 UsingSnippets Microsoft Visual Studio BEES File Edit View Project Build Debug Data Tools Window Community Help D agaa AaB O EE gt debug AnycPu L i GB how j E S S O PR eRe IL Form1 vb Form1 vb Design Xx F 3 3g Formt gt ES Deciarations gt g H 10 Public Class Form 2 m F j S cl 4 mein Integer property 3 5 PrThe property s description PS Integer 0 T 3 6H Public Property MyProperty As Integer i a 7 Get EA 8 Return m MyProperty 9i p End Get E 106 Set ByVal value As Integer 8 11 m MyProperty value 12
96. t s source code Right click a breakpoint and select Condition to display the dialog shown in Figure 1 33 By default a breakpoint stops execution whenever it is reached You can use this dialog to add an additional condi tion that determines whether the breakpoint activates when reached In this example the breakpoint IDE stops execution only if the expression i j And i gt 20 is True when the code reaches the break point Note that specifying a breakpoint condition can slow execution considerably Breakpoint Condition 21x When the breakpoint location is reached the expression is evaluated and the breakpoint is hit only if the expression is true or has changed IV Condition i j And i gt 20 Istrue C Has changed cren Figure 1 33 The Breakpoint Condition dialog lets you specify a condition that determines whether Visual Studio stops at the breakpoint Right click a breakpoint and select Hit Count to display the Breakpoint Hit Count dialog shown in Figure 1 34 Each time the code reaches a breakpoint it increments the breakpoint s hit count You can use this dialog to make the breakpoint s activation depend on the hit count s value Breakpoint Hit Count 21x A breakpoint is hit when the breakpoint location is reached and the condition is satisfied The hit count is the number of times the breakpoint has been hit Ahen the breakpoint is hit Current hit count 0 Reset Can
97. t configuration Q Form1 vb The bottom part of the Window menu lists the open documents In Figure 1 48 it lists Form1 vb in the code editor and Form1 vb Design in the Form Designer Design mode The code editor entry is checked because it is the currently active document Q Windows If you have too many open documents to display in the Window menu select this command to see a list of windows in a dialog This dialog lets you switch to another document close one or more documents or save documents By using Ctrl Click and Shift Click you can select more than one document and quickly close them Community The Community menu shown in Figure 1 49 contains commands that can help you connect with the Visual Basic programming community These commands lead to various Microsoft Web pages where you can ask questions send feedback search for examples find snippets and so forth 2 WindowsApplication1 Microsoft Visual Studio BEES File Edit View Project Build Debug Data Format Tools Window Community Help Dagdas amI of ee eee P ws 2 alei HE ope We olo h a dt Bt ej Send Feedback Check Question Status a be _ Form1 vb Design Developer Center W Form1 Codezone Community Community Search gt aan agram1 cd CE Form1 vb ylData Sources Solution Explorer Properties lx X Error List lx BYE D File Line Column Project DataBindings a Ac
98. t to On the compiler complains that the variable j is not declared and the problem is easy to fix infowe ak dl Ute i100 If i Mod 2 0 Then Debug WriteLine j Next i 8 WindowsApplication1 Microsoft Visual Studio BEES File Edit View Project Build Debug Data Tools Window Community Help ay i di a z dlv gt Debug Any CPU gt WindowsApplication1 Formi wby Form1 vb Design x ea 5 S S Application i lo iR Configuration N A X Platform N A A e 3 le Compile 8 3 Debug Assembly name Root namespace pa WindowsApplication indowsApplication1 WindowsApplicationt References 2 Application type Icon E m Resources windows Application gt Defautt Icon gt E E E Settings Startup form S For m1 fiad Assembly Information Signing ig E y E IV Enable application framework e Security E jc Publish Windows application framework properties cm JV Enable XP visual styles Make single instance application JV Save My Settings on Shutdown hd 4 gt i Error List 2j Task List gt Command Window Output Immediate Window Ready Figure 1 13 Property pages let you set a project s properties 16 IDE 2 WindowsApplication1 Microsoft Visual Studio BEES File Edit View Project Build Debug Data Tools Window Community Help D a g ag El
99. the controls you have selected It contains the commands Make Equal Increase Decrease and Remove For example if you have selected three controls the Make Equal command makes the spacing between the first two the same as the spacing between the second two This can be handy for making columns that line up nicely Vertical Spacing This submenu contains the same commands as the Horizontal Spacing sub menu except it adjusts the controls vertical spacing rather than their horizontal spacing 35 Chapter 1 Q Center in Form This submenu contains commands that center the selected controls on the form It contains the commands Horizontally and Vertically Note that the selected controls are centered as a group they are not centered individually on top of each other Order This submenu contains the commands Bring to Front and Send to Back which move the selected controls to the top or bottom of the stacking order Lock Controls This command locks all of the controls on the form so that they cannot be moved or resized by clicking and dragging You can still move and resize the controls by chang ing their Location and Size properties in the Properties window Invoking this command again unlocks the controls Locking the controls can be useful if you have spent a long time position ing them precisely After they are locked you can work on the controls without fear of acciden tally messing up your careful design To
100. the files you have open The command adds a small box to the title bar containing a Full Screen button that you can click to end full screen mode Navigate Backward Navigate Forward These commands let you move back and forth through the last several locations you visited Next Task Previous Task These commands move through the items in the Task List Property Pages This command displays the current item s property pages For example if you select an application in Solution Explorer this command displays the application s property pages similar to those shown in Figure 1 8 11 Chapter 1 2 WindowsApplication1 Microsoft Visual Studio BEES File Edit View Project Build Debug Data Tools Window Community Help al iil oo el wl amp x di E gt Debug Any CPU g gt WindowsApplication1 Form1 vb Form1 vb Design x A N A Q a Application Ej IR Configuration N A v Platform NWA 7 IE Compile z S Debug Assembly name Root namespace 2 WindowsApplication1 WindowsApplication1 i References Application type Icon S Resources windows Application gt Defautt Icon gt i s S Settings Startup form 8 For m1 gt Assembly Information ra Signing E Y a JV Enable application framework 3 Security Fi 4 Publish Windows application framework properties vE IV Enable XP visual styles Make single instance application V
101. ure 1 58 IntelliSense displays information about a method s parameters IDE The following table describes some of the default colors that the code editor uses to highlight different code elements Item Comment Compiler error Other error Highlighting Green text Underlined with a wavy blue underline Underlined with a wavy green underline Keyword Blue text Preprocessor keyword Blue text Read only region Light gray background Stale code Purple text User types Navy text User types delegates Navy text User types enums Teal text User types interfaces Navy text User types value types Teal text Warning Underlined with a wavy purple underline A few other items that may be worth changing have white backgrounds and black text by default These include identifiers variable names types object properties and methods namespace names and so forth numbers and strings When the code editor finds an error in your code it highlights the error with a wavy underline If you hover over the underline the editor displays a tooltip describing the error If Visual Studio can guess what you are trying to do it adds a small flat rectangle to the end of the wavy error line to indicate that it may have useful suggestions The assignment statement i 12 shown in Figure 1 59 has an error because it tried to assign a string value to an integer variable and that violates the Option Strict On setting The editor displays the
102. ute macros that automate repetitive Visual Studio programming chores If you must perform a series of actions many times you can record a macro that performs them Then you can call the macro repeatedly to perform the actions rather than executing them manually After you have recorded a macro you can edit the macro s code and make changes For example if you want to run the code a certain number of times you can include it in a For loop Often a quick inspec tion of the code lets you figure out how to modify the code to perform actions similar to but not exactly the same as the actions you originally recorded Most of the commands in the macros submenu are self explanatory Use the Record TemporaryMacro command to record a macro for quick temporary use When you select this command a small window pops up that contains buttons you can click to suspend finish or cancel recording Visual Studio saves the commands you execute in a macro named TemporaryMacro Select Run TemporaryMacro to run this macro If you record a new TemporaryMacro it overwrites the existing one without warning you Select the Save TemporaryMacro command to rename the macro so you can record a new TemporaryMacro without destroying this one IDE 8 WindowsApplication1 Microsoft Visual Studio oix File Edit View Project Build Debug Data Tools Window Community Help E Attach to Process Ctri Alt P Connect to Device Conn
103. you could add a command to launch WordPad MS Paint WinZip and other handy utilities from the Tools menu Device Emulation Manager This command displays the Device Emulation Manager which lets you connect reset shut down and otherwise manipulate device emulators 37 Chapter 1 Create GUID oix Choose the desired format below then select Copy to coy copy the results to the clipboard the results can then be pasted into your source code Choose Exit when New GUID done GUID Format Exit 2 DEFINE_GUID 3 static const struct GUID 4 Registry Format fie fxxxxxnx Kexx xxxx Y r Result 8E377DB3 BB68 44ce B487 108D 34584032 IMPLEMENT_OLECREATE lt lt class gt gt lt lt external_name gt gt Ox8e377db3 Oxbb68 Ox44ce Oxb4 0x87 Ox1c Ox8d 0x34 0x58 0240 0x32 Figure 1 39 The Create GUID dialog generates GUIDs Q Import Export Settings This command displays a dialog that you can use to save restore or reset your Visual Studio IDE settings Q Customize This command allows you to customize the Visual Studio IDE See the Customize section later in this chapter for details Q Options This command allows you to specify options for the Visual Studio IDE See the Options section later in this chapter for details Macros 38 The Macros submenu shown in Figure 1 40 provides commands that help you create edit and exec
Download Pdf Manuals
Related Search
Related Contents
6 févier 2012 Energy Sistem 421695 e-book reader AVAND-II取扱説明書 IMS Budget System User`s Manual Copyright © All rights reserved.
Failed to retrieve file