System.Windows.Clipboard 和 MS Office 应用程序

System.Windows.Clipboard and MS Office applications

我目前正在使用 System.Windows.Clipboard 来:设置一些文本,使用 control+V 调用 SendInput,最后恢复之前的剪贴板。

这适用于大多数应用程序,但在 Microsoft 的 Office 应用程序中,发送输入会导致恢复以前的剪贴板。我假设这与 SendInput 方法的延迟有关,所以我在恢复之前添加了等待时间并解决了大多数用户的问题,但用户的 Outlook 仍在恢复以前的剪贴板。

有没有比下面更好的方法?

 try
    {
      //method that uses GetDataObject and stores it to be restored
      _clipboard.Acquire();

      try
         {
            _clipboard.SetText(ClipboardText);

            //a wrapper for SendInput()
            SendInputWrapper.SendKeyCombination(new KeyCode(VirtualKeyShort.Control),
                                        new KeyCode(VirtualKeyShort.KeyV));
         }
         finally
         {
          //without this pause word and outlook would paste the original clipboard
          await Task.Delay(TimeSpan.FromMilliseconds(200));
          
          //wrapper method for Clipboard.SetDataObject() using the above stored 
            clipboard
          _clipboard.Restore();
          }
     }
     catch (Exception ex)
     {
       _log.Error("Error caught pasting text", ex);
     }

虽然它没有回答我对 Offices Clipboard 缓冲区的直接问题,但我现在使用的解决方案是使用 Word.Interop:

        var currentSelection = _word.Selection;

        // Store the user's current Overtype selection
        var userOvertype = _word.Options.Overtype;

        // Make sure Overtype is turned off.
        if (_word.Options.Overtype) _word.Options.Overtype = false;

        // Test to see if selection is an insertion point.
        if (currentSelection.Type == WdSelectionType.wdSelectionIP)
            currentSelection.TypeText(text);
        else if (currentSelection.Type == WdSelectionType.wdSelectionNormal)
        {
            // Move to start of selection.
            if (_word.Options.ReplaceSelection)
            {
                object direction = WdCollapseDirection.wdCollapseStart;
                currentSelection.Collapse(ref direction);
            }

            currentSelection.TypeText(text);
        }

        // Restore the user's Overtype selection
        _word.Options.Overtype = userOvertype;