我有一个方法,它允许在word中打开word文档,并等待word退出,然后才能完成。
如果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();
}
}
}发布于 2013-10-25 06:19:30
您可以获取当前正在运行的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];
}发布于 2013-10-25 04:34:37
Process[] pname = Process.GetProcessesByName("winword.exe");
if(pname.Length == 0)
{
//not running..
}您可以通过后台线程循环执行此操作,以便不断测试Word是否正在运行,并在Word未运行时重新触发事件
https://stackoverflow.com/questions/19575961
复制相似问题