0

最近,我更新了我的Visual Studio并开始使用扩展的宏浏览器。如何在Visual Studio宏中提供时间延迟

我试图使用一个示例宏“删除和排序所有”,但我意识到如果我有一个打开的文档,它不会运行。因此,我关闭了所有打开的文档,并再次尝试打开所有文档并关闭它们,但它也不起作用。

问题是在文档完全加载之前执行的命令。如果有事件或计时器可以帮助等待文档加载完毕,问题就会解决。

这是我的代码。标志着我在这里我要添加等待功能:

function formatFile(file) { 
    dte.ExecuteCommand("View.SolutionExplorer"); 
    if (file.Name.indexOf(".cs", file.Name.length - ".cs".length) !== -1) { 
     file.Open(); 
     file.Document.Activate(); 

//here i want to wait for 1 second 
     dte.ExecuteCommand("Edit.RemoveAndSort"); 

     file.Document.Save(); 
     file.Document.Close(); 
    } 
} 

我明白任何形式的帮助。

在GitHub上宏资源管理:https://github.com/Microsoft/VS-Macros

+0

感谢亲爱@Peh。但据我所知,宏主要语言是vba。我错了吗? – David

+0

谢谢你们。我删除了vba标签。但我想这个问题本身就很清楚。 – David

+1

现在怎么样?好点吗? – David

回答

1

根据代码片段你在原来的职位共享,我也克隆从GitHub项目,你的代码应该是JavaScript代码。

在JavaScript代码中,有setTimeout()或setInterval()函数。例如,如果使用setTimeout(),则需要将需要在暂停后运行的代码移动到setTimeout()回调中。

请修改您的代码,如下所示。

function formatFile(file) { 
dte.ExecuteCommand("View.SolutionExplorer"); 
if (file.Name.indexOf(".cs", file.Name.length - ".cs".length) !== -1) { 
    file.Open(); 
    file.Document.Activate(); 


    setTimeout(function() { 
     //move the code that you want to run after 1 second 
     dte.ExecuteCommand("Edit.RemoveAndSort"); 
     file.Document.Save(); 
     file.Document.Close(); 
    }, 1000); 

} 

并且在Javascript代码中有很多关于sleep()的线程。请参考:

What is the JavaScript version of sleep()?

JavaScript sleep/wait before continuing

+0

@David你有没有试过上面的代码,结果如何?如有任何问题,请告诉我。 –

+0

感谢亲爱的@ wendy。我试过你的代码,但我发现这个例外: – David

+0

第32行:预期的对象。 – David