C# — работа с компонентом WebBrowser в Visual Studio.

Суть задачи заключается в том, что компонент WebBrowser работает под управление давно устаревшего IE7 браузера. Поэтому ошибки отображение контента сайтов будут повсеместны. Для решения данной проблемы в статье предлагаются различные методы, а также рассматривается часто необходимая задача работы с браузером через прокси:

Отключение ошибок скриптов.

Для начала отключите свойство компонента, которое позволяет сыпать браузер сообщения об ошибках. Это мало поможет, зато избавит от бесконечных MessageBox с ошибками:

webBrowser1.ScriptErrorsSuppressed = true;

Изменение User-Agent Вашего браузера.

Сразу создадим класс с необходимыми функциями:

public static class IeMethods
    {
        [System.Runtime.InteropServices.DllImport(@"urlmon.dll", CharSet = CharSet.Ansi)]
        private static extern int UrlMkSetSessionOption(int dwOption, string pBuffer, int dwBufferLength, int dwReserved);

        /*
        // IE8
        IeMethods.SetAnotherUserAgent("Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; GTB7.4; InfoPath.2; SV1; .NET CLR 3.3.69573; WOW64; en-US)");
        // IE11
        IeMethods.SetAnotherUserAgent("Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko");
        // CHROME
        IeMethods.SetAnotherUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.75 Safari/537.36");
        */

        public static void SetAnotherUserAgent(string ua)
        {
            const int urlmonOptionUseragent = 0x10000001;
            const int urlmonOptionUseragentRefresh = 0x10000002;
            var UserAgent = ua;
            UrlMkSetSessionOption(urlmonOptionUseragentRefresh, null, 0, 0);
            UrlMkSetSessionOption(urlmonOptionUseragent, UserAgent, UserAgent.Length, 0);
        }

        public static void SetBrowserEmulation(int version)
        {
            string program = Application.ExecutablePath.Split('\\').Reverse().ToList()[0];
            var key = "SOFTWARE\\Microsoft\\Internet Explorer\\Main\\FeatureControl\\FEATURE_BROWSER_EMULATION";

            Microsoft.Win32.RegistryKey hkcu = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(key);
            hkcu.SetValue(program, version, Microsoft.Win32.RegistryValueKind.DWord);
            hkcu.Close();
        }
}
    

С помощью функции SetAnotherUserAgent можно указать серверу, какой именно браузер у вас используется. Это не всегда помогает, так как IE7 всет-аки редко принимается в рассчет в наше время.

public Form1()
        { 		
			//or set user agent
            IeMethods.SetAnotherUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.75 Safari/537.36");
            InitializeComponent();
            
         
        }

Изменение версии эмуляции IE.

Самое окончательное решение этой проблемы – эмуляция той версии IE, которая у вас установлена и ниже (при желании).

          	11001 (0x2AF9) - Internet Explorer 11. Webpages are displayed in IE11 edge mode, regardless of the !DOCTYPE directive.
            11000 (0x2AF8) - IE11. Webpages containing standards-based !DOCTYPE directives are displayed in IE11 edge mode. Default value for IE11.
            10001 (0×2711) - Internet Explorer 10. Webpages are displayed in IE10 Standards mode, regardless of the !DOCTYPE directive
            10000 (0×02710) - Internet Explorer 10. Webpages containing standards-based !DOCTYPE directives are displayed in IE10 Standards mode. Default value for Internet Explorer 10.
            9999 (0x270F) - Windows Internet Explorer 9. Webpages are displayed in IE9 Standards mode, regardless of the !DOCTYPE directive.
            9000 (0×2328) - Internet Explorer 9. Webpages containing standards-based !DOCTYPE directives are displayed in IE9 mode. Default value for Internet Explorer 9.Important In Internet Explorer 10, Webpages containing standards-based !DOCTYPE directives are displayed in IE10 Standards mode.
            8888 (0x22B8) - Webpages are displayed in IE8 Standards mode, regardless of the !DOCTYPE directive.
            8000 (0x1F40) - Webpages containing standards-based !DOCTYPE directives are displayed in IE8 mode. Default value for Internet Explorer 8Important In Internet Explorer 10, Webpages containing standards-based !DOCTYPE directives are displayed in IE10 Standards mode.
            7000 (0x1B58) - Webpages containing standards-based !DOCTYPE directives are displayed in IE7 Standards mode. Default value for applications hosting the WebBrowser Control.
            */
            //set IE version
            IeMethods.SetBrowserEmulation(11001);

