How to Change Ctrl+C in Visual Studio 2017 to Copy Word, Not Entire Line

自古美人都是妖i 提交于 2019-12-06 04:58:30

To copy the word the caret is on, you can assign a shortcut to the following Visual Commander (developed by me) command (language C#):

public class C : VisualCommanderExt.ICommand
{
    public void Run(EnvDTE80.DTE2 DTE, Microsoft.VisualStudio.Shell.Package package) 
    {
        this.DTE = DTE;
        EnvDTE.TextSelection ts = TryGetFocusedDocumentSelection();
        if (ts != null && ts.IsEmpty)
            CopyWord(ts);
        else if (IsCommandAvailable("Edit.Copy"))
            DTE.ExecuteCommand("Edit.Copy");
    }

    private void CopyWord(EnvDTE.TextSelection ts)
    {
        EnvDTE.EditPoint left = ts.ActivePoint.CreateEditPoint();
        left.WordLeft();

        EnvDTE.EditPoint right = ts.ActivePoint.CreateEditPoint();
        right.WordRight();

        System.Windows.Clipboard.SetText(left.GetText(right));
    }

    private EnvDTE.TextSelection TryGetFocusedDocumentSelection()
    {
        try
        {
            return DTE.ActiveWindow.Document.Selection as EnvDTE.TextSelection;
        }
        catch(System.Exception)
        {
        }
        return null;
    }

    private bool IsCommandAvailable(string commandName)
    {
        EnvDTE80.Commands2 commands = DTE.Commands as EnvDTE80.Commands2;
        if (commands == null)
            return false;
        EnvDTE.Command command = commands.Item(commandName, 0);
        if (command == null)
            return false;
        return command.IsAvailable;
    }

    private EnvDTE80.DTE2 DTE;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!