简体   繁体   English

如何在C#Winforms项目的“ InvokeMember()”之前添加延迟

[英]How to add a delay before “InvokeMember()” in a C# Winforms project

I am trying to login to my website automatically using webBrowser control in my C# application. 我正在尝试使用C#应用程序中的webBrowser控件自动登录到我的网站。 The webpage checks the time required to fill and submit the login form. 该网页检查填写和提交登录表单所需的时间。 If the time taken is less than 2 seconds, then it shows an 'error page' saying 'Robots not allowed' . 如果花费的时间少于2秒,则显示“错误页面”,显示“ 不允许机器人”

Now my application is also getting that 'error page' just because the login form is getting filled within 2 seconds. 现在,我的应用程序也正在获取“错误页面”,仅因为登录表单在2秒内被填充。 How can I add a delay before firing the 'InvokeMember("click")' so that the time calculated by the webpage to fill the form be more than 2 seconds. 如何在触发“ InvokeMember(“ click”)”之前添加延迟,以使网页计算出的填写表格的时间超过2秒。

Here is my code 这是我的代码

HtmlElement ele = WebBrowser1.Document.GetElementById("username");
if (ele != null)
{     
    ele.InnerText = "myUsrname";
}
ele = webBrowser1.Document.GetElementById("password");
if (ele != null)
{
    ele.InnerText = "myPasswrd";
}
ele = webBrowser1.Document.GetElementById("submit");
if (ele != null)
{
    // I want to add a delay of 3 seconds here
    ele.InvokeMember("click");
}

Note : I used "Task.Delay(3000);" 注意:我使用了“ Task.Delay(3000);” but it doesn't seems to work. 但它似乎不起作用。

Edit : This is what I am using now and is working for me. 编辑:这是我现在正在使用,并为我工作。

async void webBrowser1_DocumentCompleted_1(object sender, WebBrowserDocumentCompletedEventArgs e)
{
......//my code
 await Task.Delay(3000);// this is where I wanted to put a delay
....
}

But I would like to, Is this a correct way to use it ? 但是我想,这是一种正确的使用方式吗?

You could use this: 您可以使用此:

int milliseconds = 2000;
Thread.Sleep(milliseconds)  

Greetings, 问候,
ST ST

If you want to don't freeze UI when waiting, Consider this sample: 如果您不想在等待时冻结UI,请考虑以下示例:

private async void button1_Click(object sender, EventArgs e)
{
    await Task.Run(async () =>
    {
        await Task.Delay(3000);
        MessageBox.Show("1");
        button1.Invoke(new Action(() => { this.button1.Text = "1"; }));
    });
    MessageBox.Show("2");
    button1.Invoke(new Action(() => { this.button1.Text = "2"; }));
}

The sample is self describing. 该示例是自我描述。

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

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