In my WinForms app I used WebView2 to show thrird-party content.
When user clicks the link (or other navigation element) inside the webView, the target link should be opened in the default browser (not in the webView).
For most cases I was able to implement desired behaviour with NewWindowRequested and NavigationStarting events.
But for anchor navigation inside the current page (<a href="#my_anchor">) these events are not firing.
There is a SourceChanged event, which is fired in case on anchor navigation, and it even allows to determine that this is in-page navigation by checking IsNewDocument, but it does not allow to cancel the navigation.
I was thinking about js-based solution, something like subscribing to click events for all a tags or even for whole document with further filtering. But I realized that such a solution will not work in many non-trivial cases, including
dynamically created a elements
keyboard navigation (TAB to select link, Enter to initiate action, so no click event)
the cases when there are a lot of elements (img, etc) inside a element and user clicked on such an internal element
when navigation is initiated with js
So, is the way exists to handle and cancel any navigation, including anchors in the current page?
I had the same request. I'm using Win32 C++, and for me the NewWindowRequested event does fire on anchor navigation, and I added this implementation to cancel the default behaviour and open the Uri in the default browser instead...
// Register a handler for the NewWindowRequested event.
CHECK_FAILURE(m_webView->add_NewWindowRequested(
Callback<ICoreWebView2NewWindowRequestedEventHandler>(
[this](ICoreWebView2* sender, ICoreWebView2NewWindowRequestedEventArgs* args) {
// get the target Uri
LPWSTR sUri;
CHECK_FAILURE(args->get_Uri(&sUri));
// and if it was user initiated (e.g. click on an anchor tag)
BOOL bUserInit;
CHECK_FAILURE(args->get_IsUserInitiated(&bUserInit));
if (bUserInit) {
// cancel default behaviour
args->put_Handled(TRUE);
// and open Uri in default browser
ShellExecute(0, 0, sUri, 0, 0, SW_SHOW);
}
return S_OK;
})
.Get(), nullptr));
I also faced this issue, as a workaround I've made this:
//MainWindow.xaml
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:wv2="clr-namespace:Microsoft.Web.WebView2.Wpf;assembly=Microsoft.Web.WebView2.Wpf"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
x:Name="MainWindow"
x:Class="WebBrowser.MainWindow"
mc:Ignorable="d"
FontSize="14" Title="WebView2 Test" Width="400" Height="400" WindowStartupLocation="Manual"
SizeToContent="Manual" Cursor="Wait"
WindowStyle="None" ResizeMode="NoResize" PreviewKeyDown="AdvertisementWindow_PreviewKeyDown">
<DockPanel>
<wv2:WebView2 Name="myWebBrowser"/>
</DockPanel>
</Window>
MainWindow.xaml.cs Source code
using System.Windows;
using System.Windows.Input;
using Microsoft.Web.WebView2.Core;
namespace WebBrowser
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private string url = "https://en.wikipedia.org/wiki/Hyperlink";
public MainWindow()
{
InitializeComponent();
InitializeAsync();
myWebBrowser.NavigationStarting += MyWebBrowser_NavigationStarting;
myWebBrowser.SourceChanged += MyWebBrowser_SourceChanged;
}
private void MyWebBrowser_SourceChanged(object sender, CoreWebView2SourceChangedEventArgs e)
{
string uri = myWebBrowser.Source.ToString();
if (e.IsNewDocument == false && uri.EndsWith("#Further_reading"))
{
MessageBox.Show("You clicked #Further_reading", "Further Reading");
}
}
async void InitializeAsync()
{
await myWebBrowser.EnsureCoreWebView2Async(null);
myWebBrowser.CoreWebView2.Navigate(url);
}
private void AdvertisementWindow_PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
if(e.Key == Key.Escape)
{
Close();
}
}
private void MyWebBrowser_NavigationStarting(object sender, Microsoft.Web.WebView2.Core.CoreWebView2NavigationStartingEventArgs e)
{
//cancel the current event
if (!e.Uri.ToString().StartsWith(url))
{
e.Cancel = true;
System.Diagnostics.Process.Start(e.Uri.ToString());
}
}
}
}
This code should open each link in an external browser (the default system browser) and anchors to external pages will be opened in the external browser too. So it means that we cancel navigating in the WebView (e.Cancel = True). Regarding anchors to the same site, we can handle them in the SourceChanged event, and we don't need to stop navigating as it will stay on the same page.
Related
I have a fairly simple C# WPF application using .NET 5. Basically it sits in the background and times specific events for the end user. The events are built from a xml file that is generated externally.
The application consists of 2 windows, one hidden that does all the thinking. If it detects that an event is due it raises a toast message which when clicked on opens the other window to show the event details to the user. All works fine and runs as expected except after a windows sleep/suspend and resume. We obviously don't want the events to add up upon sleep/suspend and so we close the hidden window and upon resume open it again. No problems there but once the system is resumed and an event is raised the visible window refuses to show. If the visible window is open when sleep/suspend happens then upon resume the whole window is frozen and refuses to respond (only way to close the window is kill the application and restart)
The APP code is as follows :-
public static Forms.NotifyIcon notifyIcon;
public static MainWindow mw;
public static ConfigWindow cw;
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
SystemEvents.PowerModeChanged += new PowerModeChangedEventHandler(SystemEvents_PowerModeChanged);
// Listen to notification activation
ToastNotificationManagerCompat.OnActivated += toastArgs =>
{
// Obtain the arguments from the notification
ToastArguments args = ToastArguments.Parse(toastArgs.Argument);
// Obtain any user input (text boxes, menu selections) from the notification
ValueSet userInput = toastArgs.UserInput;
// Need to dispatch to UI thread if performing UI operations
Application.Current.Dispatcher.Invoke(delegate
{
ToastControl.HandleToast(args);
});
};
ConfNotifyIcon();
OpenApp();
}
private void ConfNotifyIcon()
{
notifyIcon = new Forms.NotifyIcon();
notifyIcon.Icon = new System.Drawing.Icon("Images/Wellformation.ico");
notifyIcon.DoubleClick += OnClick;
notifyIcon.ContextMenuStrip = new Forms.ContextMenuStrip();
notifyIcon.ContextMenuStrip.Items.Add("Open", System.Drawing.Image.FromFile("Images/Wellformation.ico"), OnClick);
notifyIcon.ContextMenuStrip.Items.Add("Close", System.Drawing.Image.FromFile("Images/Wellformation.ico"), OnClose);
notifyIcon.ContextMenuStrip.Items.Add(new Forms.ToolStripSeparator());
notifyIcon.ContextMenuStrip.Items.Add("Exit", System.Drawing.Image.FromFile("Images/Wellformation.ico"), OnExit);
}
private void SystemEvents_PowerModeChanged(object sender, PowerModeChangedEventArgs e)
{
switch (e.Mode)
{
case PowerModes.Suspend:
this.Dispatcher.BeginInvoke((Action)(() =>
{
PrepareLock();
}), null);
break;
case PowerModes.Resume:
this.Dispatcher.BeginInvoke((Action)(() =>
{
PrepareAwake();
}), null);
break;
default:
break;
}
}
private void PrepareAwake()
{
OpenApp();
ConfNotifyIcon();
notifyIcon.Visible = true;
}
private void PrepareLock()
{
notifyIcon.Dispose();
cw.Close();
}
private void OnExit(object sender, EventArgs e)
{
Application.Current.Shutdown();
}
private void OnClose(object sender, EventArgs e)
{
mw.Close();
}
private void OnClick(object sender, EventArgs e)
{
OpenMain();
}
private void OpenMain()
{
mw = new();
mw.Show();
mw.Activate();
}
public static void OpenApp()
{
cw = new ConfigWindow();
}
The hidden Window XAML is as follows :-
<Window x:Class="WellformationDesktopApplication.ConfigWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WellformationDesktopApplication"
mc:Ignorable="d"
Title="ConfigWindow" Height="1" Width="1" Visibility="Hidden" WindowState="Minimized">
<Grid>
</Grid>
</Window>
with code as follows :-
Timer at = new();
public ConfigWindow()
{
BuildConfig();
InitializeComponent();
}
public void refreshconfig()
{
myObjects.Clear();
myObjects = NudgeManager.GetNudges();
NudgeHandler(myObjects);
}
public void BuildConfig()
{
myObjects.Clear();
myObjects = GetEvents(); // pulls a list of event names with intervals from the config file
EventHandler(myObjects); //Goes through the list of events and figures out when the next event is due based upon the interval in the configuration
ActionTimer();
}
private void ActionTimer()
{
at.Interval = 60000;
at.Elapsed += ChecktActions;
at.AutoReset = true;
at.Enabled = true;
}
private void ChecktActions(object sender, ElapsedEventArgs e)
{
//Go through the trigger times for all events and see if those time have passed, if they have raise a toast showing the event name.
//If an event is raised reset the trigger time for the event based upon the interval and reset that time.
}
and the visible window XAML is as follows :-
<Window x:Class="WellformationDesktopApplication.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WellformationDesktopApplication"
mc:Ignorable="d"
ResizeMode="NoResize"
WindowStyle="None"
Title="MainWindow" Height="500" Width="800" Background="{x:Null}" Foreground="{x:Null}" AllowsTransparency="True">
<Grid x:Name="BG">
<TextBlock x:Name="Display" HorizontalAlignment="Left" Margin="546,13,0,0" Text="Show event name and appropriate information about the event here..." VerticalAlignment="Top" FontSize="22"/>
</Grid>
</Window>
With Code as follows :-
public MainWindow()
{
InitializeComponent();
setstyles();
this.MouseLeftButtonDown += delegate { DragMove(); };
}
We know that everything to do with the ConfigWindow works fine, we know it is closed upon suspend and a new one is opened on resume with new timings set and all the appropriate alerts working.
The issue is with MainWindow as after a suspend and resume it cannot be interacted with at all. The open button on the icon does nothing, if the window is opened is is completely frozen and cannot be interacted with in any way, and if a toast is clicked on the window does not open but the rest of the toast handling code works fine around it. This happens on Win8, Win10 and Win11.
Any help out there as I am completely at a loss for how this is happening?
Thanks
After much work and going through the code section by section commenting it out to see if it made a difference I have found the issue.
Buried deep inside the the code for the hidden window (4 calls to functions down the line) I found that the EventHandler() was also raising a listener for
SystemEvents.SessionSwitch += new SessionSwitchEventHandler(OnSessionSwitch);
With all the associated functions buried in a separate class that was not directly referenced from the window itself.
When this line was commented out everything worked fine, with it in and attached to the hidden window after Suspend/Resume of windows no UI changes would take place throughout the whole code (hence hidden window continued to working completely fine as it did not interact with the UI).
By lifting this code out into the APP space and handling it there rather than in a window the problem has gone away (though has revealed other issues that were not being handled upon Resume of Windows that I now have to fix).
So the answer is that for a WPF application listeners for SystemEvents of any type need to be housed int the APP code space and not within windows.
I have page1 with a button that opens page2. Page2 takes approx 1 second to open and contains a list of options (user controls) that when tapped, saves the selection and returns the user to page1.
When the user taps the button on page1, if they become impatient, they will tap it again before page2 has loaded/displayed. the problem is, that the tap is recognised and the first option on page2 is tapped, even though it's not yet visible. This then saves the selection and returns the user to page1.
Is there anyway I can stop the tap/click event being recognised until the page2 has fully loaded?
One idea may be to subscribe to the Tap/Click event in OnNaviagatedTo on first page, then inside Tap/Click event unsubscribe it, so that user won't be able to click it again. Then when he navigates back, OnNavigatedTo subscribes again. You may also think about flag that will be set up upon Tap/Click and dismissed in Loaded event of second page. Sample:
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
Debug.WriteLine("OnNavigatedTo");
base.OnNavigatedTo(e);
this.button.Click += Button_Click;
}
private async void Button_Click(object sender, RoutedEventArgs e)
{
(sender as Button).Click -= Button_Click;
await Task.Delay(1000); // simulate heavy load of second page
this.Frame.Navigate(typeof(SecondPage));
}
}
I wrote a small control that creates a popup for my Win8 Phone application which does all the nasty things for me like rotation, proper placement etc.
The popup is opened in a Popup control but not on a new phone page.
To close the popup, my control hooks up to the "backKeyPressed" event of the underlying page.
This works like charm until the underlying page has its own implementation of BackKeyPressed event. In this case, the page event is triggered but not the popup control event.
If I would own the event, I could create my own stack to call the last added event first, but I do not own the event of the pages.
As far as I know, I am unable to unregister any previously attached event handler and reassign it once my control unsubscribes from the event.
I could have only one implementation for the BackKeyPressed event which then informs the popup control to close itself (if open), if nothing was open, do the Page specific implementation. But this would require code changes on all pages where I might want to use the popup. Even worse, if I have 5 possible popups, I would have to check all of them :-(
So I am looking for an option to handle this centrally.
What other options do I have to overcome this situation?
Normally you cannot change the order of fired events - they are executed in registered order, but it's not required by specifications - source.
But as Jon Skeet says here:
Summary: For all sane events, you can rely on the ordering. In theory, events can do what they like, but I've never seen an event which doesn't maintain the appropriate ordering.
it is fired in registered order and should be.
BUT for your purpose (I think) you can set an event to invoke your method where you would control the order. I think simple example can show this behaviour:
public partial class MainPage : PhoneApplicationPage
{
private List<EventHandler<CancelEventArgs>> listOfHandlers = new List<EventHandler<CancelEventArgs>>();
private void InvokingMethod(object sender, CancelEventArgs e)
{
for (int i = 0; i < listOfHandlers.Count; i++)
listOfHandlers[i](sender, e);
}
public event EventHandler<CancelEventArgs> myBackKeyEvent
{
add { listOfHandlers.Add(value); }
remove { listOfHandlers.Remove(value); }
}
public void AddToTop(EventHandler<CancelEventArgs> eventToAdd)
{
listOfHandlers.Insert(0, eventToAdd);
}
public MainPage()
{
InitializeComponent();
this.BackKeyPress += InvokingMethod;
myBackKeyEvent += (s, e) => { MessageBox.Show("Added first"); e.Cancel = true; };
AddToTop((s, e) => { MessageBox.Show("Added later"); });
}
}
I have a pretty simple problem but I can't get it to work. I want a MessageBox to appear each time I left click inside my form. I didn't know how to capture it on the whole form so I started of trying to capture my left click inside my WebBrowser1. However, nothing really happens when trying to trigger the event.
I declared the action as WebBrowser1_Mousedown.
private void WebBrowser1_Mousedown(object sender, MouseButtonEventArgs e)
{
if (e.LeftButton == MouseButtonState.Pressed)
{
MessageBox.Show("test");
}
}
What am I doing wrong?
My relevant XAML as follows:
<Window x:Class="IndianBrowser.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="488.806" Width="807.089" MouseDown="Window_MouseDown">
and now trying with the webbrowser:
<WebBrowser x:Name="WebBrowser1" HorizontalAlignment="Stretch" Height="auto" Margin="0,85,0,0" VerticalAlignment="Stretch" Width="auto" MouseDown="WebBrowser1_Mousedown"/>
If you look into MSDN documentation for WebBrowser class, you'll see that mouse events are not supported. What you can do instead is subscribe for HtmlDocument.MouseDown event.
Update
Here is small snippet that demonstrates how to do this in WPF, NOTE you will have to add reference to Microsoft.mshtml assembly:
public MainWindow()
{
InitializeComponent();
this.webBrowser1.Navigated += webBrowser1_Navigated;
this.webBrowser1.Source = new Uri("your url");
}
void webBrowser1_Navigated(object sender, NavigationEventArgs e)
{
HTMLDocumentClass document = this.webBrowser1.Document as HTMLDocumentClass;
document.HTMLDocumentEvents2_Event_onclick += document_HTMLDocumentEvents2_Event_onclick;
}
bool document_HTMLDocumentEvents2_Event_onclick(IHTMLEventObj pEvtObj)
{
// here you can check if the clicked element is your form
// if (pEvtObj.fromElement.id == "some id")
MessageBox.Show("test");
return true;
}
I have this code:
Mouse.AddPreviewMouseDownOutsideCapturedElementHandler(this,
OnMouseDownOutsideCapture);
And it fully captures when a mouse click happens outside my WPF Popup (so I can close it).
private void OnMouseDownOutsideCapture(object sender, MouseButtonEventArgs e)
{
if (Mouse.Captured is ComboBox) return;
if (IsOpen)
IsOpen = false;
ReleaseMouseCapture();
}
But I need some way to know if the focus is moved outside my popup via the keyboard. More specifically by an shortcut (ie Alt + T).
Right now, my popup does not close when the user moves focus off it that way. Any ideas?
This is how I did it:
Add this to the constructor:
EventManager.RegisterClassHandler(typeof(UIElement),
Keyboard.PreviewGotKeyboardFocusEvent,
(KeyboardFocusChangedEventHandler)OnPreviewAnyControlGotKeyboardFocus);
Then add this event handler:
/// <summary>
/// When focus is lost, make sure that we close the popup if needed.
/// </summary>
private void OnPreviewAnyControlGotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
// If we are not open then we are done. No need to go further
if (!IsOpen) return;
// See if our new control is on a popup
var popupParent = VLTreeWalker.FindParentControl<Popup>((DependencyObject)e.NewFocus);
// If the new control is not the same popup in our current instance then we want to close.
if ((popupParent == null) || (this.popup != popupParent))
{
popupParent.IsOpen = false;
}
}
VLTreeWalker is a custom class that walks up the visual tree looking for a match to the passed in generic type and then (if it does not find a matching item, will walk up the logical tree.) Sadly, I can't easily post the source for that here.
this.popup is the instance that you are comparing against (that you want to know if it should close).
You could add a KeyDown event and check if alt+tab were pressed.