以编程方式重置VisualStudio快捷方式 [英] Programmatically reset VisualStudio shortcuts

查看:72
本文介绍了以编程方式重置VisualStudio快捷方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于

确保在更改currentSettings.vssettings文件之前先对其进行备份.

c)这引出了Chris Dunaway的建议,您可以在其中创建一个vssettings文件(完全包含键盘快捷键),然后将其导入以重置键盘快捷键.我知道默认快捷方式没有保存,但是这是一些可以与DTE一起使用的代码,用于将命令导出,插入到新的vssettings文件中,然后导入:

 //注意,这是未经测试的代码!公共无效Exec(字符串commandName,vsCommandExecOption executeOption,ref对象varIn,ref对象varOut,ref bool处理){处理=假;if(executeOption == vsCommandExecOption.vsCommandExecOptionDoDefault){如果(commandName =="ResetKeyBoard.Connect.ResetKeyBoard"){System.Diagnostics.Debug.WriteLine(< UserShortcuts>");;foreach(_applicationObject.Commands中的命令c){如果(!string.IsNullOrEmpty(c.Name)){System.Array绑定= default(System.Array);绑定=(System.Array)c.Bindings;for(int i = 0; i< = bindings.Length-1; i ++){字符串范围= string.Empty;字符串keyShortCut = string.Empty;string [] binding = bindings.GetValue(i).ToString().Split(new string [] {"::"},StringSplitOptions.RemoveEmptyEntries);范围=绑定[0];keyShortCut =绑定[1];System.Diagnostics.Debug.WriteLine(< RemoveShortcut Command = \" ... \"Scope = \""+范围+" \>" + keyShortCut +</RemoveShortcut>");System.Diagnostics.Debug.WriteLine(<快捷方式命令= \""+ c.Name +" \范围= \""+范围+" \>" + keyShortCut +</快捷方式");}}}System.Diagnostics.Debug.WriteLine(</UserShortcuts>"); 