Изменение проси-сервера.

При желании работать через прокси-сервер с целью, допустим, накрутки ресурсов или с целью анонимности можно настроить прокси для большинства пользовательских приложения через настройки браузера IE. Свойства браузера -> вкладка Подключения — > Настройка сети:

Или через настройки реестра HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings:

Однако, предпочтительнее сделать это только для одного приложения. Для этого создадим класс для настройки прокси:

public static class ProxyControl
    {
        [DllImport("wininet.dll", SetLastError = true)]
        private static extern bool InternetSetOption(IntPtr hInternet, int dwOption, IntPtr lpBuffer, int lpdwBufferLength);

        public static void Set(string proxy)
        {
            try
            {
                const int INTERNET_OPTION_PROXY = 38;
                const int INTERNET_OPEN_TYPE_PROXY = 3;

                Struct_INTERNET_PROXY_INFO struct_IPI;

                // Filling in structure
                struct_IPI.dwAccessType = INTERNET_OPEN_TYPE_PROXY;
                struct_IPI.proxy = Marshal.StringToHGlobalAnsi(proxy);
                struct_IPI.proxyBypass = Marshal.StringToHGlobalAnsi("local");

                // Allocating memory
                IntPtr intptrStruct = Marshal.AllocCoTaskMem(Marshal.SizeOf(struct_IPI));

                // Converting structure to IntPtr
                Marshal.StructureToPtr(struct_IPI, intptrStruct, true);

                bool iReturn = InternetSetOption(IntPtr.Zero, INTERNET_OPTION_PROXY, intptrStruct, Marshal.SizeOf(struct_IPI));
            }
            catch (Exception)
            {
            }
        }

        public struct Struct_INTERNET_PROXY_INFO
        {
            public int dwAccessType;
            public IntPtr proxy;
            public IntPtr proxyBypass;
        };
    }

И из любого места программы вызвать метод Set с целью установки или смены proxy:

ProxyControl.Set("127.0.0.1:8888");

И в заключении есть еще один более универсальный способ установки прокси через функцию UrlMkSetSessionOption, которой мы пользовались для установки userAgent, описанный в https://docs.microsoft.com/en-us/previous-versions/windows/internet-explorer/ie-developer/platform-apis/ms775125(v=vs.85)

