我有一个方法,允许在word中打开word文档,并在完成之前等待单词退出。
如果单词尚未运行,则一切正常。
如果word正在运行,则该过程立即退出,因此我可以等待退出。
如果单词已经在运行,我可以等待文档关闭的任何想法吗?
这是在Windows 8.1
public void ShowExternalReference(string externalRef, bool waitForCompletion)
{
if (externalRef.NotEmpty())
{
var pInfo = new ProcessStartInfo {FileName = externalRef};
// Start the process.
Process p = Process.Start(pInfo);
if (waitForCompletion)
{
// Wait for the window to finish loading.
p.WaitForInputIdle();
// Wait for the process to end.
p.WaitForExit();
}
}
}
答案 0 :(得分:1)
您可以获取当前正在运行的Word进程并附加到事件
我收到了一些信息here
以下是将文档附加到文档中并将其放入文档的示例...
希望这有帮助。
using Word = Microsoft.Office.Interop.Word;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load_1(object sender, EventArgs e)
{
}
public void ShowExternalReference(string externalRef, bool waitForCompletion)
{
if (externalRef.Length > 0)
{
var pInfo = new ProcessStartInfo { FileName = externalRef };
bool isrunning = false;
Process [] pList = Process.GetProcesses();
foreach(Process x in pList)
{
if( x.ProcessName.Contains("WINWORD"))
{
isrunning = true;
Word.Application myWordApp =
System.Runtime.InteropServices.Marshal.GetActiveObject(
"Word.Application") as Word.Application;
if(myWordApp.ActiveDocument.FullName.Contains(externalRef))
// do something
myWordApp.ActiveDocument.Content.Text = " already open";
}
}
if(!isrunning)
{
// Start the process.
Process p = Process.Start(pInfo);
if (waitForCompletion)
{
// Wait for the window to finish loading.
p.WaitForInputIdle();
// Wait for the process to end.
p.WaitForExit();
}
}
}
}
private void button1_Click(object sender, EventArgs e)
{
string myWordFile = @"C:\Temp\test.docx";
ShowExternalReference(myWordFile, true);
}
private void listView1_ItemChecked(object sender, ItemCheckEventArgs e)
{
listView1.Items[e.Index].Group = listView1.Groups[e.NewValue == CheckState.Checked ? 0 : 1];
}
答案 1 :(得分:0)
Process[] pname = Process.GetProcessesByName("winword.exe");
if(pname.Length == 0)
{
//not running..
}
你可以通过一个后台线程来循环它,也许是为了不断测试Word是否正在运行,并在事件没有时触发事件