繁体   English   中英

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

[英]Opening multiple documents with Process.Start()

我正在尝试编写一个程序,只需单击即可打开多个文档,并为每个单独的文档窗口指定大小和位置。 在尝试打开第二个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);
         }
    }
}

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

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

我建议您只是尝试捕获并忽略该异常-我不确定有任何方法可以判断Word / Excel是否通过Process.Start Update成功打开了文档:从概念上讲,如果您确实获得了表示Word / Excel的异常找到另一个正在运行的实例并切换到它 - 所以,大概是某种程度的“成功”。

当您打开第二个Word或Excel文档时,启动过程会检测到Word / Excel已经启动,并且只是向另一个进程发送文档信息并关闭。

一个更简单的应用程序,如记事本,没有这种行为。

这意味着,在这种情况下,您第二次启动时的Process实例值得精确zilch,以便控制正在打开的文档。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM