如何让EmEditor宏等待用户输入窗口关闭后再执行后续代码?
解决EmEditor宏执行时序异常(prompt未等待用户输入就跑后续逻辑)
问题根因
代码中直接调用的全局prompt()方法,未接入EmEditor主窗口的模态消息循环,在EmEditor宏执行环境下为非阻塞异步接口:弹窗挂载到UI层后,宏引擎不会等待用户操作完成、窗口关闭,就直接向下执行后续逻辑,完全打乱执行顺序。
修复方案
替换非阻塞的prompt()为EmEditor原生同步模态输入接口,强制宏暂停直到用户完成输入操作,优先用改动最小的内置方法实现:
- 使用
editor.GetString()接口:该接口是EmEditor宏原生的模态输入弹窗,执行时会挂起宏流程,直到用户点击确定/取消关闭弹窗才会返回输入值,完全同步。 - 接口兼容空值、取消操作的判断逻辑:用户点取消时接口返回
null,输入空值时返回空字符串,需要同步修正原有判断分支。
修改后的完整宏代码
clipboardData.setData("Text", ""); wnd = shell.FindWindow( "", "Playlist" ); wnd.SetForeground(); Sleep( 1000 ); shell.SendKeys( "^a" ); Sleep( 100 ); shell.SendKeys( "^%c" ); Editor.newfile(); Sleep(500); document.selection.Paste(eeCopyUnicode); if( !editor.EnableTab ){ editor.EnableTab = true; alert( "Please run this macro again." ); Quit(); } // 替换原有非阻塞prompt,用同步模态输入接口 sFind = editor.GetString( "This macro extracts lines that do contain any of the specified multiple strings separated by |:", "", "批量提取配置" ); // 兼容用户点取消(返回null)、输入空值的退出逻辑 if( sFind === null || sFind.trim() === "" ){ Quit(); } var sArr = sFind.split("|"); batch_list = editor.filters; for( i = 0; i < sArr.length; ++i ) { batch_list.AddFind(sArr[i],0,0); } document.selection.BatchFind(batch_list, eeFindExtract | eeFindLineOnly,0); document.selection.SelectAll(); // select all text document.selection.Copy(eeCopyUnicode); // copy the selection to the Clipboard WshShell = new ActiveXObject( "WScript.Shell" ); WshShell.Run ( "PotPlayerMini64.exe /clipboard" );
兜底兼容方案(适用于老版本EmEditor)
如果editor.GetString()仍出现非阻塞问题,可替换为自定义模态Dialog实现,该方式为强模态绑定,100%阻塞宏执行直到窗口关闭:
// 替换原有prompt逻辑 var dlg = editor.CreateDialog(); dlg.width = 480; dlg.height = 160; dlg.AddLabel( "This macro extracts lines that do contain any of the specified multiple strings separated by |:", 15, 15, 420, 25 ); var inputBox = dlg.AddTextBox( 15, 45, 430, 22, "" ); dlg.AddButton( "确定", 160, 85, 80, 28, eeDialogOK ); dlg.AddButton( "取消", 270, 85, 80, 28, eeDialogCancel ); // 模态显示弹窗,代码停在此处直到弹窗关闭 if( dlg.Show() !== eeDialogOK ){ Quit(); } var sFind = inputBox.value.trim(); if( sFind === "" ){ Quit(); }
注意事项
- 不要在调用同步输入接口前连续执行超过1秒的
Sleep(),避免宏执行线程和UI消息循环绑定异常,再次出现非预期的非阻塞问题。 - 原有判断
if(sFind == "")需要补全null值判断,否则用户点击“取消”按钮时会触发异常后续执行。
内容的提问来源于stack exchange,提问作者Koteswara Rao
相关产品推荐
相关产品推荐

