更新:2007 年 11 月
除了显示快捷键绑定外,还可以使用 Bindings 属性设置或更改 Visual Studio 命令的键绑定。请注意,更改键绑定时,它会替换以前的键绑定(旧的绑定将丢失)。而且,如果新的键绑定由另一个命令使用,则此键绑定将会从旧的命令中移除并重新分配给新的命令。
然而,有一种方法可以保留键绑定,使新的键绑定成为附加快捷键,而不会替换旧的键绑定。在主题 如何:保留现有命令键绑定 中介绍了这种方法。
![]() |
---|
显示的对话框和菜单命令可能会与“帮助”中的描述不同,具体取决于您的当前设置或版本。这些过程是使用现用的常规开发设置开发的。若要更改设置,请在“工具”菜单上选择“导入和导出设置”。有关更多信息,请参见 Visual Studio 设置。 |
过程
将命令绑定到快捷键
使用“Visual Studio 外接程序向导”创建一个新的外接程序。为项目命名,然后单击“确定”启动向导。
有关使用“Visual Studio 外接程序向导”的更多信息,请参见 如何:创建外接程序。
在“选择编程语言”页上选择“使用 Visual C# 创建外接程序”,以运行下面的 Visual C# 示例,或选择“使用 Visual Basic 创建外接程序”运行 Visual Basic 示例。
将下面的示例函数粘贴到“Visual Studio 外接程序向导”生成的代码的 Connect 类中。
在“选项”对话框的左窗格中,展开“环境”文件夹,然后选择“键盘”。
请确保在步骤 7 中重命名的 vsk 文件的名称出现在“应用以下其他键盘映射方案”下拉菜单中。
运行外接程序示例之前,请确保键盘绑定设置为“(默认)”。可以通过单击“选项”对话框的“键盘”窗格中的“重置”来执行此操作。
按照 如何:编译和运行自动化对象模型代码示例 中的描述从 OnConnection 方法调用函数。
生成外接程序。
若要运行外接程序,请单击“工具”菜单上的“外接程序管理器”,选择您创建的外接程序,再单击“确定”。
此时,该命令被绑定到单个全局快捷键上。可以通过按下 Ctrl+Shift+Alt+X 使“新建文件”对话框显示出来,对此键盘绑定进行测试。
示例
下面的外接程序示例演示如何将 File.NewFile 命令绑定到单个快捷键 (F2)。
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)
BindingsExample(_applicationObject)
End Sub
Sub BindingsExample(ByVal dte As DTE2)
Dim cmds As Commands
Dim cmd As Command
Try
' Set references to the Commands collection and the
' File.NewFile command.
cmds = DTE.Commands
cmd = cmds.Item("File.NewFile")
' Assigns the command (File.NewFile) globally to the F2 key.
cmd.Bindings = "Global::F2"
MsgBox("key remapped")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
public void OnConnection(object application, ext_ConnectMode
connectMode, object addInInst, ref Array custom)
{
_applicationObject = (DTE2)application;
_addInInstance = (AddIn)addInInst;
BindingsExample(_applicationObject);
}
public void BindingsExample(DTE2 dte)
{
Commands cmds;
Command cmd;
try
{
// Set references to the Commands collection and the
// File.NewFile command.
cmds = dte.Commands;
cmd = cmds.Item("File.NewFile", 1);
// Assigns the command (File.NewFile) globally to the F2 key.
cmd.Bindings = "Global::F2";
System.Windows.Forms.MessageBox.Show("key remapped");
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
}
}