When you create a new macro project, the Open dialog box creates a new directory for the project, just like the main IDE, which creates directories for you.. Renaming Projects and Module
Trang 1Explorer.” The difference is that in the latter section I discuss how to manage your jects using the Macro Explorer in the main IDE; here I show you how to manage yourproject using the Macros IDE However, there are certain things you can do only fromwithin the main IDE through either the Macro Explorer or the menu items These are:
pro-■■ Create a new project
■■ Load a project
■■ Unload a project
Since I show you later how to do these three tasks using the Macro Explorer, now I’ll
show you how to do them using the menus Remember, however, that these are the
menus in the main IDE, not in the Macros IDE (Why can’t life be less complicated?)
The Macros IDE is aware of an active project You can tell which project is
currently active by looking at the title bar of the IDE window The title will
start with the name of your project, followed by a hyphen, followed by the
words “Microsoft Visual Studio Macros.”
Creating a New Project
To create a macro project, you must use the main IDE To do so, choose Tools➪Macros➪New Macro Project The New Macro Project dialog box will open The onlytemplate available by default is Macro Project Make sure the Macro Project templateicon is highlighted Then enter the name of your project in the text box labeled Name.Next, choose a directory in which to place your project
When you create a new macro project, the Open dialog box creates a new
directory for the project, just like the main IDE, which creates directories for you The new directory has the same name as your project file, but without
the vsmacros extension.
After you create the new project, when you switch back to the Macros IDE, you willsee the project in the Project Explorer
Loading and Unloading Projects
Like creating a macro project, you can only load and unload projects from the main IDE
Remember, the main IDE maintains a list of macro projects that are
currently loaded These are the macro projects that you (or your IDE users)
can access while working with the IDE.
If there is a macro project that you don’t care to use or work on for the time being,
you can remove it from the macro system This is called unloading the project After you
do so, the macro project will vanish from the Macro Explorer in the main IDE and from
Trang 2the Project Explorer and Class View in the Macros IDE The project is still on your harddrive; it’s just not loaded into the IDE
Here’s how to load or unload a macro project:
■■ To load a macro project: Choose Tools➪Macros➪Load Macro Project A dialogbox will open allowing you to locate and choose a vsmacros project file Whenyou click Open, the macro project will be added to the macro system It willalso show up in the Macro Explorer Alternatively, you can double-click the.vsmacros file in Windows Explorer
■■ To unload a macro project: In the Macro Explorer, click on the name of the macro
project you wish to unload Then choose Tools➪Macros➪Unload Macro Project
Saving Your Project
Back in the Macros IDE, to save a project, choose File➪Save (the word “Save” on themenu will be followed by the name of your project) Or press Ctrl-S
Which project you save depends on what item in the IDE is currently active:
■■ If you first click on any item in either the Project Explorer or the Class View, theproject containing that item will be saved
■■ If you first click on the source file window, then the project containing theactive document will be saved
You cannot tell the IDE to save only a single module Since all modules within a ect are stored in a single vsmacros file, you can only save the entire project, includingall its modules, at once
proj-Note also that when you edit a macro, you don’t need to save the project to see thechanges from within the Macros IDE The main IDE knows of the code as it is in mem-ory, not as it is on disk
Although the macro system keeps all the modules for a project wrapped up inside asingle vsmacros file, you can export the individual modules to their own text files with
a vb extension The macro system doesn’t actually use these vb files; the macro systemstill uses the modules as they are stored in the vsmacros file But this way you can usethe files in other VB.NET projects if you wish (To use the module in another macroproject, you can use the insert the module by right-clicking on the macro project in theProject Explorer in the Macros IDE, and then choosing Add➪Add Existing Item fromthe popup menu.)
To export a module to its own file, either make sure the module is open in the sourcecode window or click on the module’s name in the Project Explorer Then chooseFile➪Export, where the word “Export” will be followed by the name of the moduleyou are exporting An Export File dialog box will open that’s equivalent to a typicalSave As dialog box Choose the location where you want to save the file, enter its name,and click Save
When you export a file, the file will be saved in Unicode format Therefore, some text editors might not be able to open it (although, believe it or not, Notepad.exe on Windows NT, 2000, and XP will open a Unicode file).
Trang 3Default Macro Location
Although you can save your macro projects anywhere on the hard drive where youhave permissions, by default, Visual Studio NET stores the macros in a directorycalled VSMacros, in the default Visual Studio projects locations
To view or change this default location, make sure you’re in the main IDE, not the Macros IDE, and choose Tools➪Options Inside the Options dialog box, choose Envi-ronment➪Projects and Solutions In the options page is an edit control labeled “VisualStudio project locations.” This edit control contains the default project path
If you decide to change the default location for your macros to a different
directory, remember that you will also be changing the default location for
the programming projects and solutions in the main IDE.
Creating a New Module
To create a new module, you have some choices:
■■ Make sure the project that will contain the module is the active project (You
can tell by looking at the title bar of the Macros IDE(you should see the
proj-ect’s name there.) If your project is not the active one, click on its name (or one
of its modules) in the Project Explorer Next, choose File➪Add New Item
■■ Right-click the project name in the Project Explorer, and in the popup menu
choose Add➪Add Module
Either of these two options will cause the Add New Item dialog box to open Makesure Module is highlighted in the Templates list, then type the name of your new mod-ule in the Name edit box Next, click Open (Yes, the button is labeled Open, not Create
or something more appropriate.)
After you click Open, the new module will be in your project You will see it in theProject Explorer, and you can now edit it
Renaming Projects and Modules
To rename a project or module from within the Macros IDE, do one of the following:
■■ Right-click the project name or module name in the Project Explorer and
choose Rename The project or module name in the Project Explorer will turn
into an edit control, where you can type the new name and press Enter
■■ Click the project name or module name in the Project Explorer, pause a couple
seconds, and then click the name a second time (Note, if the name is already
highlighted, you should only have to click the name once.) The name will turn
into an edit control into which you can type the new name
Trang 4Make sure that when you attempt to change a project’s or a module’s name that you are in the Project Explorer in the Macros IDE, not the Class View You cannot change the project or module name from the Class View.
When you change a project’s or a module’s name, the change will not be permanentuntil you save the project by choosing File➪Save, where the word Save will be fol-lowed by the project name Even then, you will not see the actual vsmacros filenamechange until you either unload the macro or shut down the main IDE, because themain IDE keeps the vsmacros file open as long as the macro project is open
Be careful with module names The Project Explorer in the Macros IDE lists the name of the file that contains the module (even though technically all the “files” for these modules are stored inside a single vsmacros file) This filename does not have to match the name contained in the header line of the Module declaration in the source code file But that’s when things get confusing I prefer to name my module and its filename the same, for simplicity Plus, that helps me to think of the file and the module as a single entity But if you do rename the module, only do so by right-clicking the module in the Project Explorer and choosing Rename That will keep
everything synchronized.
Deleting a Module
To delete a module, do one of the following (Make sure you do these in the ProjectExplorer, not the Class View.)
■■ Click the name of the module in the Project Explorer (If an edit control appears
so that you can edit the name, just press Esc.) Then either press Del or chooseEdit➪Delete
■■ Right-click the name of the module in the Project Explorer and choose Delete.Whichever action you take, you will then see a message that says, “Module1 will bedeleted permanently” (but instead of Module1 you will see the name of your module)
In other words, you cannot undo the deletion of a module If you are sure you want todelete the module, click Yes (The reason the action cannot be undone is that all themodules for a single project are all stored in a single vsmacros file for the project.When you click Yes, the IDE deletes the module directly from the vsmacros file There-fore, although the vsmacros project file is still present, the module is not.)
Running a Macro
To run a macro without starting a debugging session, either switch to the main IDE anddouble-click the macro name in the Macro Explorer, or, from the Macros IDE, click themouse anywhere inside the macro’s code in the source code editor; then either pressCtrl-F5 or choose Debug➪Start without Debugging
Trang 5If there are errors anywhere in a macro project, then neither the main IDE
nor the Macros IDE will let you run any of the macros in the project Make
sure, then, that there are no errors in your project.
An important point to be aware of when you run your macros is that if you haveglobal variables in your macro project, these variables will not change between execu-tions of the macro For example, suppose you have this variable and macro defined in
However, if you change any code inside the project containing the macro (whether
or not you save the changes to disk), then Visual Studio NET will restart the project,meaning your variables will be reset as well Thus, if I modify the IncTestNumbermacro, when I return to the main IDE and double-click the IncTestNumber name, I will
once again see the number 11, not 13, in a message box.
If you run a macro, and while it is running attempt to run another macro, the second macro will get queued, and will not begin until immediately after the first macro finishes.
Stopping a Macro
If a macro you have running gets stuck, or you just want to end it, you can force themacro to stop Suppose you have the following macro (or perhaps a macro that callsthis subroutine):
Public Sub WaitForAMoment()
MsgBox(“Going to sleep for 10 seconds ”)
Trang 6If, instead, you want to abort the macro before the 10 seconds is up, switch to thetask bar on the Windows desktop There, you will see an animated icon of a cassettetape flipping around Double-click this icon and the macro will stop Or, you can right-click this icon, in which case you’ll get a popup menu with a single choice: “Stop VisualStudio macros.” Choose this menu item to stop the macro.
Using the Code Editor in the Macros IDE
By now you’ve certainly seen the code editor in the Macros IDE, and you’ve probablydiscovered that it works pretty much just like the code editor in the main IDE In theintroductory section of Chapter 2, I mentioned that the code editor will automaticallyformat your VB.NET code for you Here, now, are some more tips for getting the mostfrom the editor
Collapsible Code
You may have noticed that to the left of some of your lines of code is a small minus signthat looks similar to the minus symbol in a treeview control This sign serves the samepurpose as that in a treeview control: to collapse the code For example, if you want tosee only a subroutine’s header and hide the subroutine’s code, you can collapse thesubroutine For example, if this is your subroutine:
outlining feature of the code editor.
And while the code is collapsed, you’ll see to the right of it a small white box with
an ellipses ( ) in it If you momentarily hold the mouse pointer over this box, a smalltooltip window will appear showing you the collapsed code
If you want to collapse all the subroutines and functions in your code, choose Edit ➪Outlining➪Collapse to Definitions.
If you don’t like this outlining feature, you can turn it off by choosing Editing➪Stop Outlining Later, if you decide you want it back on, choose Edit➪Outlin-ing➪Start Automatic Outlining
Trang 7➪Outlin-Working with Blocks of Code
If there are several lines of code that you want to comment out, highlight them andchoose Edit➪Advanced➪Comment Selection To uncomment a commented block ofcode, choose Edit➪Advanced➪Uncomment Selection
If you have the automatic formatting feature turned off (through the Tools➪Optionsdialog box, on the Text Editor➪Basic➪VB Specific page, under the Pretty Listing (refor-matting) of code selection), you can automatically format a section of code by high-lighting the lines and choosing Edit➪Advanced➪Format Selection
You can also perform all the usual features that are present in the main IDE underthe Edit➪Advanced menu, such as making a selection all uppercase or all lowercase (ifyou have such a need)
If you have a block of code collapsed and you want to perform a block edit
operation (such as commenting out the code) on the collapsed code,
highlight the box with the ellipses in it before performing the block edit
operation.
Debugging a Macro
In this section I assume you’re familiar with debugging concepts and how to use thedebugger in the main IDE, which is the tool you use for debugging your programmingprojects The debugger in the Macros IDE works very much like the one in the mainIDE However, there’s a trick to getting your macros to run there:
1 To debug a macro, make sure the module containing the macro is opened in thecode editor
2 Click on the first line of the macro, the header line containing the Sub declaration
3 Press F9 to set a breakpoint (or right-click the line and choose Insert
Break-point) You will see a red highlight appear on the line
4 Press F5 to start the debugger (or choose Debug➪Start)
When the debugger starts, it will break at the first line in your macro, and the firstline’s highlight will change from red to yellow
When you are running a macro in the Macro IDE Debugger, you cannot stop
the macro by double-clicking the macro icon in the tray of the Windows
desktop’s task bar Doing so will have no effect.
While you are at a breakpoint, you can then do any of the following:
■■ Step into a subroutine or function: Choose Debug➪Step Into, or press F11, or clickthe Step Into button on the Debug toolbar
■■ Step over a subroutine or function: Choose Debug➪Step Over, or press F10, or
click the Step Over button on the Debug toolbar
Trang 8■■ Step out of a subroutine or function: Choose Debug➪Step Out, or press Shift+F11,
or click the Step Out button on the Debug toolbar
■■ Modify an existing breakpoint: Right-click a line with a breakpoint and choose
Remove Breakpoint, or Disable Breakpoint, or Breakpoint Properties If youchoose Breakpoint Properties, the Breakpoint Properties window will open,allowing you to add conditions upon which to break
■■ Add a breakpoint: Right-click a line and choose Add Breakpoint.
■■ Add a watch: Right-click an identifier in the source code window and choose
Add Watch The Watch window will open, showing the identifier along withother identifiers you are already watching
■■ Add a quick watch: Right-click an identifier in the source code window and
choose Quick Watch The Quick Watch window will open, showing you theidentifier and its current value, which you can change
When you’re viewing the Quick Watch window, you can call other subroutines and functions in your code Simply type the name of the subroutine or function in the Expression window along with parentheses containing zero or more parameters, and click Recalculate.
■■ Watch the local variables in a subroutine: Choose Debug➪Windows➪Locals
■■ Observe the call stack: Choose Debug➪Windows➪Call Stack
Working with the Macro Explorer
Although you will normally use the Macro IDE to develop your macros, you have fullaccess to the macros from the standard IDE through the Macro Explorer To view theMacro Explorer, shown in Figure 3.3, choose View➪Other Windows➪Macro Explorer.Like the Solution Explorer, the Macro Explorer shows your macro projects in a hier-archical manner inside a treeview When you expand a project, you see the individualmodules, and under each module you see the individual macros for that project.(Remember, each macro is a public VB.NET subroutine inside the module.)
Figure 3.3 The Macro Explorer in the main IDE.
64 Chapter 3
Team-Fly®
Trang 9To run a macro using the Macro Explorer, double-click its name in the Macro Explorer or right-click its name and choose Run.
The Macro Explorer allows you to do the following actions on your projects, ules, and macros First, here are items involving macro projects:
mod-■■ Create a new macro project: Right-click the top item called Macros in the
tree-view; in the popup menu, choose New Macro Project The New Macro Project
dialog box will open, just as it does when you use the menu items to create a
new macro project You only have one option for a template, Macro Project
Type a name and a location for your new project Then click Open (even
though you’re actually creating and then opening the project).
■■ Insert an existing project into the Macro Explorer: If you have a macro project, such
as one you received from somebody else, that’s not in the Macro Explorer, you
can add it Right-click the Macros item and choose Add➪Insert Existing Project
■■ To unload a project: Right-click the project name and choose Unload Macro Project.
■■ To save a project: The only way to save a macro project from within the main IDE
is to choose File➪Save All However, this saves everything that has changed Ifyou prefer to save only your file, use the Macros IDE and choose File➪Save,
where Save is followed by the name of your project
■■ To rename a project: Right-click the name of the project and choose Rename.
Now here are items involving modules within a project:
■■ To create a new module: Right-click the module name in the Macro Explorer and
choose New Module The Add Module dialog box will open, allowing you to
create the new module
■■ To rename a module: Right-click the module name in the Macro Explorer and
choose Rename You can then type in a new name for the module
■■ To delete a module: Right-click the module name and choose Delete As in the
Project Explorer in the Macros IDE, you cannot undelete a module once you’vedeleted it here But you will see a slightly different message from the one you
see in the Macros IDE: “Are you sure that you want to delete Module1? This
action cannot be undone.”
■■ To Edit a module: Double-click the module name The Macros IDE will open and
you will see the code file for the module whose name you double-clicked
If you’re digging through the popup menus as you read this, you’ll see the menuname Set as Recording Project For more information on this item, see “QuicklyRecording a Temporary Macro” in this chapter
And now here are the actions you can perform in the Macro Explorer on individualmacros Remember, macros are subroutines inside a module, and all the moduleswithin a project are stored in a single vsmacro file:
■■ Create a new macro: Right-click on the module that you want to hold the macro
and choose New Macro When you do so, the Macro IDE will open and the
Trang 10Macro IDE will automatically insert a new macro called Macro1 (or Macro2,and so on) into the module.
■■ Rename a macro: Right-click on the macro name (back inside the Macro Explorer,
in case you’re looking at the Macros IDE now from the previous bullet item).Then choose Rename You can type in a new name for the macro
■■ Delete a macro: Right-click on the macro name and choose Delete The IDE will
ask if you really want to delete the macro, since the action cannot be undone.Just like modules, macros live inside a module, which lives inside the
.vsmacros project file If you delete a macro, the IDE completely removes itfrom within the vsmacros project file; thus it cannot be undone So be sure youreally want to delete a macro before doing so
■■ Run a macro: Either double-click a macro name or right-click on the macro name
and choose Run
While a macro is running, you will see two visual indicators: First, down in the status bar of the main IDE, you will see a small animated icon that looks sort of like a cassette tape flipping around; second, you will see this same animated icon in the tray portion of the taskbar on your Windows desktop
Finally, remember this important tip:
When you double-click a macro in the Macro Explorer, the macro runs Do not double-click the macro to edit it However, if you double-click a module name, you will enter the Macros IDE so you can edit the module.
Quickly Recording a Temporary Macro
When programmers first developed the concept of a macro, the process was simple:The user identified a task that he or she wanted to repeat several times, and so started
a macro recorder; next, the user performed the task to be repeated (such as typing
some-thing into the keyboard and perhaps selecting various menu items); finally, the userturned off the recorder The macro was recorded When the user wanted to repeat thetask, he or she started the macro, usually by pressing some key
The process was nice and simple Fortunately, today, Microsoft has maintained thatsimplicity for those users who only want to record repeated tasks The Visual Studio.NET IDE includes a recorder feature that’s as easy as the steps just described And itnot only records the macros, but it saves the macros in the same language you use towrite your own macros from scratch, VB.NET
Saving the macros in VB.NET has a nice bonus feature, too: If you, the macro oper, want to automate a task that involves pressing keys, choosing menu items, and
devel-filling in dialog boxes, you can use the recorder features as a starting point for writing
your macro
Thus, in this section I show you how to get the most out of the recorder features
Trang 11Selecting the Recording Project
If you have no macro projects open and you start recording a macro, Visual Studio.NET will create a macro project for you by default This project will be calledMyMacros, and it will have two modules: one called Module1 (which is a default mod-ule that the recorder doesn’t use, but to which you’re free to add macros) and anothercalled RecordingModule The macro that you record goes inside the RecordingModulemodule, and the macro is called TemporaryMacro
But if you do have several macro projects open, you have a choice: You can either letVisual Studio NET assign you a RecordingModule and a TemporaryMacro when itrecords your macro for you or you can choose which project will be the recording proj-ect (If you let Visual Studio NET assign you a RecordingModule, it will use thedefault Module1 until you choose a different project to be the recording project.)
To choose the recording project, open the Macro Explorer, right-click the
project, and choose Set as Recording Project After you select which project
will be the recording project, your chosen project’s name will appear in
boldface in the Macro Explorer.
Recording a Macro
Once you have chosen a recording project (which means you might have chosen thedefaults), you can go ahead and record your macro Now remember, the IDE willassign this macro the name TemporaryMacro, but it is in no way temporary: You arefree to rename it, move it to another module, and so on
If you are going to record a macro, I recommend opening up the Macro Explorer
so that you can easily access the macro after you have recorded it Then you’re ready
to record:
To record a macro, choose Tools ➪Macros➪Record Temporary Macro (The
default key combination for this is Ctrl+Shift+R.)
When you begin recording, the Recorder toolbar will open This toolbar lets youpause the recording, stop the recording, or altogether cancel the recording
A point of note about the Recorder toolbar: Though it is a toolbar, it’s special in thatthe IDE won’t let you open it unless the recorder is running, nor can you close it whenthe recorder is running Oddly, the IDE will, however, let you modify the toolbar while
it is open (which means a macro is being recorded) But if you do modify the Recordertoolbar, your changes will not get recorded into the macro (Probably, it’s best not tomess with such self-referential universes Leave that for the science fiction movies.)
While the Recorder toolbar is open, any keystrokes you perform, or toolbar buttonsyou click, or menu items you choose will be recorded Further, if any of these actionsopens a dialog box, and you click OK in the dialog box, your settings will be recorded.Each action that you perform will result in additional VB.NET lines of code being put
in the macro subroutine
Trang 12The toolbar has three buttons on it:
Pause Recording. If you click this button, the recording action will be ily suspended, at which point any keystrokes or other actions you perform willnot be recorded Recording will resume when you click the Pause Recordingbutton a second time
momentar-Stop Recording. This button will end your recording and save the actions intothe Module as a new macro
Cancel Recording. This button is the abort button; if you click it, the recorderwill stop recording and your actions will not be saved to a macro Click this ifyou decide you don’t want to record a macro after all
Editing the Temporary Macro
After you have recorded a macro, you can edit it To do so, locate the macro project in theMacro Explorer that is the recording project (its name will be bold) Underneath it, right-click on RecordingModule and choose Edit When you do so, the Macros IDE will open.Here’s an example of a macro that I recorded First, here are the actions that Irecorded:
1 Ctrl+A (That’s the same as Edit➪Select All.)
2 Edit➪Advanced➪Format Selection
Option Strict Off
Option Explicit Off
DTE.ActiveDocument.Save(“C:\MyProject\ArrayTest.backup.txt”)
Trang 13End Sub
End Module
Notice that the Save selected the filename I typed in That’s not good; my intentionwas to write an automatic backup macro But that’s okay; I can change it Also, notice that even though I typed MyProgram.backup, the macro recorded it as MyPro-gram.backup.txt with a txt extension But that’s not the recorder’s fault That’s thefault of the Save File As dialog box: If while inside the Save File As dialog box I hadchosen All Files (*.*) for the Save as Type box, then Visual Studio NET would havesaved the filename as I requested it
The next step is to modify this macro so it’s more useful I certainly don’t want tosave every file as MyProgram.backup Instead, I will ask the IDE for the name of thedocument that’s open, and I’ll piece the filename together myself Also notice that thefirst line in the macro is a call to Activate That function activates the documentcalled MyProgram.cpp But in the final version of this macro, I hope to have the macrouse whichever file is currently active So I will chop that Activate line altogether
To figure out the filename information, I’m going to use two NET macro features:
■■ To retrieve the filename, I’m going to use the DTE.ActiveDocument object
That’s a handy property right on the DTE object itself that returns an instance of
a class called Document
■■ To figure out the backup filename, I’m going to use a class called Path, which
has a handy function called ChangeExtension This function takes a filenameand a new extension name as parameters, and returns a new string with the
path modified What could be simpler?
Finally, after I recorded the macro I decided that I should probably close the newbackup file that I created So I added a line at the end of the macro to close the file
Here, then, is the new code after I changed it:
Option Strict Off
Option Explicit Off
Dim Filename As String
Dim Doc As Document
Trang 14DTE.ActiveDocument.Selection.Paste() DTE.ActiveDocument.Save(BackupFilename) DTE.ActiveDocument.Close(vsSaveChanges.vsSaveChangesYes) End Sub
End Module
Now this code is more usable in a general sense Instead of working on a particularfile, it works on any open file in the main IDE Once I’m happy with the code, I canrename the macro and copy it to a different module from the RecordingModule Thenthe macro is ready for prime-time use
Assigning Shortcut Keys to Your Macros
If you give your macros to other people to use on their computers, you might not wantthem to have to keep the Macro Explorer open so they can access your macros Fortu-nately, you have some choices on how to allow them to run your macros (You canimplement these on your own computer, too, for use during the development of yourmacros.)
■■ Choose and assign the macro a shortcut key so that when the IDE user presses
a certain keystroke combination (such as Ctrl+Shift+m), the macro will run
■■ Add various menu items to the user’s IDE that allow menu access to themacros
■■ Add various buttons to the toolbars on the user’s IDE that allow button access
Tool-1 From the main IDE, choose Tools➪Options Expand the Environment tree;under Environment, click Keyboard to see the Keyboard options (Alterna-tively, choose Tools➪Customize In the Customize dialog box, under the Tool-bars tab, click Keyboard This will also get you to the Keyboard options page.)
2 In the middle of the dialog box you’ll see a listbox with all the commandsknown to the IDE Either scroll through this to find your macro or just type themacro name in the text box above the list labeled “Show commands contain-ing.” Do not press Enter; just wait a moment and the list will shorten to onlythose commands that have the text your entered
Trang 153 Next click on your macro in the list, then click the mouse on the text box
labeled “Press Shortcut Key(s).” You will see the name of your keystroke
appear in the edit control For example, if you press Ctrl+Shift+I, you will see
“Ctrl+Shift+I” appear in the text box You will also see a list of places where
this shortcut key is already assigned (Hint: It’s a good idea to look at this list tomake sure you’re not clobbering a shortcut key that’s already in use and that
you use occasionally Once, while using Microsoft Excel during a slow time in
my mental activity, I reassigned Ctrl+S and later wondered why, when I tried
to save my file, one of my macros would run instead.)
4 When you’re happy with the key assignment, press Assign
Moving Forward
This chapter introduced you to the Macros IDE, which, as you now realize, looks verymuch like the main IDE That means if you know how to use the main IDE, you’ll becomfortable using the Macros IDE as well Further, you learned how to use the MacroExplorer in the main IDE to create and modify the names of your macros
In the next chapter I show you ways to write macros that have their own user faces And while on that topic, I’ll cover the different ways that you can present infor-mation to the user
Trang 17In this chapter I show you how you can interact with the user in various ways I devotethe first half of the chapter to showing how you can reference other libraries in yourprojects, because to make interaction easy, often you will want to work with external
projects or libraries For example, you might have a NET assembly (which is a NET
form of a DLL) that contains subroutines, functions, or classes that you want to use inyour macros To use these items, however, you must set up a reference to the assembly
in your macro project Or you might have a set of subroutines and functions you wrote
in VB.NET using the Macros IDE that you want to use in other macros
In this chapter I also show you how you can access these subroutines and functionsfrom any macro project using two different approaches: importing the code into yourproject and creating a standalone assembly that you reference in your project
From there I move on to show you how easy it is to create forms and populate themwith controls, and how you can interact with the forms I also show how you can makeuse of the common Windows dialogs
Finally, I discuss the different events you can respond to that occur in the mainVisual Studio NET IDE, events such as a window opening or the main IDE starting up
Referencing Assemblies and Macro Projects
In Visual Studio NET, you can create DLLs called assemblies An assembly is a DLL orEXE that contains managed Microsoft.NET code, along with information about the file
Macros That Interact
with the User
4
Trang 18When you build a managed application or class library in Visual Studio NET, the final.EXE or DLL you create is an assembly
Since your macros use VB.NET, you have access to the rich set of features included
in NET programming, including the use of external assemblies (As a user of VisualStudio NET, you’ve probably encountered assemblies before, but if you’re not surewhat they’re all about, refer to Chapter 5, “Just Enough NET Architecture.”)
Referencing External Assemblies
When you want to use objects and classes from an external assembly, you need to add
a reference to the assembly from your VB.NET macro The Macros IDE includes a log box for adding references; the Macros IDE also includes a list of the referencedassemblies in the Project Explorer
dia-To view the references list in the Project Explorer, expand a project; the first item you will see under the project name is References When you expand References, you will see the names of referenced assemblies.
To add a reference to your project, you have two choices:
■■ Right-click the word References under the project name in the Project Explorer
A popup menu containing a single item opens: Add Reference Choose it andits dialog box will open
■■ Make sure your project is active (in the Project Explorer or Class View, click onany item in the project; the project name will appear in the title bar of theMacros IDE) Then choose Project➪Add Reference The Add Reference dialogbox will open
Whenever you add a reference using the Project ➪Add Reference menu item,
take a quick look at the title bar of the Macros IDE to make sure the correct project is active It’s easy to accidentally add the reference to the wrong project!
The Add Reference dialog box is shown in Figure 4.1 It contains a list of assembliesregistered in the NET system You can add your project references to one or more ofthese assemblies The list of assemblies contains the name of the assembly, the versionnumber, and the path to the assembly’s DLL file
To use the Add Reference dialog box, click on the assembly’s name in the list andthen click the Select button; or just double-click the assembly’s name; its name willthen appear in the Selected Components list in the lower portion of the dialog box.(You can select multiple names by holding down the Shift and Ctrl keys and clickingmultiple names.) Repeat this step to add more than one assembly
74 Chapter 4
Team-Fly®
Trang 19Figure 4.1 Use the Add Reference dialog box to add to your project references to external
assemblies
If you have a list of assemblies to add, but decide you want to remove one from thelist, click its name in the Selected Components list and click Remove When you’re fin-ished, click OK (If you change your mind, you can always return to this dialog boxlater to add more references; or you can remove them from the References list in theProject Explorer You will see that the References section in the Project Explorer nowcontains the items you chose in the Add Reference dialog box If you want to remove areference, right-click the reference name in the References list in the Project Explorerand choose Remove
Referencing Items in Other Macro Projects
If you have a set of subroutines, functions, and classes in a macro project that you want
to make available to other macro projects, you have a couple of choices for doing this.First, you can export the module containing the subroutines, functions, and classes,and then add the module to the project needing the items Second, you can move themodule into a VB.NET program inside the main IDE and build an assembly containingthe items (This second approach isn’t as difficult as it sounds; in fact, it’s pretty easy.The only catch is that you must have VB.NET available in your main Visual Studio.NET installation.)
Trang 20Both approaches have some pros and cons:
■■ Exporting the module The advantage is that you have direct access to the source
code in your macro project, because the module becomes an actual part of yourproject The disadvantage is that your project ends up with a copy of the originalmodule, rather than the original module itself Thus, if you make changes to theoriginal, you will have to duplicate the changes in your project, or reimport it
LISTING REFERENCES FROM A MACRO
This is a book on macros, so in addtion to telling you about references, I’m going to show you how you can gain access to a project’s references at runtime The following macro lists all the macro projects presently loaded, and for each project lists the references, including the full path to the reference In the following listing, I obtain a Solution object from the DTE.MacrosIDE object The Solution object contains a set of Project
objects I climb through the list of Project objects, and from each obtain a VSProject, which contains the list of references For each reference, I ask for its name and its path, which I print to the Output window.
Imports EnvDTE
Imports System.Diagnostics
Public Module ObtainReferences
Sub ListRefs() Dim a As VSLangProj.Reference Dim s As Solution
Dim vsp As VSLangProj.VSProject Dim p As Project
ClearOutput()
s = DTE.MacrosIDE.Solution For Each p In s.Projects vsp = p.Object Print(“Project: “ & p.Name) For Each a In vsp.References Print(“ “ & a.Name) Print(“ “ & a.Path) Next
Next
End Sub
End Module