如何:将命令绑定到单个快捷键

除了显示快捷键绑定外,还可以使用 Bindings 属性设置或更改 Visual Studio 命令的键绑定。 请注意,更改键绑定时,它会替换以前的键绑定(旧的绑定将丢失)。 而且,如果新的键绑定由另一个命令使用,则此键绑定将会从旧的命令中移除并重新分配给新的命令。

然而,有一种方法可以保留键绑定,使新的键绑定成为附加快捷键,而不会替换旧的键绑定。 在主题如何:保留现有键盘快捷键中介绍了这种方法。

备注

显示的对话框和菜单命令可能会与“帮助”中的描述不同,具体取决于您现用的设置或版本。这些过程是在“常规开发设置”处于活动状态时开发的。若要更改设置,请在“工具”菜单上选择“导入和导出设置”。有关更多信息,请参见Visual Studio 设置

过程

将命令绑定到快捷键

  1. 使用**“Visual Studio 外接程序向导”创建新的外接程序。 为项目命名,并单击“确定”**以启动该向导。

    有关使用**“Visual Studio 外接程序向导”**的更多信息,请参见 如何:创建外接程序

  2. 在**“选择编程语言”页上选择“使用 Visual C# 创建外接程序”,以运行下面的 Visual C# 示例,或选择“使用 Visual Basic 创建外接程序”**运行 Visual Basic 示例。

  3. 将下面的示例函数粘贴到**“Visual Studio 外接程序向导”**生成的代码的 Connect 类中。

  4. 使用 OnConnection 方法,如如何:编译和运行自动化对象模型代码示例中所述。

  5. 生成并运行外接程序。

    按 F2 键运行**“File.Newfile”**命令

示例

下面的外接程序示例演示如何将 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);
    }
}

请参见

任务

如何:将一个命令绑定到多个键盘快捷键

如何:保留现有键盘快捷键

概念

Bindings 属性的参数格式

其他资源

将外接程序命令绑定到键