Share via


방법: VSProject2 개체를 사용하여 Visual Basic 및 C# 프로젝트 조작

VSProject2 인터페이스는 Visual C# 및 Visual Basic 프로젝트와 관련된 속성 및 메서드에 액세스할 수 있도록 합니다. 또한 VSProject2DTEProject 속성을 통해 일반 환경 모델의 DTEProject 개체에 액세스할 수 있게 합니다.

VSProject2에 있는 대부분의 메서드와 속성은 Visual C# 및 Visual Basic 프로젝트에 똑같이 적용됩니다. 유일한 예외는 Imports 속성입니다. 이 속성은 Visual Basic에 적용되고 Imports 개체에 대한 액세스를 제공합니다. 자세한 내용은 방법: Visual Basic 프로젝트의 Imports 속성 조작을 참조하십시오. Events 속성을 사용하면 VSLangProjWebReferencesEventsReferencesEvents 같은 프로젝트별 이벤트에 액세스할 수 있습니다. 이벤트 처리 작업에 대한 내용은 다른 항목에서 다룹니다. 자세한 내용은 이벤트에 응답(Visual Basic 및 Visual C# 프로젝트)을 참조하십시오.

아래 단계에서는 일반 자동화 모델을 사용하여 프로그래밍 방식으로 Visual C# Windows 응용 프로그램을 만드는 방법을 보여 줍니다. VSProject2의 메서드와 속성은 작성된 프로젝트를 프로그래밍 방식으로 제어하는 데 사용됩니다.

참고

일부 Visual Studio 사용자 인터페이스 요소의 경우 다음 지침에 설명된 것과 다른 이름 또는 위치가 시스템에 표시될 수 있습니다.설치한 Visual Studio 버전과 사용하는 설정에 따라 이러한 요소가 결정됩니다.자세한 내용은 Visual Studio에서 개발 설정 사용자 지정을 참조하십시오.

