Handle IE To filling a form c#

后端 未结 1 1779
旧时难觅i
旧时难觅i 2020-12-12 01:40

I want to navigate a website, login and fill a form through my application without seeing users anything and finally show it to users for submitting.

Previously I us

相关标签:
1条回答
  • 2020-12-12 02:19

    You can automate an instance of Internet Explorer from your C# app. First, create the interop assembly SHDocVw.dll with TlbImp.exe ieframe.dll and add it as a reference to your project. Then use the following code to create an out-of-process instance of Internet Explorer:

    var ie = (SHDocVw.WebBrowser)Activator.CreateInstance(Type.GetTypeFromProgID("InternetExplorer.Application"));
    ie.Visible = true;
    ie.Navigate("http://www.example.com");
    

    Use it in a similar way you used WebBrowser control.

    That said, I believe you still can use hosted WebBrowser for what you want to achieve, just implement feature control to make it behave the same way IE does (or as close as possible).

    [EDITED] This innocent example may however have a hidden catch. Because you automate an out-of-proc COM object here, its events (if you handle any) may arrive on a thread, different from your main UI thread. Generally, you'd need to marshal them back to your main thread using Control.Invoke or SynchronizationContext.Post/Send (depending on whether you want to handle them asynchronously or synchronously). Here's an example of handling DocumentComplete and taking care of threading:

    using System;
    using System.Diagnostics;
    using System.Threading;
    using System.Windows.Forms;
    
    namespace WinformsIE
    {
        public partial class Form1 : Form
        {
             public Form1()
            {
                SetBrowserFeatureControl();
                InitializeComponent();
            }
    
            private void Form1_Load(object sender, EventArgs ev)
            {
                var ie = (SHDocVw.InternetExplorer)Activator.CreateInstance(Type.GetTypeFromProgID("InternetExplorer.Application"));
                ie.Visible = true;
                Debug.Print("Main thread: {0}", Thread.CurrentThread.ManagedThreadId);
                ie.DocumentComplete += (object browser, ref object URL) =>
                {
                    string url = URL.ToString();
                    Debug.Print("Event thread: {0}", Thread.CurrentThread.ManagedThreadId);
                    this.Invoke(new Action(() =>
                    {
                        Debug.Print("Action thread: {0}", Thread.CurrentThread.ManagedThreadId);
                        var message = String.Format("Page loaded: {0}", url);
                        MessageBox.Show(message);
                    }));
                };
                ie.Navigate("http://www.example.com");
            }
    
        }
    }
    
    0 讨论(0)
提交回复
热议问题