一旦找到它们,就可以轻松地将它们导入:

  _applicationObject.ExecuteCommand("Tools.ImportandExportSettings","/import:\" KeyboardOnly-Exported-2016-08-29.vssettings \"); 

参考:

Visual Studio 2005 IDE技巧和窍门

如何仅通过一个快捷方式将Visual Studio设置重置为我保存的设置?

如何设置视觉效果Studio 2010的键盘快捷键使用起来很舒适,尤其是在使用ReSharper时?

https://superuser.com/questions/914244/is-the-a-quick-way-to-delete-all-shortcuts-in-visual-studio-10

使用以下命令在Visual Studio中删除键盘快捷键绑定宏

http://vswindowmanager.codeplex.com/

获取DTE可用命令的完整列表.ExecuteCommand

如何:通过Visual Studio包中的Guid和Id执行命令

如何:通过Visual Studio加载项的Guid和Id执行命令

如何:以编程方式将参数传递给Visual Studio加载项中的命令

最后是贾里德·帕尔(Jared Par)的那张

https://github.com/jaredpar/VsVim/blob/master/Src/VsVimShared/Extensions.cs

 ///< summary>///安全地将此命令上的键盘绑定重置为提供的值///</summary>公共静态无效值SafeSetBindings(此DteCommand命令,IEnumerable< string>命令绑定){尝试{var bindings = commandBindings.Cast< object>().ToArray();command.Bindings =绑定;//Visual Studio中的某些命令根本不想拥有它们//键盘绑定已删除.让他们放弃控制权的唯一方法是//要求他们两次删除绑定.////这样的一个示例是SolutionExplorer.OpenFilesFilter.两者都有绑定//"Ctrl- [,O"和"Ctrl- [,Ctrl-O".要求它删除所有绑定将删除一个//但不是两者(至少直到您重新启动Visual Studio时,两者都将消失).如果//我们要求它删除绑定两次,但是它将按照预期的方式运行.if(bindings.Length == 0&& command.GetBindings().Count()!= 0){command.Bindings =绑定;}}捕获(异常){//几种实现,特别是Transact SQL,为此返回E_FAIL//手术.只需忽略故障并继续} 

There are two related questions about resetting VisualStudio keyboard scheme and importing VisualStudio settings. However, this doesn't seem to play nice all together.

I have two settings files containing shortcuts:

<!-- IntelliJ.vssettings -->   
<ShortcutsScheme>Visual C# 2005</ShortcutsScheme>
<UserShortcuts>
  <Shortcut Command="ReSharper.ReSharper_GotoNextHighlight" Scope="Global">F12</Shortcut>
</UserShortcuts>

<!-- ReSharper.vssettings -->   
<ShortcutsScheme>Visual C# 2005</ShortcutsScheme>
<UserShortcuts>
  <!-- Implicitly has F12 assigned to Edit.GoToDefinition -->
</UserShortcuts>

As you see ReSharper.vssettings doesn't really have the F12 shortcut assigned, since it is the default for VisualStudio. Importing that file, will not reapply the ShortcutsScheme, which is Visual Studio C# 2005 in both cases. This in turn results in the fact, that F12 keeps executing the GotoNextHighlight command. Same problem when just using the import dialog.

Using DTE as follows to reset the keyboard scheme also doesn't work:

var property = dte.Properties["Environment", "Keyboard"];
property.Item("SchemeName").Value = "(Default)";

Exporting the default settings doesn't work for the same reason. As shown here no shortcuts are exported.

Question therefore: How can I reset the VisualStudio keyboard scheme programmatically using DTE?

What I actually need is the command to trigger the Reset button in Options | Environment | Keyboard dialog.

解决方案

You can remove specific key bindings as per: Visual Studio key bindings configuration file

Unfortunately I dont have both IntelliJ and ReSharper to test if it works. If it does it'd be nice to do this using DTE however this solution is beyond the scope of DTE and would be trivial using System.IO.File.

UPDATE:

Question: How can I reset the VisualStudio keyboard scheme programmatically using DTE? What I actually need is the command to trigger the Reset button in Options | Environment | Keyboard dialog.

Unfortunately you cannot do it (AFAIK) because resetting the Keyboard Shortcuts is beyond the scope of DTE.

If you setup a VS AddIn Project called "ResetKeyBoard" and put a break point on the Exec method you will see DTE doesnt catch any Visual Studio events firing when you're inside the Tools Options window, they simply aren't exposed through the DTE Object model:

public void Exec(string commandName, vsCommandExecOption executeOption, ref object varIn, ref object varOut, ref bool handled)

This can also be demonstrated by Recording a Macro, the recorded commands only go so deep as to open the Option Dialog (no matter what settings you change inside):

Public Module RecordingModule
    Sub TemporaryMacro()
        DTE.ExecuteCommand("Tools.Options")
    End Sub
End Module

I did learn how to open the Keyboard tab of the Options window directly but since its a Modal Dialog you cant even use SendKeys to press the Reset button:

public void Exec(string commandName, vsCommandExecOption executeOption, ref object varIn, ref object varOut, ref bool handled)
        {
            handled = false;
            if(executeOption == vsCommandExecOption.vsCommandExecOptionDoDefault)
            {
                if(commandName == "ResetKeyBoard.Connect.ResetKeyBoard")
                {
                    _applicationObject.ExecuteCommand("Tools.Options", "BAFF6A1A-0CF2-11D1-8C8D-0000F87570EE");
                    System.Windows.Forms.SendKeys.Send("%e");
                    System.Windows.Forms.SendKeys.Send("{ENTER}");

The last DTE option I tried (without luck) is using Commands.Raise, again you cant get deeper than opening Tools Options or at least if you can its undocumented.

public void Exec(string commandName, vsCommandExecOption executeOption, ref object varIn, ref object varOut, ref bool handled)
{
    handled = false;
    if(executeOption == vsCommandExecOption.vsCommandExecOptionDoDefault)
    {
        if(commandName == "ResetKeyBoard.Connect.ResetKeyBoard")
        {
            Commands cmds = _applicationObject.Commands;
            Command cmdobj = cmds.Item("Tools.Options");
            object customIn = null;
            object customOut = null;
            _applicationObject.Commands.Raise(cmdobj.Guid, cmdobj.ID, ref customIn, ref customOut);

Workarounds:

a) I dont encourage you to replace the Visual C# 2005.vsk file, but if you want to investigate its this file:

C:\Program Files (x86)\Microsoft Visual Studio 1X.0\Common7\IDE\Visual C# 2005.vsk

MSDN Warning

You cannot programmatically change the settings for the default keyboard mapping scheme. To change the settings, save a copy of the default keyboard mapping scheme in the Keyboard node in the Options dialog box. You can then change the settings in that mapping scheme.

I do not recommend or encourage this method, its bad programming and you could destroy someone's keyboard shortcuts!

b) Another way could be by creating your own VSK file and setting it in the currentSettings.vssettings:

    </ScopeDefinitions>
     <ShortcutsScheme>Visual C# JT</ShortcutsScheme>
    </KeyboardShortcuts>

Make sure you backup the currentSettings.vssettings file before changing it.

c) This leads back to Chris Dunaway's suggestion where you create a vssettings file (purely containing keyboard shortcuts) and import that in to reset the keyboard shortcuts. I realise the default shortcuts are not saved, however here is some code you can use with DTE to export the commands out, to insert into a new vssettings file to then import in:

//note, this is untested code!
public void Exec(string commandName, vsCommandExecOption executeOption, ref object varIn, ref object varOut, ref bool handled)
{
    handled = false;
    if(executeOption == vsCommandExecOption.vsCommandExecOptionDoDefault)
    {
        if(commandName == "ResetKeyBoard.Connect.ResetKeyBoard")
        {
            System.Diagnostics.Debug.WriteLine("<UserShortcuts>");
            foreach (Command c in _applicationObject.Commands)
            {
                if (!string.IsNullOrEmpty(c.Name))
                {
                    System.Array bindings = default(System.Array);
                    bindings = (System.Array)c.Bindings;
                    for (int i = 0; i <= bindings.Length - 1; i++)
                    {
                        string scope = string.Empty;
                        string keyShortCut = string.Empty;
                        string[] binding = bindings.GetValue(i).ToString().Split(new string[] {  "::" },StringSplitOptions.RemoveEmptyEntries );
                        scope = binding[0];
                        keyShortCut = binding[1];
                        System.Diagnostics.Debug.WriteLine("<RemoveShortcut Command=\"...\" Scope=\"" + scope + "\">" + keyShortCut + "</RemoveShortcut>");
                        System.Diagnostics.Debug.WriteLine("<Shortcut Command=\"" + c.Name + "\" Scope=\"" + scope + "\">" + keyShortCut + "</Shortcut>");
                    }
                }
            }
            System.Diagnostics.Debug.WriteLine("</UserShortcuts>");

Once you've got them out its easy to import them in:

_applicationObject.ExecuteCommand("Tools.ImportandExportSettings", "/import:\"KeyboardOnly-Exported-2016-08-29.vssettings\"");

REFs:

Visual Studio 2005 IDE Tips and Tricks

How to reset visual studio settings to my saved settings with just a single shortcut?

How does one set Visual Studio 2010 keyboard shortcuts comfortably, especially when using ReSharper?

https://superuser.com/questions/914244/is-there-a-quick-way-to-delete-all-shortcuts-in-visual-studio-10

Remove a keyboard shortcut binding in Visual Studio using Macros

http://vswindowmanager.codeplex.com/

Get full list of available commands for DTE.ExecuteCommand

HOWTO: Execute a command by Guid and Id from a Visual Studio package

HOWTO: Execute a command by Guid and Id from a Visual Studio add-in

HOWTO: Pass parameters programmatically to a command from a Visual Studio add-in

And finally this one by Jared Par:

https://github.com/jaredpar/VsVim/blob/master/Src/VsVimShared/Extensions.cs

/// <summary>
/// Safely reset the keyboard bindings on this Command to the provided values
/// </summary>
public static void SafeSetBindings(this DteCommand command, IEnumerable<string> commandBindings)
{
    try
    {
        var bindings = commandBindings.Cast<object>().ToArray();
        command.Bindings = bindings;

        // There are certain commands in Visual Studio which simply don't want to have their
        // keyboard bindings removed.  The only way to get them to relinquish control is to
        // ask them to remove the bindings twice.  
        //
        // One example of this is SolutionExplorer.OpenFilesFilter.  It has bindings for both
        // "Ctrl-[, O" and "Ctrl-[, Ctrl-O".  Asking it to remove all bindings will remove one
        // but not both (at least until you restart Visual Studio, then both will be gone).  If
        // we ask it to remove bindings twice though then it will behave as expected.  
        if (bindings.Length == 0 && command.GetBindings().Count() != 0)
        {
            command.Bindings = bindings;
        }
    }
    catch (Exception)
    {
        // Several implementations, Transact SQL in particular, return E_FAIL for this
        // operation.  Simply ignore the failure and continue
    }

这篇关于以编程方式重置VisualStudio快捷方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