VSProject2 개체를 사용하여 C# 프로젝트를 제어하려면

  1. Visual C#을 사용하여 Visual Studio 추가 기능 프로젝트를 만듭니다.

  2. 프로젝트 메뉴에서 참조 추가를 클릭하고 .NET 탭을 클릭한 다음 VSLangProj, VSLangProj2, VSLangProj80, VSLangProj90 및 VSLangProj100을 선택하고 확인을 클릭합니다.

  3. 컴퓨터에 다음 두 개의 폴더를 만듭니다.

    • <Installation Root>\UserFiles\MyProjects\MyTestProject.

    • <Installation Root>\UserFiles\MyKeyFiles.

      이 예제에서 <Installation Root>는 "C:"입니다.

  4. Connect.cs 파일의 맨 위에 다음과 같은 using 문을 추가합니다.

    using VSLangProj;
    using VSLangProj2;
    using VSLangProj80;
    using VSLangProj90;
    
  5. VSLangProj100을 사용하여 다음 메서드 호출을 OnConnection 메서드에 추가합니다.

    public void OnConnection(object application, 
    ext_ConnectMode connectMode, object addInInst, ref Array custom)
    {
        _applicationObject = (DTE2)application;
        _addInInstance = (AddIn)addInInst;
        CSVSProj2Manip(_applicationObject);
    }
    
  6. OnConnection 메서드 바로 아래 CSVSProj2Manip 메서드 선언을 추가합니다.

    public void CSVSProj2Manip(DTE2 dte)
    {
    }
    
  7. 메서드의 맨 위에 다음 선언을 추가합니다.

    Solution2 soln = (Solution2)_applicationObject.Solution;
    String csTemplatePath;
    String csPrjPath;
    Project proj;
    VSProject2 vsproj;
    String webServiceRef;
    BuildManager bldMgr;
    
  8. AddFromTemplate을 사용하여 Visual C# 프로젝트를 만듭니다.

    • 템플릿을 가져오는 구문은 EnvDTE80.Solution2.GetProjectTemplate("WindowsApplication.zip", "CSharp")입니다. 여기서 " WindowsApplication.zip " 이름은 <Installation Root>\Program Files\Microsoft Visual Studio 8\Common7\IDE\ProjectTemplates\CSharp\Windows\1033 폴더에 있는 WindowsApplication.zip 파일에서 가져온 것입니다. 모든 Visual Studio 프로젝트 형식에 대해 이 파일은 <Installation Root>\Program Files\Microsoft Visual Studio 8\Common7\IDE\ProjectTemplates\Language 폴더에 들어 있습니다. "CSharp"은 이 프로젝트가 Visual C# 프로젝트임을 나타냅니다.

    • Visual Basic Windows 응용 프로그램 프로젝트의 경우 구문은 EnvDTE80.Solution2.GetProjectTemplate("WindowsApplication.zip", "VisualBasic")입니다. Visual Basic 프로젝트의 경우 Windows 응용 프로그램 zip 파일 템플릿은 <Installation Root>\ Program Files\Microsoft Visual Studio 8\Common7\IDE\ProjectTemplates\VisualBasic\Windows\1033 폴더에 있습니다.

    // Make sure you create the folders that 
    // make up the file path
    // on your computer. You can replace 
    // this with your own file path.
    csPrjPath = "C:\\UserFiles\\MyProjects\\MyTestProject";
    // Get the project template path for a C# windows 
    // application.
    csTemplatePath = soln.GetProjectTemplate 
    ("WindowsApplication.zip", "CSharp");
    // Create a new windows application by using the 
    // template obtained above.
    soln.AddFromTemplate(csTemplatePath, csPrjPath,
     "Test2CSProj", false);
    
  9. VSProject2 메서드의 사용 방법을 보여 주는 다음 코드를 추가합니다.

    웹 서비스를 프로그래밍 방식으로 프로젝트에 추가하려면 코드에서 자리 표시자 텍스트인 <web service>를 실제 웹 서비스의 URL로 바꿔야 합니다. 웹 서비스 URL을 찾으려면 Visual Studio IDE(통합 개발 환경)에서 프로젝트를 열고, 프로젝트 메뉴에서 참조 추가를 클릭합니다. 참조 추가 대화 상자에서 UDDI 디렉터리 링크를 클릭하고 이 디렉터리를 사용하여 웹 서비스를 찾습니다.

    proj = soln.Projects.Item(1);
    // Cast the project as a 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");
    // Create a Web references folder.
    MessageBox.Show("Creating a Web references folder.");
    vsproj.CreateWebReferencesFolder();
    // Add a Web reference to the folder.
    MessageBox.Show("Adding a Web reference.");
    // Replace the placeholder, <web service>, with a
    // Web service URL.
    webServiceRef = "<web service>";
    vsproj.AddWebReference(webServiceRef);
    bldMgr = vsproj.BuildManager;
    Array monikers = null;
    // String moniker = null;
    String msg = null;
    Object obj = bldMgr.DesignTimeOutputMonikers;
    if (obj != null)
    {
        try
        {
            monikers = (System.Array)obj;
            foreach(String tempmoniker in monikers)
            {
                msg += bldMgr.BuildDesignTimeOutput
    (tempmoniker) + "\n";
            }
        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        MessageBox.Show("The build design-time output is:" 
    + "\n"  + msg);
    }
    // Change the MyHTML file name by using GetUniqueFilename.
    MessageBox.Show("Adding an HTML page named 'MyHTML'...");
    String itemTemplatePath = soln.GetProjectItemTemplate("HTMLPage",
     "CSharp");
    proj.ProjectItems.AddFromTemplate
    (itemTemplatePath, "MyHtml");
    MessageBox.Show("Renaming MyHtml' to 'MyTesthtml.htm'...");
    vsproj.Project.ProjectItems.Item("MyHtml").Name =
     vsproj.GetUniqueFilename(proj, "MyTesthtml", "htm");
    // Generate a key-pair file.
    MessageBox.Show("Generating a key-file...");
    vsproj.GenerateKeyPairFiles("C:\\UserFiles\\MyKeyFiles
    \\MyKeyText2.bin", "0");
    

    CSVSProj2Manip 메서드에서는 VSProject2 개체를 사용하여 다음 작업을 수행합니다.

    전체 메서드에 대한 try-catch 블록이 포함된 전체 코드는 예제 단원을 참조하십시오.

  10. 빌드 메뉴에서 솔루션 빌드를 클릭하여 추가 기능을 빌드합니다.

  11. Visual Studio IDE에서 Visual C# 프로젝트를 엽니다.

  12. 도구 메뉴에서 추가 기능 관리자를 클릭하고 추가 기능 관리자 대화 상자에서 추가 기능을 선택합니다. 확인을 클릭하여 추가 기능을 실행합니다.

  13. Sn.exe(강력한 이름 도구)를 사용하여 <Installation Root>\UserFiles\MyKeyFiles 폴더에서 생성한 키 쌍 파일을 봅니다.

예제

다음은 VSProject2 개체의 속성과 메서드를 사용하여 Visual C# 프로젝트를 만들고 조작하는 기본 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;
    CSVSProj2Manip(_applicationObject);
}
public void CSVSProj2Manip(DTE2 dte)
{
    try
    {
        Solution2 soln = (Solution2)_applicationObject.Solution;
        String csTemplatePath;
        String csPrjPath;
        Project proj;
        VSProject2 vsproj;
        String webServiceRef;
        BuildManager bldMgr;
        // Make sure you create the folders that make up the file path
        // on your computer.
        // You can replace this with your own file path.
        csPrjPath = "C:\\UserFiles\\MyProjects\\MyTestProject";
        // Get the project template path for a C# windows application.
        csTemplatePath = soln.GetProjectTemplate
("WindowsApplication.zip", "CSharp");
        // Create a new Windows application by using the template 
        // obtained above.
        soln.AddFromTemplate(csTemplatePath, csPrjPath,
 "Test2CSProj", false);
        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");
        // Create a Web references folder.
        MessageBox.Show("Creating a Web references folder.");
        vsproj.CreateWebReferencesFolder();
        // Replace the placeholder, <web service>, with a
        // Web service URL.
        MessageBox.Show("Adding a Web reference.");
        // Replace the placeholder, <web service>, with a
        // Web service URL.
        webServiceRef = "<web service>";
        vsproj.AddWebReference(webServiceRef);
        bldMgr = vsproj.BuildManager;
        Array monikers = null;
        // String moniker = null;
        String msg = null;
        Object obj = bldMgr.DesignTimeOutputMonikers;
        if (obj != null)
        {
            try
            {
                monikers = (System.Array)obj;
                foreach(String tempmoniker in monikers)
                {
                    msg += bldMgr.BuildDesignTimeOutput(tempmoniker) 
+ "\n";
                }
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            MessageBox.Show("The build design-time output is:" + "\n"  
+ msg);
        }
        // Change the MyHTML file name by using GetUniqueFilename.
        MessageBox.Show("Adding an HTML page named 'MyHTML'...");
        String itemTemplatePath =
 soln.GetProjectItemTemplate("HTMLPage", "CSharp");
        proj.ProjectItems.AddFromTemplate(itemTemplatePath, "MyHtml");
        MessageBox.Show("Renaming MyHtml' to 'MyTesthtml.htm'...");
        vsproj.Project.ProjectItems.Item("MyHtml").Name =
 vsproj.GetUniqueFilename(proj, "MyTesthtml", "htm");
        // Generate a key-pair file.
        MessageBox.Show("Generating a key-file...");
        vsproj.GenerateKeyPairFiles
("C:\\UserFiles\\MyKeyFiles\\MyKeyText2.bin", "0");
    }
    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)
    CSVSProj2Manip(_applicationObject)
End Sub
Sub CSVSProj2Manip(ByVal dte As DTE2)
    Try
        Dim soln As Solution2 = CType(_applicationObject.Solution, _
         Solution2)
        Dim csTemplatePath As String
        Dim csPrjPath As String
        Dim proj As Project
        Dim vsproj As VSProject2
        Dim webServiceRef As String
        Dim bldMgr As BuildManager
        ' Create this or your own file path on your computer.
        ' The file path must exist before you run this add-in.
        csPrjPath = "C:\UserFiles\MyProjects\MyTestProject"
        ' Get the project template path for a C# windows application.
        csTemplatePath = soln.GetProjectTemplate _
        ("WindowsApplication.zip","CSharp")
        ' Create a new Windows Application
        ' using the template obtained above.
        soln.AddFromTemplate(csTemplatePath, csPrjPath _
        , "Test2CSProj", 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")
        ' Create a Web references folder.
        MsgBox("Creating a Web references folder.")
        vsproj.CreateWebReferencesFolder()
        ' Replace the placeholder, <web service>, with a
        ' web service URL.
        webServiceRef = "<web service>"
        MsgBox("Adding a Web reference.")
        vsproj.AddWebReference(webServiceRef)
        bldMgr = vsproj.BuildManager
        Dim monikers As String() = Nothing
        Dim moniker As String = Nothing
        Dim msg As String = ""
        Dim obj As Object = bldMgr.DesignTimeOutputMonikers
        If Not obj Is Nothing Then
            Try
                monikers = CType(obj, String())
                For Each moniker In monikers
                    msg &= bldMgr.BuildDesignTimeOutput(moniker) + vbCr
                Next
            Catch ex As System.Exception
                MsgBox(ex.ToString)
            End Try
            MsgBox("The build design-time output is:" + vbCr + msg)
        End If
        ' Use the UniqueFilename to rename a new project item.
        MsgBox("Adding an HTML page called 'MyHTML'...")
        Dim itemTemplatePath As String = _
        soln.GetProjectItemTemplate("HTMLPage", "CSharp")
        proj.ProjectItems.AddFromTemplate(itemTemplatePath, "MyHtml")
        MsgBox("Renaming MyHtml' to 'MyTesthtml.htm'...")
        vsproj.Project.ProjectItems.Item("MyHtml").Name = _
        vsproj.GetUniqueFilename(proj, "MyTesthtml", "htm")
        ' Generate a key-pair file.
        vsproj.GenerateKeyPairFiles _
        ("C:\UserFiles\MyKeyFiles\MyKeyText2.bin", "0")
    Catch ex As System.Exception
        MsgBox(ex.ToString)
    End Try
End Sub

코드 컴파일

이 코드를 컴파일하려면 새 Visual Studio 추가 기능 프로젝트를 만들고 OnConnection 메서드의 코드를 예제의 코드로 바꿉니다. 추가 기능을 실행하는 방법에 대한 내용은 방법: 추가 기능 관리자를 사용하여 추가 기능 제어를 참조하십시오.

참고 항목

개념

VSProject2 개체 소개

기타 리소스

Visual Basic 및 Visual C# 프로젝트 확장