Ответ 1
Вы можете удалить определенные привязки клавиш в соответствии с: Конфигурационный файл привязки ключей Visual Studio
К сожалению, у меня нет и IntelliJ и ReSharper, чтобы проверить, работает ли он. Если это так, было бы неплохо сделать это с помощью DTE, но это решение выходит за рамки DTE и будет тривиально с помощью System.IO.File.
UPDATE:
Вопрос: Как программно использовать reset схему клавиатуры VisualStudio с помощью DTE? Мне действительно нужна команда запуска кнопки reset в Options | Среда | Диалоговое окно клавиатуры.
К сожалению, вы не можете сделать это (AFAIK), потому что сброс ярлыков клавиатуры выходит за рамки DTE.
Если вы настроите проект VS Addon под названием "ResetKeyBoard" и поместите точку прерывания в метод Exec
, вы увидите, что DTE не захватывает какие-либо события в Visual Studio, когда вы находитесь в окне "Параметры инструментов", t через объектную модель DTE:
public void Exec(string commandName, vsCommandExecOption executeOption, ref object varIn, ref object varOut, ref bool handled)
Это также может быть продемонстрировано с помощью записи макроса, записанные команды работают настолько глубоко, что открывается диалоговое окно Option (независимо от того, какие настройки вы меняете внутри):
Public Module RecordingModule
Sub TemporaryMacro()
DTE.ExecuteCommand("Tools.Options")
End Sub
End Module
Я научился открывать вкладку "Клавиатура" в окне "Параметры" напрямую, но с его модального диалога вы даже не можете использовать SendKeys для нажатия кнопки reset:
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}");
Последняя опция DTE, которую я пробовал (без везения), использует Commands.Raise
, снова вы не можете углубиться, чем открывать опции "Инструменты" или, по крайней мере, если вы можете его недокументированные.
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);
Обходные:
a) Я не рекомендую вам заменять файл Visual С# 2005.vsk, но если вы хотите изучить его этот файл:
C:\Program Files (x86)\Microsoft Visual Studio 1X.0\Common7\IDE\Visual C# 2005.vsk
Вы не можете программно изменить настройки для схемы сопоставления клавиатуры по умолчанию. Чтобы изменить настройки, сохраните копию схемы сопоставления клавиатуры по умолчанию в Клавиатуре node в диалоговом окне "Параметры". Затем вы можете изменить настройки в этой схеме сопоставления.
Я не рекомендую и не поощряю этот метод, его плохое программирование, и вы можете уничтожить кого-то быстрые клавиши!
b) Другим способом может быть создание собственного файла VSK и установка его в файле currentSettings.vssettings:
</ScopeDefinitions>
<ShortcutsScheme>Visual C# JT</ShortcutsScheme>
</KeyboardShortcuts>
Перед тем, как изменить его, обязательно создайте резервную копию файла currentSettings.vssettings.
c) Это приводит к предложению Криса Дунауэя, в котором вы создаете файл vssettings (чисто содержащий сочетания клавиш) и импортируете его в reset быстрые клавиши. Я понимаю, что ярлыки по умолчанию не сохраняются, однако вот какой-то код, который вы можете использовать с DTE для экспорта команд, для вставки в новый файл vssettings для импорта:
//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>");
Как только вы их получите, их легко импортировать в:
_applicationObject.ExecuteCommand("Tools.ImportandExportSettings", "/import:\"KeyboardOnly-Exported-2016-08-29.vssettings\"");
РЭС:
Советы и подсказки IDE Visual Studio 2005
Как reset настройки визуальной студии для моих сохраненных настроек с помощью всего одного ярлыка?
Как удобно установить быстрые клавиши для Visual Studio 2010, особенно при использовании ReSharper?
Удалите привязку сочетания клавиш в Visual Studio с помощью макросов
http://vswindowmanager.codeplex.com/
Получить полный список доступных команд для DTE.ExecuteCommand
HOWTO: выполнить команду Guid и Id из пакета Visual Studio
HOWTO: Выполнить команду Guid и Id из надстройки Visual Studio
HOWTO: программно передать параметры из надстройки Visual Studio
И, наконец, это Джаред Пар:
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
}