
406
|
Chapter 12, Extending Visual Studio
#89 Writing a Visual Studio Add-in
HACK
Write the Code
The next step is to write the code that will do the work of the add-in. In this
example, I will be writing a simple piece of code that surrounds the selected
text with a
try...catch block. This code needs to be added to the Exec
method that was added for you by the wizard. Here is a look at the default
code:
public void Exec(string commandName,
EnvDTE.vsCommandExecOption executeOption,
ref object varIn, ref object varOut, ref bool handled)
{
handled = false;
if(executeOption = =
EnvDTE.vsCommandExecOption.vsCommandExecOptionDoDefault)
{
if(commandName = = "TryCatchMatic.Connect.TryCatchMatic")
{
handled = true;
return;
}
}
}
This code first checks the executeOptions and then checks to see if the com-
mand being called is the command for this add-in. Inside the last
if state-
ment is where you will write the code for what your add-in will actually do.
Here is the code I have added to get the currently selected text and then sur-
round it with a
try...catch block:
if(commandName = = "TryCatchMatic.Connect.TryCatchMatic")
{
string selectedText = textDoc.Selection.Text;
string newText = "try\n { \n" + selectedText
+ "\n}\ncatch\n{\n}";
textDoc.Selection.Text = newText;
handled = true;
return;
}
In this code, I get a reference to the ActiveDocument and then get the selected
text. I can then replace the selected ...