C # webbrowser cannot be opened in a new window. It must be opened in this window.

Source: Internet
Author: User

When developing webBrower, you will certainly encounter a problem.
That is how to force a new window in this window.
The most common solution on the internet is,
InNewwindowEvent to open the URL, cancel the new window, and then open the URL to switch in this window
P rivate void webBrowser_1_NewWindow (object sender, CancelEventArgs e)
{
WebBrowser webBrowser_temp = (WebBrowser) sender;
String newUrl = webBrowser_temp.Document.ActiveElement.GetAttribute ("href ");
WebBrowser_1.Url = new Uri (newUrl );
E. Cancel = true;
}

Although this method can solve most of the requirements, it does not cure the symptoms.
In addition, it is even more troublesome when there are Chinese characters in the website. For example, in Baidu MP3, Song names are both Chinese characters, and in Baidu space, most user names are Chinese characters, the URLs are garbled. Although, you can code the web site, but not all web pages are uft-8 code, for how to know the Web Page code is a subject.

The most fundamental method is to rewrite it.
Create a class
Using System;
Using system. Collections. Generic;
Using system. text;

Namespace webtestrecorder
{

Public class extendedwebbrowser: system. Windows. Forms. webbrowser
{
System. Windows. Forms. axhost. connectionpointcookie;
Webbrowserextendedevents events;

// This method will be called to give you a chance to create your own event sink
Protected override void createsink ()
{
// Make sure to call the base or the normal events won't fire
Base. createsink ();
Events = new webbrowserextendedevents (this );
Cookie = new system. Windows. Forms. axhost. connectionpointcookie (this. activexinstance, events, typeof (dwebbrowserevents2 ));
}

Protected override void detachsink ()
{
If (null! = Cookie)
{
Cookie. Disconnect ();
Cookie = NULL;
}
Base. detachsink ();
}

// This new event will fire when the page is navigating
Public event eventhandler <webbrowserextendednavigatingeventargs> beforenavigate;
Public event eventhandler <webbrowserextendednavigatingeventargs> beforenewwindow;

Protected void onbeforenewwindow (string URL, out bool cancel)
{
EventHandler <WebBrowserExtendedNavigatingEventArgs> h = BeforeNewWindow;
WebBrowserExtendedNavigatingEventArgs args = new WebBrowserExtendedNavigatingEventArgs (url, null );
If (null! = H)
{
H (this, args );
}
Cancel = args. Cancel;
}

Protected void OnBeforeNavigate (string url, string frame, out bool cancel)
{
EventHandler <WebBrowserExtendedNavigatingEventArgs> h = BeforeNavigate;
WebBrowserExtendedNavigatingEventArgs args = new WebBrowserExtendedNavigatingEventArgs (url, frame );
If (null! = H)
{
H (this, args );
}
// Pass the cancellation chosen back out to the events
Cancel = args. Cancel;
}
// This class will capture events from the WebBrowser
Class WebBrowserExtendedEvents: System. Runtime. InteropServices. standardoleexternalobject, DWebBrowserEvents2
{
ExtendedWebBrowser _ Browser;
Public WebBrowserExtendedEvents (ExtendedWebBrowser browser) {_ Browser = browser ;}

// Implement whichever events you wish
Public void beforenavigate2 (Object Pdisp, ref object URL, ref object flags, ref object targetframename, ref object postdata, ref object headers, ref bool cancel)
{
_ Browser. onbeforenavigate (string) URL, (string) targetframename, out cancel );
}

Public void newwindow3 (Object Pdisp, ref bool cancel, ref object flags, ref object urlcontext, ref object URL)
{
_ Browser. onbeforenewwindow (string) URL, out cancel );
}

}
[System. runtime. interopservices. comimport (), system. runtime. interopservices. GUID ("34a715a0-6587-11d0-924a-0020afc7ac4d "),
System. runtime. interopservices. interfacetypeattribute (system. runtime. interopservices. cominterfacetype. interfaceisidispatch ),
System. runtime. interopservices. typelibtype (system. runtime. interopservices. typelibtypeflags. fhidden)]
Public interface dwebbrowserevents2
{

[System. Runtime. InteropServices. DispId (250)]
Void BeforeNavigate2 (
[System. Runtime. InteropServices. In,
System. Runtime. InteropServices. financialas (System. Runtime. InteropServices. UnmanagedType. IDispatch)] object pDisp,
[System. Runtime. InteropServices. In] ref object URL,
[System. Runtime. InteropServices. In] ref object flags,
[System. runtime. interopservices. In] ref object targetframename, [system. runtime. interopservices. In] ref object postdata,
[System. runtime. interopservices. In] ref object headers,
[System. runtime. interopservices. In,
System. runtime. interopservices. Out] ref bool cancel );
[System. runtime. interopservices. dispid (273)]
Void newwindow3 (
[System. Runtime. InteropServices. In,
System. Runtime. InteropServices. financialas (System. Runtime. InteropServices. UnmanagedType. IDispatch)] object pDisp,
[System. Runtime. InteropServices. In, System. Runtime. InteropServices. Out] ref bool cancel,
[System. Runtime. InteropServices. In] ref object flags,
[System. Runtime. InteropServices. In] ref object URLContext,
[System. runtime. interopservices. In] ref object URL );

}
}

Public class webbrowserextendednavigatingeventargs: system. componentmodel. canceleventargs
{
P rivate string _ URL;
Public String URL
{
Get {return _ URL ;}
}

P rivate string _ frame;
Public String Frame
{
Get {return _ Frame ;}
}

Public WebBrowserExtendedNavigatingEventArgs (string url, string frame)
: Base ()
{
_ Url = url;
_ Frame = frame;
}
}
}

 

Replace webBrowser with ExtendedWebBrowser, which we override, and add event processing.
IeBrowser = new ExtendedWebBrowser ();
IeBrowser. BeforeNewWindow + = new EventHandler <WebBrowserExtendedNavigatingEventArgs> (ieBrowser_BeforeNewWindow );

ThenBeforenewwindowEvent:

Void ieBrowser_BeforeNewWindow (object sender, WebBrowserExtendedNavigatingEventArgs e ){
E. Cancel = true;
(ExtendedWebBrowser) sender). Navigate (e. Url );
}

--------------------- Under another solution ----------------------

 

To solve this problem, you can use the following method:

In daily development, you sometimes need to use WebBrowser to load URLs to implement some functions. At this time, we do not want to open the link in the page, open in the new window, because in this case, it is actually opened in the default browser of the system, thus breaking away from your WebBrowser, you cannot control it.

Assume that the Name of WebBrowser is webBrowser1.

* ****** Void webbrowserappsdocumentcompleted (object sender, WebBrowserDocumentCompletedEventArgs e)

{// Point the target of all links to this form

Foreach (htmlelement archor in this. webbrowser1.document. Links)

{

Archor. setattribute ("target", "_ Self ");

} // Point all the form submission targets to the form foreach (htmlelement form in this. webbrowser1.document. forms) {form. setattribute ("target", "_ Self ");}}

* ***** Void webbrowser1_newwindow (Object sender, canceleventargs e) {e. Cancel = true ;}

 

Remember to set allowwebbrowserdrop of webbrowser to false.

Set webbrowsershortcutsenabled of webbrowser to false

Set iswebbrowsercontextmenuenabled of webbrowser to false

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.