Archive for 一月 17th, 2007


Chui-Wen Chiu(Arick)
MSN SpaceGoogle DocGoogle Blog

本文主要是教導你如何建立一個簡單的 Visual Studio Add-in。

建立 Visual Add-in 框架
首先建立 Visual Studio Add-in 專案:File | New | Project | Other Project Types | Extensibility | Visual Studio Add-in,設定如下

將功能選項移到 View
預設情況下,每一個 Visual Studio Add-in 都會放置在 Tools 選項下,如果要移到 View 選項下,我們可以到 Connect.cs 的 OnConnection 事件中找出如下的程式片段(L36-L52)

                    //If you would like to move the command to a different menu, change the word "Tools" to the
                    //  English version of the menu. This code will take the culture, append on the name of the menu
                    //  then add the command to that menu. You can find a list of all the top-level menus in the file
                    //  CommandBar.resx.
                    ResourceManager resourceManager = new ResourceManager("MyAddin1.CommandBar", Assembly.GetExecutingAssembly());
                    CultureInfo cultureInfo = new System.Globalization.CultureInfo(_applicationObject.LocaleID);
                    string resourceName = String.Concat(cultureInfo.TwoLetterISOLanguageName, "Tools");
                    toolsMenuName = resourceManager.GetString(resourceName);
                    //We tried to find a localized version of the word Tools, but one was not found.
                    //  Default to the en-US word, which may work for the current culture.
                    toolsMenuName = "Tools";

當使用者點選你 Add-in 選項時,會觸發 Exec 事件,要處理自己的 Add-In 功能,請找出下面的片段

        public void Exec(string commandName, vsCommandExecOption executeOption, ref object varIn, ref object varOut, ref bool handled)
            handled = false;
            if(executeOption == vsCommandExecOption.vsCommandExecOptionDoDefault)
                if(commandName == "MyAddin1.Connect.MyAddin1")
                    TextSelection sel = (TextSelection)_applicationObject.ActiveDocument.Selection;

                    if (!String.IsNullOrEmpty(sel.Text)) {
                        String[] dataSet = sel.Text.Split(new char[] { ‘=’ });
                        if (dataSet.Length == 2) {
                            sel.Text = dataSet[1] + " = " + dataSet[0];

                    handled = true;

黃色標記區是判斷是否屬於自己的 Add-in 命令,紅色區域是 Add-in 實作,上述實作是將目前選取字串中,如果包含一個 = 字元時,將 = 兩端的字串交換。如果想要控制 IDE,首先必須先取得 EnvDTE80.DTE2 型態的物件,在 Visual Studio Add-ins 專案中,已經預先定義了一個 _applicationObject 成員變數,你可以直接透過這個變數來控制 IDE。


[1] http://www.codeproject.com/useritems/vstoolwindow.asp

Read Full Post »