0

I write an add-in for word in c#.
I want to hook keyboard and catch ctrl-c and read text copied to clipboard.
My add-in could found ctrl-c by using code below,



    //C# code:
    private void ThisAddIn_Startup(object sender, System.EventArgs e)
    {
        .
        .
        .
         Application.KeyBindings.Add(Word.WdKeyCategory.wdKeyCategoryCommand, "KeyCode1",
                    Application.BuildKeyCode(Word.WdKey.wdKeyControl , Word.WdKey.wdKeyAlt , Word.WdKey.wdKeyD));
    }

    public void CallKey(int i)
    {
            switch (i)
            {
                case 1:
                    MessageBox.Show("Ctrl+C");
                    break;
            }
        }
    //VBA code:
    Function GetAddin() As Object
    On Error Resume Next

    Dim addIn As COMAddIn
    Dim automationObject As Object
    Set addIn = Application.COMAddIns(“WordKeyBinding”)
    Set automationObject = addIn.Object
    Set GetAddin = automationObject
    End Function

    Public Sub KeyCode1()
    On Error Resume Next
    GetAddin.CallKey 1
    End Sub

Now my problem is when I press ctrl-c, the message box is displayed but nothing copy to clipboard! what should I do?

nazanin
  • 478
  • 5
  • 15

1 Answers1

2

You could try repurpose commands in VSTO which works for any copy either through ribbon, right click context menu or shortcut (ctrl + c).

**

Ribbon.xml

**

<?xml version="1.0" encoding="UTF-8"?>
<customUI xmlns="http://schemas.microsoft.com/office/2009/07/customui" >
  <commands>
    <command idMso="Copy" onAction="CustomCopy"/>    
  </commands>
</customUI>

Ribbon.cs

 private Word.Application wordApp = Globals.ThisAddIn.Application;
    public void CustomCopy(Office.IRibbonControl control, bool cancelDefault)
    {
        //wordApp.Selection - returns the selction of copy
        //Or use Clipboard.GetData()
        //https://msdn.microsoft.com/en-us/library/system.windows.forms.clipboard.getdata(v=vs.110).aspx
        wordApp.Selection.Copy();
    }

More about repurpose in Office 2007 in here. But it also works with Word 2013.

Kiru
  • 3,489
  • 1
  • 25
  • 46
  • 1
    `Keybindings` only works in VBA code that resides inside a Word document. It can't be used by "outside" code, such as VSTO. For that you need keyboard hooking, using the Windows API. Here are some links with code: https://social.msdn.microsoft.com/Forums/office/en-US/c3c64a28-b9d3-41a8-bb08-8c261500f116/global-keyboard-hook-callback-function-not-responding-to-any-key-stroke-in-office-2013-word?forum=worddev, http://stackoverflow.com/questions/8120199/how-to-get-the-keypress-event-from-a-word-2010-addin-developed-in-c, http://stackoverflow.com/questions/33451907/word-addin-local-keyboard-hook – Cindy Meister May 03 '16 at 05:42