Como manipular a propriedade Imports de projetos do Visual Basic
A maioria dos métodos e propriedades do VSProject2 se aplicam igualmente a projetos do Visual C# e do Visual Basic. Para obter mais informações, consulte Como manipular projetos do Visual Basic e do C# usando o objeto VSProject2. A propriedade Imports do objeto VSProject2 é específica de projetos do Visual Basic. Fornece acesso ao objeto Imports com métodos para adicionar e enumerar a coleção Imports.
As etapas a seguir explicam como controlar programaticamente a propriedade de Imports em um projeto de Visual Basic usando um suplemento Visual Studio.
Dica
Seu computador pode mostrar diferentes nomes ou localizações para alguns dos elementos de interface do usuário Visual Studio nas instruções a seguir.A edição do Visual Studio que você possui e as configurações que você usa determinam esses elementos.Para obter mais informações, consulte Personalizando configurações de desenvolvimento no Visual Studio.
Para usar o objeto VSProject2 para controlar projetos Visual Basic
Crie um projeto de suplemento do Visual Studio usando o Visual C#.
No menu Projeto, clique em Adicionar Referência, clique na guia .NET, selecione VSLangProj, VSLangProj2, and VSLangProj80 e clique em OK.
Crie uma pasta em seu computador:
<Installation Root>\UserFiles\MyProjects\MyTestProject
Nesse exemplo, o <Installation Root> é "C:".
Adicione as seguintes instruções de uso na parte superior do arquivo Connect.cs.
using VSLangProj; using VSLangProj2; using VSLangProj80; using VSLangProj90;
usando VSLangProj100; Adicione o seguinte método de chamada para o método de OnConnection.
public void OnConnection(object application, ext_ConnectMode connectMode, object addInInst, ref Array custom) { _applicationObject = (DTE2)application; _addInInstance = (AddIn)addInInst; VBVSProj2Manip(_applicationObject); }
Adicione a declaração do método CSVSProj2Manip diretamente abaixo do método OnConnection.
public void CSVSProj2Manip(DTE2 dte) { }
Adicione as seguintes declarações na parte superior do método.
Solution2 soln = (Solution2)_applicationObject.Solution; String vbTemplatePath; String vbPrjPath; Project proj; VSProject2 vsproj; Imports impCollection;
Use AddFromTemplate para criar um projeto do Visual C#.
- A sintaxe para obter os modelos é EnvDTE80.Solution2.GetProjectTemplate("WindowsApplication.zip", "VisualBasic"), onde o nome "WindowsApplication.zip" é obtido do arquivo de WindowsApplication.zip localizado na pasta <Installation Root>\Program Files\Microsoft Visual Studio 8\Common7\IDE\ProjectTemplates\VisualBasic\Windows\1033. Para todos os tipos de projeto do Visual Studio, esses arquivos podem ser encontrados na pasta <Installation Root>\Arquivos de Programas\Microsoft Visual Studio 8\Common7\IDE\ProjectTemplates\Language. "VisualBasic" especifica que este projeto é um projeto Visual Basic.
// Make sure you create the folders that // make up the file path // on your computer. You can replace // this with your own file path. vbPrjPath = "C:\\UserFiles\\MyProjects\\MyTestProject"; // Get the project template path for a C# windows // application. vbTemplatePath = soln.GetProjectTemplate ("WindowsApplication.zip", "VisualBasic"); // Create a new Windows application by using the // template obtained above. soln.AddFromTemplate(vbTemplatePath, vbPrjPath, "Test2VBProj", false);
Adicione o seguinte código para demonstrar o uso de Imports depois que é obtido através da propriedade de Imports.
proj = soln.Projects.Item(1); // Get a reference to the VSProject2 object. vsproj = (VSProject2)proj.Object; // Add a reference to System.Security.dll. MessageBox.Show("Adding a reference to System.Security.dll"); // Remove the <version number> in the following path // and replace it with one of the version // number folders that appear // in <installation root>\WINDOWS\Microsoft.NET\Framework // folder vsproj.References.Add ("C:\\WINDOWS\\Microsoft.NET\\Framework\\ <version number>\\System.Security.dll"); impCollection = vsproj.Imports; MessageBox.Show("The number of imports in this project is: " + impCollection.Count.ToString() + "\n"); MessageBox.Show ("Adding System.Security to the Imports collection."); impCollection.Add("System.Security"); MessageBox.Show("The number of imports in this project is now: " + impCollection.Count.ToString() + "\n"); String temp = null; for (int i = 1; i <= impCollection.Count; i++) { temp = temp + impCollection.Item(i).ToString() + "\n"; } MessageBox.Show("The Imports in this project are:" + "\n" + temp);
O método VBVSProj2Manip usa o objeto VSProject2 para:
Adicionar uma referência a System.Security.dll usando References.
Obtenha um identificador para Imports usando a propriedade de Imports.
Os métodos em Imports são usados para:
Adicione System.Security à coleção de Imports usando Add.
Exiba o número de itens na coleção Importações usando a propriedade Count.
Exiba o nome dos itens na coleção Imports usando o método Item.
A seção de exemplo lista o código completo que inclui um bloco try-catch para o método inteiro.
Para compilar o suplemento, clique em Compilar Solução no menu Compilação.
Abra um projeto do Visual Basic no ambiente de desenvolvimento integrado (IDE) do Visual Studio.
No menu de Ferramentas , clique Gerenciador de Suplementos, e selecione o suplemento da caixa de diálogo Gerenciador de Suplementos . Clique OK para executar o suplemento.
Exemplo
O exemplo a seguir é um suplemento básico do Visual Studio que demonstra como usar a propriedade Imports usando a automação do Visual Studio.
using System;
using System;
using Extensibility;
using EnvDTE;
using EnvDTE80;
using System.Windows.Forms;
using VSLangProj;
using VSLangProj2;
using VSLangProj80;
using VSLangProj90;
using VSLangProj100;
public void OnConnection(object application,
ext_ConnectMode connectMode, object addInInst, ref Array custom)
{
_applicationObject = (DTE2)application;
_addInInstance = (AddIn)addInInst;
VBVSProj2Manip(_applicationObject);
}
public void VBVSProj2Manip(DTE2 dte)
{
try
{
Solution2 soln = (Solution2)_applicationObject.Solution;
String vbTemplatePath;
String vbPrjPath;
Project proj;
VSProject2 vsproj;
Imports impCollection;
// Make sure you create the folders that make up the file path
// on your computer. You can replace this with
// your own file path.
vbPrjPath = "C:\\UserFiles\\MyProjects\\MyTestProject";
// Get the project template path for a Visual Basic windows
// application.
vbTemplatePath = soln.GetProjectTemplate
("WindowsApplication.zip", "VisualBasic");
// Create a new Windows application by using the
// template obtained above.
soln.AddFromTemplate(vbTemplatePath, vbPrjPath,
"Test2VBProj", false);
proj = soln.Projects.Item(1);
// Cast to the VSProject2 object.
vsproj = (VSProject2)proj.Object;
// Add a reference to System.Security.dll.
MessageBox.Show("Adding a reference to System.Security.dll");
// Remove the <version number> in the following path
// and replace it with one of the version
// number folders that appear
// in <installation root>\WINDOWS\Microsoft.NET\Framework
// folder
vsproj.References.Add
("C:\\WINDOWS\\Microsoft.NET\\Framework\\
<version number>\\System.Security.dll");
vsproj.Refresh();
impCollection = vsproj.Imports;
MessageBox.Show("The number of imports in this project is: "
+ impCollection.Count.ToString() + "\n");
MessageBox.Show("Adding System.Security to the
Imports collection.");
impCollection.Add("System.Security");
MessageBox.Show("The number of imports in this project is now:
" + impCollection.Count.ToString() + "\n");
String temp = null;
for (int i = 1; i <= impCollection.Count; i++)
{
temp = temp + impCollection.Item(i).ToString() + "\n";
}
MessageBox.Show("The Imports in this project are:" + "\n"
+ temp);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Imports System
Imports Microsoft.VisualStudio.CommandBars
Imports Extensibility
Imports EnvDTE
Imports EnvDTE80
Imports VSLangProj
Imports VSLangProj2
Imports VSLangProj80
Imports VSLangProj90
Imports VSLangProj100
Public Sub OnConnection(ByVal application As Object, _
ByVal connectMode As ext_ConnectMode, ByVal addInInst As Object, _
ByRef custom As Array) Implements IDTExtensibility2.OnConnection
_applicationObject = CType(application, DTE2)
_addInInstance = CType(addInInst, AddIn)
VBVSProj2Manip(_applicationObject)
End Sub
Sub VBVSProj2Manip(ByVal dte As DTE2)
Try
Dim soln As Solution2 = CType(_applicationObject.Solution, _
Solution2)
Dim vbTemplatePath As String
Dim vbPrjPath As String
Dim proj As Project
Dim vsproj As VSProject2
Dim impCollection As [Imports]
' Create this or your own file path on your computer.
' The file path needs to exist before you run this add-in.
vbPrjPath = "C:\UserFiles\MyProjects\MyTestProject"
' Get the project template path for a Visual Basic
' Windows application.
vbTemplatePath = soln.GetProjectTemplate _
("WindowsApplication.zip", "VisualBasic")
' Create a new Windows Application by using the
' template obtained above.
soln.AddFromTemplate(vbTemplatePath, vbPrjPath, _
"Test2JSProj", False)
proj = soln.Projects.Item(1)
' Cast the project to a VSProject2.
vsproj = CType(proj.Object, VSProject2)
' Add a reference to System.Security.dll.
MsgBox("Adding a reference to System.Security.dll")
' Remove the <version number> in the following path
' and replace it with one of the version
' number folders that appear
' in <installation root>\WINDOWS\Microsoft.NET\Framework
' folder
vsproj.References.Add _
("C:\WINDOWS\Microsoft.NET\Framework\ _
<version number>\System.Security.dll")
impCollection = vsproj.Imports
MsgBox("The number of imports in this project is: " & vbCr _
& impCollection.Count.ToString())
MsgBox("Adding System.Security to the Imports collection.")
impCollection.Add("System.Security")
MsgBox("The number of imports in this project is now: " _
& vbCr & impCollection.Count.ToString())
Dim temp As String = ""
For i As Integer = 1 To impCollection.Count
temp = temp & impCollection.Item(i).ToString() & vbCr
Next i
MsgBox("The Imports in this project are:" & vbCr & temp)
Catch ex As System.Exception
MsgBox(ex.ToString)
End Try
End Sub
Compilando o código
Para compilar este código, crie um novo projeto do suplemento Visual Studio e substitua o código do método OnConnection com o código no exemplo. Para obter informações sobre como executar um suplemento, consulte Como controlar suplementos usando o Gerenciador de Suplementos.
Consulte também
Conceitos
Introdução ao objeto VSProject2