【问题标题】:How to see Word document text changes in ThisDocument_New()如何在 ThisDocument_New() 中查看 Word 文档文本的变化
【发布时间】:2020-07-10 19:07:20
【问题描述】:

我正在考虑将我们所有的 Word 模板从 VBA 迁移到 VSTO,并且有以下问题:如何在 VSTO 项目中调试代码?

与 VBA 中的调试不同,在单步执行过程时,我看不到代码逐行执行的结果。

例如,我在 VS 2019 中构建了一个原型 Word 文档:

using ...;
namespace MyCompany.OfficeTemplates.MyTemplate
    {
        public partial class ThisDocument
        {

            private void ThisDocument_Startup(object sender, System.EventArgs e)
            {
            }

            private void ThisDocument_Shutdown(object sender, System.EventArgs e)
            {
            }

            private void ThisDocument_New()
            {
                var currentSelection = Application.Selection;
                currentSelection.TypeText("This text was added by using code.");
            }

            #region VSTO Designer generated code

            /// ...<summary>
            /// Required method for Designer support - do not modify
            /// the contents of this method with the code editor.
            /// </summary>
            private void InternalStartup()
            {
                this.Startup += new System.EventHandler(ThisDocument_Startup);
                this.Shutdown += new System.EventHandler(ThisDocument_Shutdown);
                this.New += new Microsoft.Office.Interop.Word.DocumentEvents2_NewEventHandler(this.ThisDocument_New);
            }

            #endregion

        }
    }

我计划在ThisDocument_New() 事件中添加更多代码(显示对话框、选择客户、选择语言和其他信息)。为什么当我使用调试器跳过命令 ...TypeText()... 时文本没有插入到 word 文档中?!?

而是在调试器离开ThisDocument_New()时插入?

当 ThisDocument_New() 不允许正确调试时,我遗漏了什么以及将我的代码放在哪里?

【问题讨论】:

    标签: debugging ms-word vsto


    【解决方案1】:

    在代码执行期间看不到发生了什么是 VSTO 的典型特征。调试与 VBA 不同 - 结果仅在代码完成后可见。无法改变这一点 - 这是事物的本质(.NET COM 交互)。

    我自己在开始使用 VSTO 时遇到了这个问题,并且必须学会解决它。

    一般来说,如果在故障排除期间需要查看发生了什么,我首先在 VBA 中进行测试,然后将该代码传输到 VSTO。

    如果有必要在代码运行时检查代码生成的值,我会粘贴一些 Debug.Print 行,以便在单步执行代码时在 Visual Studio 输出窗口中进行操作。

    还可以在单​​步执行代码时跟踪分配给对象的内容。

    【讨论】:

    • 感谢 Cindy 的回复,如果您必须先在 VBA 中测试代码然后将其移至 VSTO,那么从 VBA 切换到 VSTO 的动机是什么?
    • 一个人不必首先在 VBA 中测试代码 - 有时对“奇怪”情况进行故障排除或进行概念验证会更简单。我在 C# 中做了很多工作而没有从 VBA 迁移。选择 VBA 与 VSTO 的一些原因立即浮现在脑海中:1)项目的分发/维护; 2) 使用其中一个或另一个不可用的功能; 3) 安全考虑
    猜你喜欢
    • 1970-01-01
    • 2019-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多