WebBrowser - unable to retrieve and set HTML eleme

2020-04-24 11:33发布

问题:

This is for a Desktop C# app in Visual Studio Express 2012.

I am using a webBrowser control to logon to various websites however I am unable to retrieve and set the attributes for this particular website where the logon attributes are in an .asp page which is 'called' by the HTML.

The attributes themselves do not appear visible via GetElementById or navigation through the HtmlElementCollection.

The HTML snippet below shows the call to login.asp and the fields "CorporateSignonCorpId" and "CorporateSignonPassword" which I am trying to set but which reside in "login.asp"

**Website HTML**
</head>
<frameset rows="*,0">
<frame src="login.asp" id="main" name="main" frameborder="0" noresize="true" scrolling="auto" hidefocus="true" target="_top">
<frame src="hiddenframe.asp" id="data" name="data" frameborder="0" noresize="true" scrolling="auto" hidefocus="true">
<noframes>


**login.asp:**
<!--CRN AND PASSWORD TABLE-->
    <table border="0" cellpadding="2" cellspacing=0>
        <tr>
            <td align="right" nowrap class="header5">Customer Registration Number:</td>
            <td valign="top" colspan="2"><font face="sans"><input type="TEXT" name="CorporateSignonCorpId" tabIndex=0 size="16" maxlength="19" AUTOCOMPLETE="OFF" onKeyPress="onFocus:microsoftKeyPress();" onFocus="javascript: strActiveField='CorporateSignonCorpId';"></font></td>
        </tr>
        <tr>
            <td align="right" class="header5">Password:</td>
            <td valign="top"><font face="sans"><input type="PASSWORD" name="CorporateSignonPassword" size="16" tabIndex=0 AUTOCOMPLETE="OFF" onKeyPress="javascript:microsoftKeyPress();" onFocus="javascript: strActiveField='CorporateSignonPassword';"></font></td>
        </tr>
        <tr>

How do I reference and set values for the attributes "CorporateSignonCorpId" and "CorporateSignonPassword" in C#?

ANY help would be appreciated!! thks Mick

回答1:

You can use webBrowser.Document.Window.Frames["main"].Document to get to the inner frame's document. The following works for me:

private async void MainForm_Load(object sender, EventArgs e)
{
    var tcs = new TaskCompletionSource<bool>();
    WebBrowserDocumentCompletedEventHandler handler = (s, arg) => 
        tcs.TrySetResult(true);

    this.webBrowser.DocumentCompleted += handler;
    this.webBrowser.Navigate("http://localhost:81/frameset.html");
    await tcs.Task;
    this.webBrowser.DocumentCompleted -= handler;

    var frameDocument = this.webBrowser.Document.Window.Frames["main"].Document;
    var element = frameDocument.GetElementById("CorporateSignonCorpId");
    MessageBox.Show(element.OuterHtml);
}