使用 Process.Start() 打开多个文档

Pet*_*efe 2 .net c#

我正在尝试编写一个程序,只需单击一下即可打开多个文档,并为每个单独的文档窗口指定大小和位置。在我尝试打开第二个 Word 或 Excel 文档之前,我使用基本程序测试打开和定位操作取得了不错的成功。

using System;
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace ConsoleApplication1
{
    class Program
    {
        [DllImport("user32.dll", SetLastError = true)]
        internal static extern bool MoveWindow(IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint);

        static void Main(string[] args)
        {
            Process resize = new Process();

            resize.StartInfo.FileName = "C:\\Users\\Pete\\Desktop\\TEST1.txt";
            resize.Start();
            resize.WaitForInputIdle();
            MoveWindow(resize.MainWindowHandle, 10, 10, 500, 500, true);

            resize.StartInfo.FileName = "C:\\Users\\Pete\\Desktop\\MSWTEST1.docx";
            resize.Start();
            resize.WaitForInputIdle();
            MoveWindow(resize.MainWindowHandle, 20, 20, 500, 500, true);

            resize.StartInfo.FileName = "C:\\Users\\Pete\\Desktop\\MSXTEST1.xlsx";
            resize.Start();
            resize.WaitForInputIdle();
            MoveWindow(resize.MainWindowHandle, 30, 30, 500, 500, true);

            resize.StartInfo.FileName = "C:\\Users\\Pete\\Desktop\\TEST2.txt";
            resize.Start();
            resize.WaitForInputIdle();
            MoveWindow(resize.MainWindowHandle, 40, 40, 500, 500, true);

            resize.StartInfo.FileName = "C:\\Users\\Pete\\Desktop\\MSWTEST2.docx";
            resize.Start();
            resize.WaitForInputIdle();
            MoveWindow(resize.MainWindowHandle, 50, 50, 500, 500, true);

            resize.StartInfo.FileName = "C:\\Users\\Pete\\Desktop\\MSXTEST2.xlsx";
            resize.Start();
            resize.WaitForInputIdle();
            MoveWindow(resize.MainWindowHandle, 60, 60, 500, 500, true);
         }
    }
}
Run Code Online (Sandbox Code Playgroud)

该程序尝试使用记事本打开两个 .txt 文件、使用 MSWord 打开两个 .docx 文件以及使用 MSExcel 打开两个 .xlsx 文件。无论我在程序中打开文档的顺序如何,都会在打开第二个 Word 或 Excel 文件后立即在 WaitForInputIdle 行上抛出 InvalidOperationException。任何修复此错误的帮助将不胜感激。

Pet*_*hie 5

当您尝试打开 Word 或 Excel 文档时,正在执行的应用程序(取决于版本)只会查找已经运行的相同应用程序,要求它打开一个新的“窗口”并关闭。这意味着你实际运行从来没有真正得到一个消息泵的应用-这会导致WaitForInputIdle异常触发的InvalidOperationException(如文档

我建议您简单地尝试捕获并忽略异常——我不确定有什么方法可以判断 Word/Excel 是否通过Process.Start 更新成功打开了文档:从概念上讲,如果您确实得到异常,则意味着 Word/Excel 发现另一个正在运行实例并切换到它 - 所以,大概这是某种程度的“成功”。