如何捕获Word中的拖放事件?
我正在为 Microsoft Word 创建一个加载项(使用 C#),并希望在将某些文本/图像等从任何源拖放到 Word 中时触发某些功能。所以基本上我想在Word中捕获Drop事件。但是我找不到任何对此有帮助的 Word API。你能帮忙吗?
I am creating an Add-in (using C#) for Microsoft Word and want to trigger some functionality when some text/image etc. is dragged from any source and dropped into Word. So basically I want to trap the Drop event in Word. However I am not able to find any Word API which helps in this. Can you please help in this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不存在这样的野兽。
您可以期望的最好(简单)方法是观察 DocumentChange 事件,并尝试监视更改的内容(它将位于“选择”的当前位置)。
一种更可靠的方法是对主 Word 窗口进行子类化,并监视正在交换的任何拖/放消息,并根据需要拦截它们。
No such beast exists.
The best (easy-ish) approach you can hope for is to watch the DocumentChange event, and try to monitor what changed (it'll be located at the current location of the "Selection").
A much hardy way would be to subclass the main Word Window and watch for whatever Drag/drop messages are being exchanged, and intercept them as appropriate.
SelectionChange 事件有时可以用于此目的。有时,因为选择并不总是包含删除的内容。例如,如果将图像放入文档中,则不会选择该图像。
The SelectionChange event can sometimes be used for this. Sometimes, because the selection will not always contain the dropped content. E.g. if you drop an image into a document, the image will not be selected.
更好的替代方法是使用覆盖在 Word 窗口顶部的透明窗口。该窗口在拖动过程开始时启动,并放置在文档窗口的顶部。然后,该窗口而不是 Word 接收放置操作,因此您可以准确地知道传入的内容以及放置的位置。然后,您可以将这些位置坐标转换为相应的文档位置(使用
Window
类的RangeFromPoint()
方法),并对删除的数据执行任何您需要执行的操作。之后,您只需隐藏透明窗口,一切都会恢复正常。此方法的完整实现以及源代码可在 这篇优秀的 MSDN 文章。
A better alternate is to use a transparent window that you overlay on top of the Word window. This window is initiated when the drag process starts and placed on top of the document window. The drop operation is then received by this window instead of Word, so you know exactly what came in and at which location it was dropped. You can then translate these location coordinates into corresponding document location (using
RangeFromPoint()
method ofWindow
class) and do whatever you need to do with the dropped data. After this you simply hide your transparent window and everything goes back to normal.A complete implementation of this approach along with source code is available in this excellent MSDN article.