我在使用 PlUpload 小部件时遇到了类似的问题。感谢 CheryJose 让我走上正轨。
首先我必须创建一个小类来找出打开了哪些窗口并将它们作为窗口字典返回。
public static IDictionary<string, IntPtr> GetOpenWindows()
{
IntPtr lShellWindow = GetShellWindow();
Dictionary<string, IntPtr> lWindows = new Dictionary<string, IntPtr>();
EnumWindows(delegate(IntPtr hWnd, int lParam)
{
if (hWnd == lShellWindow) return true;
if (!IsWindowVisible(hWnd)) return true;
int lLength = GetWindowTextLength(hWnd);
if (lLength == 0) return true;
StringBuilder lBuilder = new StringBuilder(lLength);
GetWindowText(hWnd, lBuilder, lLength + 1);
lWindows[lBuilder.ToString()] = hWnd;
return true;
}, 0);
return lWindows;
}
public delegate bool EnumDelegate(IntPtr hWnd, int lParam);
public delegate bool EnumedWindow(IntPtr handleWindow, ArrayList handles);
[DllImport("USER32.DLL")]
public static extern bool EnumWindows(EnumDelegate enumFunc, int lParam);
[DllImport("USER32.DLL")]
public static extern IntPtr GetShellWindow();
[DllImport("USER32.DLL")]
public static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
[DllImport("USER32.DLL")]
public static extern int GetWindowTextLength(IntPtr hWnd);
[DllImport("USER32.DLL")]
public static extern bool IsWindowVisible(IntPtr hWnd);
[DllImport("user32.dll")]
public static extern bool SetForegroundWindow(IntPtr hWnd);
在 Selenium 页面代码中,我单击按钮启动 PlUpload 窗口并稍等片刻。 (这在代码中没有显示)
然后我使用下面的代码找到所有打开的窗口
IDictionary<string, IntPtr> getOpenWindows = GetOpenWindows();
切换到 PlUpload 窗口(窗口名称因浏览器而异。请注意!)
IntPtr hWnd = getOpenWindows["File Upload"];
SetForegroundWindow(hWnd);
输入文件路径
SendKeys.SendWait(filename);
按回车
SendKeys.SendWait(@"{Enter}");
PlUpload 窗口将关闭,因此我们切换回浏览器窗口(在本例中为 Firefox)
hWnd = getOpenWindows["Mozilla Firefox"];
SetForegroundWindow(hWnd);
这有几个问题,因为窗口标题会根据所使用的浏览器而有所不同,因此需要考虑到这一点才能获得完整的解决方案。此外,当这部分代码正在执行时,不要将任何其他窗口置于前台,因为该窗口将收到“SendKeys”而不是所需的窗口。