C#WebBrowser控件FileUpload对话框不会一直关闭

时间:2013-10-07 13:49:56

标签: c# webbrowser-control asyncfileupload

我正在使用WebBrowser控件进行一些自动化测试。问题是偶尔 - 并非所有时间 - 当我测试上传图像时,文件上传对话框没有关闭,程序只是“挂起”并等待手动输入,这违背了整个自动化过程的目的。我想要做的是“强制”关闭对话框,但一直无法解决这个问题。任何帮助或方向将不胜感激。

要意识到的是,此代码在当时部分,但不是所有。我需要帮助弄清楚如何使这个代码始终工作。

以下是代码:

    async Task PopulateInputFile(System.Windows.Forms.HtmlElement file, string fname)
    {
        file.Focus();

        // delay the execution of SendKey 500ms to let the Choose File dialog show up
        var sendKeyTask = Task.Delay(5000).ContinueWith((_) =>
        {
            // this gets executed when the dialog is visible
            //SendKeys.Send(fname + "{ENTER}");
            //PressKey(Keys.Space, false);
            SendKeys.SendWait(fname);
            PressKey(Keys.Enter, false);
        }, TaskScheduler.FromCurrentSynchronizationContext());

        file.InvokeMember("Click"); // this shows up the dialog

        await sendKeyTask;

        // delay continuation 500ms to let the Choose File dialog hide
        await Task.Delay(5000);
    }

    async Task Populate(string fname)
    {
        var elements = webBrowser.Document.GetElementsByTagName("input");
        foreach (System.Windows.Forms.HtmlElement file in elements)
        {
            if (file.GetAttribute("name") == "file")
            {
                this.Activate();
                this.BringToFront();
                file.Focus();
                await PopulateInputFile(file, fname);
                file.RemoveFocus();
            }
        }
    }

2 个答案:

答案 0 :(得分:0)

不是一个真正的答案,但它可能会在以后变成一个答案。 确保焦点位于IE“选择要上传的文件”对话框中,当您执行SendKeys时?使用以下内容验证,将代码放在Task.Delay(4000)下面进入ContinueWith并检查Debug.Print的输出。

static class Win32
{
    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    public static extern int GetWindowText(IntPtr hWnd, System.Text.StringBuilder lpString, int nMaxCount);

    [DllImport("user32.dll")]
    public static extern IntPtr GetForegroundWindow();
}

private async void Form1_Load(object sender, EventArgs ev)
{
    await Task.Delay(4000);

    var currentWindow = new System.Text.StringBuilder(1024);
    Win32.GetWindowText(Win32.GetForegroundWindow(), currentWindow, currentWindow.Capacity);
    Debug.Print("Currently focused window: \"{0}\"", currentWindow);
}

答案 1 :(得分:0)

好的,这是解决方案。您必须使用WIN API关闭窗口。我使用SPY ++找到了“选择要上载的文件”对话框的类名,结果证明是:#32770。

    [DllImport("user32.dll")]
    public static extern int FindWindow(string lpClassName,string lpWindowName);
    [DllImport("user32.dll")]
    public static extern int SendMessage(int hWnd, uint Msg, int wParam, int lParam);

    public const int WM_SYSCOMMAND = 0x0112;
    public const int SC_CLOSE = 0xF060;

    int iHandle = FindWindow("#32770", "Choose File to Upload");
    if (iHandle > 0)
    {
          // close the window using API        
          SendMessage(iHandle, WM_SYSCOMMAND, SC_CLOSE, 0);
    }