3

我有一种方法,允许在 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();
            }
        }
    }
4

2 回答 2

1

您可以获取当前正在运行的 Word Process 并附加到事件

我在这里得到了一些信息

这是附加文本并将其放入文档中的示例...

希望这可以帮助。

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-24T22:19:29.897 回答
0
Process[] pname = Process.GetProcessesByName("winword.exe");
if(pname.Length == 0)
{
   //not running..
}

您可以通过后台线程循环此线程,以不断测试 Word 是否正在运行,并在未运行时触发事件

于 2013-10-24T20:34:37.157 回答