46 комментариев: C# — работа с компонентом WebBrowser в Visual Studio.

  • I will immediately clutch your rss feed as
    I can not find your email subscription hyperlink or newsletter
    service. Do you have any? Please let me recognise so that I may just subscribe.
    Thanks.

  • Woah! I’m really digging the template/theme of this website.
    It’s simple, yet effective. A lot of times it’s difficult to get that «perfect balance» between superb usability and visual appeal.
    I must say that you’ve done a amazing job with this.
    In addition, the blog loads very quick for me on Internet explorer.
    Excellent Blog!

  • I have been surfing online greater than 3 hours lately,
    but I by no means found any interesting article like yours.

    It is lovely worth sufficient for me. Personally,
    if all webmasters and bloggers made excellent content as
    you did, the internet can be much more useful than ever before.

  • I have been browsing on-line more than three hours lately, but I never discovered any interesting article like yours.
    It’s lovely value enough for me. Personally, if all site owners and
    bloggers made just right content as you probably did, the internet might be much more helpful than ever before.

  • I have learned newer and more effective things by means of your blog. One other thing I would really like to say is that newer laptop os’s tend to allow additional memory to use, but they also demand more storage simply to perform. If your computer can’t handle much more memory along with the newest computer software requires that storage increase, it may be the time to buy a new Computer system. Thanks

  • It’s appropriate time to make some plans for the longer term and it is time to
    be happy. I have read this post and if I may I want to suggest you some fascinating issues
    or tips. Perhaps you could write next articles regarding this article.
    I want to learn even more things approximately it!

  • It is perfect time too maske a ffew plans
    foor tthe future andd it’s tine to bbe happy.
    I’ve learrn thuis submit aand iff I mayy I want too counse you sme attention-grabbing thints orr advice.
    Maytbe yyou cojld wrige next afticles rlating to this article.
    I wnt tto rad more issues aboout it!

  • It’s very trouble-free to find out any matter on web as compared
    to books, as I found this post at this web
    site.

  • I truly love your website.. Pleasant colors & theme.
    Did you develop this web site yourself? Please
    reply back as I’m hoping to create my own personal website and would love to know where you got this from or just what the theme is named.
    Many thanks!

  • I’ve been surring onjline more thwn 4 hours today, yyet I never fpund aany interesting
    aricle liie yours. It’s prettyy worth enouggh for me.
    In myy view, iff alll sjte ownets annd bloggers made ood content aas
    you did, the wweb wipl bbe a loot more seful thasn evesr before.

  • Way cool! Some extremely valid points! I appreciate you writing this write-up plus the rest of the
    website is extremely good.

  • Howdy! This post could not be written much
    better! Going through this post reminds me of my previous roommate!
    He always kept talking about this. I will send this article to him.
    Fairly certain he will have a good read. Thanks
    for sharing!

  • Hola! I’ve been following your website for a long time now
    and finally got the courage to go ahead and give you a shout out from
    New Caney Texas! Just wanted to say keep up the great work!

  • Hello my family member! I wish to say that this post is
    amazing, great written and include almost all significant infos.
    I would like to look more posts like this .

  • Уведомление: where to get cialis
  • It’s appropriate time to make some plans for the long run and it
    is time to be happy. I’ve learn this submit and if I
    may just I want to suggest you some fascinating issues or advice.
    Maybe you could write next articles referring to this article.
    I desire to learn more issues approximately it!

  • Ahaa, its good conversation about this piece of writing at this place at
    this weblog, I have read all that, so at this time me also commenting here.

  • It’s very straightforward to find out any matter on net
    as compared to textbooks, as I found this article at this
    site.

  • Some tips i have always told persons is that when evaluating a good on the net electronics retail outlet, there are a few components that you have to remember to consider. First and foremost, you need to make sure to choose a reputable as well as reliable shop that has got great testimonials and rankings from other consumers and business sector leaders. This will make certain you are getting along with a well-known store providing you with good program and help to it’s patrons. Thank you for sharing your ideas on this site.

  • I want to to thank you for this great read!! I absolutely loved every bit of
    it. I’ve got you saved as a favorite to check out new stuff you

  • I truly love your site.. Pleasant colors & theme.
    Did you develop this amazing site yourself? Please reply
    back as I’m wanting to create my own site and would love to know where you got this from or exactly what the theme is called.
    Appreciate it!

  • This is a very big difference in the way remote flashes can be controlled,
    the equipment becomes incompatible.

  • I will right away seize your rss as I can not in finding your
    email subscription link or newsletter service.
    Do you’ve any? Please let me realize in order that I could subscribe.
    Thanks.

  • Hey there, I think your blog might be having browser compatibility issues.
    When I look at your website in Safari, it looks fine but when opening in Internet Explorer, it has some overlapping.
    I just wanted to give you a quick heads up! Other then that, fantastic
    blog!

  • It is perfect time to make a few plans for the future and it’s time to be
    happy. I’ve learn this publish and if I could I wish to counsel you few interesting things or advice.
    Maybe you could write subsequent articles referring to this article.
    I want to read even more issues about it!

  • Greetings from California! I’m bored to death at work so I decided
    to check out your website on my iphone during lunch
    break. I really like the information you provide here and can’t
    wait to take a look when I get home. I’m shocked at how quick your blog loaded on my cell
    phone .. I’m not even using WIFI, just 3G .. Anyhow, amazing blog!

  • I really love your site.. Excellent colors & theme.
    Did you make this website yourself? Please reply back as I’m attempting to create my own blog and want to know where you got this
    from or exactly what the theme is called. Cheers!

  • I’ve been surfing online more than 3 hours lately, but I
    never found any fascinating article like yours.
    It is beautiful worth sufficient for me. In my opinion, if all
    site owners and bloggers made good content material as you probably
    did, the net shall be much more useful than ever
    before.

  • Ahaa, its nice dialogue regarding this paragraph at this place at this blog, I have read
    all that, so at this time me also commenting here.

  • I really like what you guys are usually up too.
    Such clever work and exposure! Keep up the good works guys I’ve incorporated you guys to my personal blogroll.

  • I have been surfing online more than 3 hours today, yet I never found any interesting article
    like yours. It’s pretty worth enough for me. In my opinion, if all site owners and bloggers made good content as
    you did, the internet will be much more useful than ever before.

  • I’ve been surfing on-line greater than 3
    hours these days, but I never discovered any interesting article like yours.
    It’s lovely worth enough for me. In my view, if all web owners and bloggers made good content
    material as you did, the internet might be a lot more helpful
    than ever before.

  • I’m extremely impressed together with your writing abilities as neatly as with the format on your blog.
    Is that this a paid theme or did you customize it yourself?
    Anyway stay up the excellent high quality writing, it’s rare to see a great blog
    like this one nowadays..

  • You have made some good points there. I checked on the net
    for more info about the issue and found most people will
    go along with your views on this web site.

  • Hi to every , as I am truly keen of reading this weblog’s post to be
    updated on a regular basis. It includes nice data.

  • Hi, I do think this is an excellent blog. I stumbledupon it 😉 I
    may return yet again since i have book-marked it.
    Money and freedom is the greatest way to change, may you be rich and continue to help others.

  • I’ve been surfing on-line greater than 3
    hours lately, yet I by no means discovered any fascinating article like yours.

    It is pretty value enough for me. In my opinion, if all site owners and bloggers
    made excellent content as you did, the web might be much more useful than ever before.

  • I will right away take hold of your rss feed as
    I can not find your e-mail subscription link or newsletter
    service. Do you’ve any? Kindly permit me recognise in order that
    I may subscribe. Thanks.

  • I visited many sites however the audio quality for audio
    songs existing at this site is truly fabulous.

  • I simply could not go away your website before suggesting that I actually loved the usual information a person provide for your visitors?
    Is gonna be back frequently to investigate cross-check new posts

  • It iis perdect ime too make soome pplans for the futture annd it’s timee to bee happy.
    I hace read thiss ost andd iif I could I dwsire too
    suggeest yyou slme interesting thinggs orr tips.

    Maybe yoou ould wwrite newxt artiicles referring tto thhis article.

    I dedsire to read even molre thinngs aboput it!

  • I’ve been browsing on-line greater than three hours these days, but I by no means found any fascinating article like yours.
    It’s lovely price sufficient for me. Personally, if all site owners
    and bloggers made just right content as you did, the internet will be much more helpful than ever before.

  • Hi, I do believe this is a great website. I stumbledupon it ;
    ) I’m going to come back once again since I book-marked it.
    Money and freedom is the greatest way to change, may
    you be rich and continue to help others.

  • It’s appropriate time to make some plans for the future and it
    is time to be happy. I have learn this publish and
    if I may I desire to recommend you few attention-grabbing issues or advice.

    Perhaps you can write next articles referring to this article.

    I want to read more things approximately it!

  • These are actually wonderful ideas in concerning blogging.
    You have touched some good factors here. Any way keep up wrinting.

  • Thanks for the auspicious writeup. It in fact used to be a amusement account it. Glance complex to far added agreeable from you! However, how can we keep in touch?

