标签:
1、新建一个插件工程,如图:查看工程右键->属性,如图:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using EnvDTE;
using EnvDTE80;
namespace AddinDemo
{
public partial class MyUserControl : UserControl
{
private DTE2 _applicationObject;
/// <summary>
/// VS的DTE2对象
///
public DTE2 ApplicationObject { set { _applicationObject = value; } }
public MyUserControl()
{
InitializeComponent();
}
}
}
再修改Connect.cs代码,如下:else if (connectMode == ext_ConnectMode.ext_cm_AfterStartup)
{
const string TOOLWINDOW_GUID = "{6CCD0EE9-20DB-4636-9149-665A958D8A9A}";
object myUserControlObject = null;
EnvDTE80.Windows2 windows2 = (EnvDTE80.Windows2)_applicationObject.Windows;
string assembly = System.Reflection.Assembly.GetExecutingAssembly().Location;
myToolWindow = windows2.CreateToolWindow2(_addInInstance, assembly,
typeof(MyUserControl).FullName, "AddinDemo", TOOLWINDOW_GUID, ref myUserControlObject);
// 设置DTE对象
MyUserControl muc = myToolWindow.Object as MyUserControl;
muc.ApplicationObject = _applicationObject;
}
此时运行,点击菜单没有效果,因为目前只是创建了对话框,没有显示它。public void Exec(string commandName, vsCommandExecOption executeOption, ref object varIn, ref object varOut, ref bool handled)
{
handled = false;
if(executeOption == vsCommandExecOption.vsCommandExecOptionDoDefault)
{
if(commandName == "AddinDemo.Connect.AddinDemo")
{
myToolWindow.Visible = true;
handled = true;
return;
}
}
}
此时再运行,对话框正常显示,效果如下:
/// <summary>
/// 在VS代码区光标处插入代码
///
///代码
private void Insert2VSDoc(string text)
{
try
{
if (string.IsNullOrEmpty(text))
return;
TextDocument textDocument = (TextDocument)null;
if (_applicationObject.ActiveDocument != null)
textDocument = _applicationObject.ActiveDocument.Object("TextDocument") as TextDocument;
if (textDocument == null || textDocument.Selection == null)
{
MessageBox.Show("不能插入代码,当前没有活动的文档!", "AddinDemo", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
else
{
textDocument.Selection.Insert(text, 1);
textDocument.Selection.SmartFormat();
}
}
catch (Exception ex)
{
MessageBox.Show("不能插入代码,当前不是代码视图!", "AddinDemo", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
private void button1_Click(object sender, EventArgs e)
{
Insert2VSDoc(textBox1.Text);
}
效果如下:
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:
原文地址:http://blog.csdn.net/zqp2013/article/details/47167445