我试图创建一个捕获visual studio的edit.copy
命令的插件,如果没有选择任何内容,则跳过它。
我已经安装了Visual Studio SDK并创建了一个VSPackage项目。我的初始化方法看起来如下:
private EnvDTE.DTE m_objDTE = null;
protected override void Initialize()
{
Debug.WriteLine (string.Format(CultureInfo.CurrentCulture, "Entering Initialize() of: {0}", this.ToString()));
base.Initialize();
m_objDTE = (EnvDTE.DTE)GetService(typeof(EnvDTE.DTE));
m_objDTE.Events.CommandEvents.BeforeExecute += (
string Guid,
int ID,
Object CustomIn,
Object CustomOut,
ref bool CancelDefault
) =>
{
EnvDTE.Command objCommand;
string commandName = "";
objCommand = m_objDTE.Commands.Item(Guid, ID);
if (objCommand != null)
{
commandName = objCommand.Name;
if (string.IsNullOrEmpty(commandName))
{
commandName = "<unnamed>";
}
}
Debug.WriteLine("Before executing command with Guid=" + Guid + " and ID=" + ID + " named " + commandName);
};
}
打开解决方案时会调用Initialize()
方法,我已将[ProvideAutoLoad(UIContextGuids80.SolutionExists)]
标记添加到我的包中。但是当我执行操作时不会调用BeforeExecute,例如按下ctrl + c
这是一个命令,使用此代码我希望所有命令都在调试控制台中打印,为什么不发生这种情况?
答案 0 :(得分:2)
以下是我使用的代码:
using System;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.InteropServices;
using System.ComponentModel.Design;
using Microsoft.Win32;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Shell;
using EnvDTE;
namespace Dinto.NoCopy
{
[PackageRegistration(UseManagedResourcesOnly = true)]
[InstalledProductRegistration("#110", "#112", "1.0", IconResourceID = 400)]
[Guid(GuidList.guidNoCopyPkgString)]
[ProvideAutoLoad(UIContextGuids80.SolutionExists)]
public sealed class NoCopyPackage : Package
{
public NoCopyPackage()
{
Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "Entering constructor for: {0}", this.ToString()));
}
#region Package Members
private EnvDTE.DTE m_objDTE = null;
private CommandEvents _pasteEvent;
protected override void Initialize()
{
Debug.WriteLine (string.Format(CultureInfo.CurrentCulture, "Entering Initialize() of: {0}", this.ToString()));
base.Initialize();
m_objDTE = (DTE)GetService(typeof(DTE));
var pasteGuid = typeof(VSConstants.VSStd97CmdID).GUID.ToString("B");
var pasteID = (int)VSConstants.VSStd97CmdID.Copy;
_pasteEvent = m_objDTE.Events.CommandEvents[pasteGuid, pasteID];
_pasteEvent.BeforeExecute += CopyRead;
}
#endregion
private void CopyRead (
string Guid,
int ID,
Object CustomIn,
Object CustomOut,
ref bool CancelDefault
)
{
EnvDTE.Command objCommand;
string commandName = "";
objCommand = m_objDTE.Commands.Item(Guid, ID);
if (objCommand != null)
{
commandName = objCommand.Name;
}
if (commandName.Equals("Edit.Copy"))
{
TextSelection textSelection = (TextSelection)m_objDTE.ActiveDocument.Selection;
if (textSelection.IsEmpty)
{
CancelDefault = true;
}
}
}
}
}