Добавить комментарий

Ваш адрес email не будет опубликован.

Найти на сайте
Со страниц сайта
Метки
хохмаУмные мыслиармейский юморДела семейныеДокторинформацияой болитфольклорВовочка & kidsВадим ЗверевПолитическиеСтатусы ВКотактеСобрание скороговорокБольшие и малые народностиПро животныхЗаконы МерфиженщиныПро это...Забойный наборНиколай ФоменкоВсякая всякотаалкоманы-наркоголикиПро услуги и рестораныВиктор ШендеровичБородатые анекдотыавтомобилистыТуристы и турыИскусство и киноПро работуКозьма ПрутковПро студентовОмар ХайямЧерномырдинСтатусы про женщин и мужчинВ общественном транспортеПро сумасшедшихСтанислав Ежи ЛецКриминальныеПро ШтирлицаСтас ЯнковскийСмешные статусыДурацкие законыПро юристовпро самолетыПечалькаПро братковХорошие советыНе та ориентацияМарк ТвенСтатусы про жизньНа селеКрасноармейскиеГусары и поручикиДразнилкиИностранные анекдотыСказочныеХрюн МоржовФрансуа де ЛарошфукоЧерный юморЖан-Жак РуссоОхота и рыбалкаПрограммистыЛеди и джентельменыСпортНа бога надейся...МультяшкиБизнесСчиталкиУильям ШекспирГеоргий ФрумкерФрансис БэконПраздникиДикий западШутливая лотереяБедные и богатыеРаневскаяПьер Огюстен Карон де БомаршеСоветы и ответыДикариИсторические анекдотыНикколо МакиавеллиНаполеон БонапартЗагадкиsongswordpresstraditionalpluginпоговоркиC#старостьmysqlЧастушкиbackendjavascripthostingsshajaxphpстатистикапандемия
Больше Меньше
Архивы
Рейтинг@Mail.ru