Using Read-Only Fields in a C# WebBrowser

亡梦爱人 提交于 2019-12-24 03:33:11

问题


I'm currently using a WebBrowser control in a C# WinForms application, and attempting to control some variability presented with this control.

Basically, my users log in to a separate UI provided by my application, which then displays the WebBrowser control, navigates to a predetermined log-in URL, and then auto-fills the username and password fields on that page.

However, in order to prevent unpredictable behavior in this WebBrowser control, I want to make these username and password text boxes read-only after they are auto-populated. Essentially, I want the user to see a browser page that has been filled out for them, and that cannot be edited. (This is so that any authentication errors can be handled by my application as opposed to the browser.)

The code I'm currently using to populate the text fields and make them read only is as follows:

webBrowser1.Document.GetElementById("username").InnerText = username;
webBrowser1.Document.GetElementById("password").InnerText = password;
webBrowser1.Document.GetElementById("username").Enabled = false;
webBrowser1.Document.GetElementById("password").Enabled = false;

Unfortunately, when I try to make the fields read-only, the authentication server acts like the password field was not filled out, and prompts the user to fill it out again after the "Submit" button is clicked. Is this expected behavior, and if so, what other methods can I try to prevent users from changing the credentials that the browser was auto-populated with?


回答1:


Try making them readonly:

webBrowser1.Document.GetElementById("username").SetAttribute("readonly", "readonly");        
webBrowser1.Document.GetElementById("password").SetAttribute("readonly", "readonly");



回答2:


Why don't you create a transparent panel as shown in this article which would be placed on top of the webbrowser-control:

/// <summary>
    /// A transparent control.
    /// </summary>
    public class TransparentPanel : Panel
    {
        public TransparentPanel()
        {
        }

        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams createParams = base.CreateParams;
                createParams.ExStyle |= 0x00000020; // WS_EX_TRANSPARENT
                return createParams;
            }
        }

        protected override void OnPaintBackground(PaintEventArgs e)
        {
            // Do not paint background.
        }
    }

This would prevent the user from modifying the values.

You could show/hide this panel as you wish, and even extend to capture mouse click locations if you wished.



来源:https://stackoverflow.com/questions/11000942/using-read-only-fields-in-a-c-sharp-webbrowser

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!