【发布时间】:2017-11-03 19:33:59
【问题描述】:
我正在编写一个程序,让用户单击一个链接,该链接将打开一个信息路径表单并为他们自动填充一些字段。
但是,由于我无权访问表单源代码来查找字段变量名称,因此我必须通过将带有 SendKeys 的“\t”发送到表单来输入信息以到达相应的字段。这意味着窗口必须具有焦点。所以我用了:
[DllImport("user32.dll", SetLastError = true)]
static extern bool SetForegroundWindow(IntPtr hWnd);
为了将窗口带到前面。出于某种原因,如果同一进程的多个窗口打开并且我尝试给予进程焦点,则 SetForegroundWindow 会抛出一个合适的结果......即使我自己创建了进程并确定我正在发送正确的窗口,它也会产生错误留言:
Process has exited, so the requested information is not available.
(这是我刚刚打开的进程。)
基本上我的代码如下:
Process[] ps = Process.GetProcessByName("InfoPath");
if (ps.Length != 0)
{
for(int i = 0; i < ps.Length; i ++)
ps[i].Close();
}
Process infoPath = new Process();
infoPath.StartInfo.FileName = "InfoPath.exe";
infoPath.StartInfo.Arguments = "TemplateLocation.xsn";
infoPath.Start();
try{
BringToFront(infoPath);
}catch (Exception e)
{
// handle failure
}
SendKeys.SendWait("\t\t\t\t");
SendKeys.SendWait(information);
BringToFront 在哪里:
private void BringToFront(Process pTemp)
{
try
{
SetForegroundWindow(pTemp.MainWindowHandle);
}catch(Exception e)
{
//fails here saying that the process has exited, so the requested information is not available.
throw e;
}
}
我得到的问题是 GetProcessByName 只返回最近打开的 InfoPath 进程。即使我会运行 5 或 6 个,它也只会返回最近打开的一个并关闭它。
所以基本上我正在寻找两件事之一:
1) 获取 GetProcessByName 以实际返回 infopath 进程的完整列表
或
2) 当我向 SetForegroundWindow 发送我刚刚打开的进程时,了解它是如何失败的。
【问题讨论】:
-
你应该使用
Process.GetProcessesByName(注意复数)。Process.GetProcessByName没有定义,所以它让我相信你是手动输入的,可能还有其他错误。 -
@RonBeyer 是的.. 一个错字。