方法 : VSProject2 オブジェクトを使用して Visual Basic プロジェクトと C# プロジェクトを操作する

更新 : 2007 年 11 月

VSProject2 インターフェイスは、Visual C#、Visual Basic、および Visual J# の各プロジェクトに固有のメソッドおよびプロパティにアクセスできます。また、VSProject2 は、DTE プロパティおよび Project プロパティを使用して一般的な環境モデルの DTE オブジェクトおよび Project オブジェクトにもアクセスできます。

VSProject2 のほとんどのメソッドおよびプロパティは、Visual C#、Visual Basic、および Visual J# の各プロジェクトに一様に適用されます。ただし、Imports プロパティだけは例外です。このプロパティは、Visual Basic に適用され、Imports オブジェクトにアクセスできます。詳細については、「方法 : Visual Basic プロジェクトの Imports プロパティを操作する」を参照してください。Events プロパティにより、VSLangProjWebReferencesEventsReferencesEvents など、プロジェクト固有のイベントにアクセスできるようになります。イベント処理タスクについては、他のトピックで説明します。詳細については、「イベントへの応答 (Visual Basic および Visual C# プロジェクト)」を参照してください。

次の手順では、一般的なオートメーション モデルを使用して、プログラムで Visual C# Windows アプリケーションを作成する方法について説明します。VSProject2 のメソッドおよびプロパティは、作成したプロジェクトをプログラムで制御する場合に使用します。

ms228960.alert_note(ja-jp,VS.90).gifメモ :

使用している設定またはエディションによっては、表示されるダイアログ ボックスやメニュー コマンドがヘルプに記載されている内容と異なる場合があります。ここに記載されている手順は、全般的な開発設定が適用されているものとして記述されています。設定を変更するには、[ツール] メニューの [設定のインポートとエクスポート] をクリックします。詳細については、「Visual Studio の設定」を参照してください。

VSProject2 オブジェクトを使用して C# プロジェクトおよび J# プロジェクトを制御するには

  1. Visual C# を使用して、Visual Studio アドイン プロジェクトを作成します。

  2. [プロジェクト] メニューの [参照の追加] をクリックし、[.NET] タブをクリックします。[VSLangProj]、[VSLangProj2]、および [VSLangProj80] を選択し、[OK] をクリックします。

  3. コンピュータ上に次の 2 つのフォルダを作成します。

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

    • <Installation Root>\UserFiles\MyKeyFiles。

      この例では、<Installation Root> は "C:" になります。

  4. 次の using ステートメントを Connect.cs ファイルの先頭に追加します。

    using VSLangProj;
    using VSLangProj2;
    using VSLangProj80;
    
  5. 次のメソッド呼び出しを OnConnection メソッドに追加します。

    public void OnConnection(object application, 
    ext_ConnectMode connectMode, object addInInst, ref Array custom)
    {
        _applicationObject = (DTE2)application;
        _addInInstance = (AddIn)addInInst;
        CSVSProj2Manip(_applicationObject);
    }
    
  6. CSVSProj2Manip メソッドの宣言を OnConnection メソッドの直後に追加します。

    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 フォルダにあります。

    • Visual J# Windows アプリケーション プロジェクトの場合、構文は EnvDTE80.Solution2.GetProjectTemplate("WindowsApplication.zip", "JSharp") です。Visual J# プロジェクトでは、Windows アプリケーション テンプレートの zip ファイルは、<Installation Root>\Program Files\Microsoft Visual Studio 8\Common7\IDE\ProjectTemplates\JSharp\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 サービスをプロジェクトに追加するには、コード内のプレースホルダ テキストである <web service> を、実際の Web サービスの URL で置き換える必要があります。Web サービスの URL を検索するには、Visual Studio 統合開発環境 (IDE: Integrated Development Environment) でプロジェクトを開きます。[プロジェクト] メニューの [Web 参照の追加] をクリックします。[参照の追加] ダイアログ ボックスで、[UDDI ディレクトリ] リンクをクリックし、ディレクトリを使用して Web サービスを検索します。

    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 オブジェクトを使用して次の操作を行います。

    • References を使用して、System.Security.dll への参照を追加します。

    • CreateWebReferencesFolder を使用して、Web 参照フォルダを作成します。

    • AddWebReference を使用して、Web 参照を追加します。

    • BuildManager プロパティで取得したメソッドを使用して、ビルド デザイン時のモニカを表示します。

    • GetUniqueFilename メソッドを使用して、新しいプロジェクト項目の名前を変更します。CSVSProj2Manip メソッドは、AddFromTemplate を使用してプロジェクト項目を追加します。

    • GenerateKeyPairFiles メソッドを使用して、キー ペア ファイルを生成します。

    以下の使用例では、メソッド全体に try-catch ブロックを含めた完全なコードを示します。

  10. アドインをビルドするには、[ビルド] メニューの [ソリューションのビルド] をクリックします。

  11. Visual Studio IDE で、Visual C#、Visual J#、または Visual Basic のプロジェクトを開きます。

  12. [ツール] メニューの [アドイン マネージャ] をクリックし、[アドイン マネージャ] ダイアログ ボックスからアドインを選択します。[OK] をクリックしてアドインを実行します。

  13. <Installation Root>\UserFiles\MyKeyFiles フォルダに生成したキー ペア ファイルを、厳密名ツール (Sn.exe) を使用して表示します。

使用例

基本的な Visual Studio アドインの例を次に示します。この例では、Visual C# プロジェクトを作成し、VSProject2 オブジェクトのプロパティおよびメソッドを使用して操作します。

using System;
using System;
using Extensibility;
using EnvDTE;
using EnvDTE80;
using System.Windows.Forms;
using VSLangProj;
using VSLangProj2;
using VSLangProj80;
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
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# の各プロジェクトの拡張