How to hide the Download dialog in WebView2 while downloading page content or printing with "Save as PDF" option? - winforms

I know how to subscribe to the CoreWebview2.DownloadStarting event and use handled = true to stop the Download dialog from showing while a download (i.e. an image) is being made, but the problem is the DownloadStarting event never fires if you right click on a web page and choose "Save as" or "Print > Save as PDF", even though the Download dialog will appear as if a regular download was being made. Does anyone know any workaround for this?
My code:
public Form1()
{
InitializeComponent();
}
private async void button1_Click(object sender, EventArgs e)
{
if (webView != null)
webView.Dispose();
webView = new WebView2();
await webView.EnsureCoreWebView2Async();
webView.CoreWebView2.DownloadStarting += CoreWebView2_DownloadStarting;
panel1.Controls.Add(webView);
webView.Dock = DockStyle.Fill;
webView.Source = new Uri("https://www.microsoft.com");
}
private void CoreWebView2_DownloadStarting(object sender, CoreWebView2DownloadStartingEventArgs e)
{
e.Handled = true;
}

I just found a solution:
subscribe to CoreWebView2.IsDefaultDownloadDialogOpenChanged event:
webView.CoreWebView2.IsDefaultDownloadDialogOpenChanged += webView_CoreWebView2_IsDefaultDownloadDialogOpenChanged;
Close the Download dialog if it's open:
private void webView_CoreWebView2_IsDefaultDownloadDialogOpenChanged(object sender, object e)
{
if (webView.CoreWebView2.IsDefaultDownloadDialogOpen) webView.CoreWebView2.CloseDefaultDownloadDialog();
}

Related

Disable drag and drop from webbrowser control c#

I am trying to prevent users from dragging images that display in my webbrowser control.
I tried setting webbrowser.Document.MouseOver e.Cursor = Cursors.No Still not working.
I tried a few other ways.
I am unable to prevent images being dragged on the desktop.
Is it possible to prevent dragging of images from webbrowser control to desktop?
There is a way to prevent the body element of the HTML document to handle drag operation.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
this.webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);
this.webBrowser1.Url = new Uri("https://www.google.bg/search?q=stackoverflow&biw=1920&bih=950&source=lnms&tbm=isch&sa=X&sqi=2&ved=0ahUKEwjw2cWH4oTQAhVG8RQKHWCWB4AQ_AUIBigB");
}
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
this.webBrowser1.Document.Body.Drag += new HtmlElementEventHandler(Body_Drag);
}
private void Body_Drag(object sender, HtmlElementEventArgs e)
{
e.ReturnValue = false;
}
}

dynamically add webbrowser control in windows chat application:

I am developing windows form chat application and i am writing message in richtextbox but when i click on send button and every message show in webbrowser control. .i want to add webbrowser control dynamically for individual message is send.i am using following code:
namespace WindowsFormsApplication1
{
[ComVisible(true)]
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
// this.w1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(w1_DocumentCompleted);
}
WebBrowser w1 = new WebBrowser();
private void button1_Click(object sender, EventArgs e)
{
this.Controls.Add(w1);
HtmlElement div = w1.Document.GetElementById("abc");
div.InnerHtml = richTextBox1.Text;
}
private void Form1_Load(object sender, EventArgs e)
{
w1.Navigate(Path.Combine(Environment.CurrentDirectory, "HTMLPageForScripting.htm"));
}
}
}
Here is the case you asked for:
Add a Panel to form to put browser in and set its autoscroll property to true;
In button1 Click event, create browser, set its width and height, and navigate to the document you want.
In button1 Click event subscribe for DocumentCompleted event and add content there. We do add here because we should be sure all contents containing <div id="abc"></div>has been loaded.
Here is code:
private void button1_Click(object sender, EventArgs e)
{
var browser = new WebBrowser();
browser.Height = 100;
browser.Dock = DockStyle.Top;
browser.Navigate(#"D:\test.html");
browser.DocumentCompleted += browser_DocumentCompleted;
this.panel1.Controls.Add(browser);
//Just do it to put it at the end of list and scroll to it
browser.BringToFront();
this.panel1.ScrollControlIntoView(browser);
}
void browser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
var browser = (WebBrowser)sender;
HtmlElement div = browser.Document.GetElementById("abc");
div.InnerHtml = richTextBox1.Text;
}

New tab in WPF - items.add from buttons vs methods

OK, so I have a window called PictureWindow which displays pictures (I've cut out the code not related to making tabs). The TabControl is named "itemsTab". Using a button press, I can make a new tab no problem. But using the same operations inside a called method doesn't work. Using the buttonTab_Click method makes a new tab, the newTab method does not.
The only real difference I can see is due to the sender and RoutedEventArgs objects - how do these effect the operation here? Or is there something else I'm missing?
Thanks in advance.
Edit To make things even stranger, the newTab method does make a new tab, but only if it is called in the PictureWindow constructor method. If I have the following a new tab is made.
public PictureWindow(string current)
{
InitializeComponent();
newTab(current);
}
But if I call the method anywhere else it doesn't work.
public partial class PictureWindow : Window
{
public PictureWindow(string current)
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
}
private void buttonClose_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
private void buttonTab_Click(object sender, RoutedEventArgs e)
{
TabItem newTab = new TabItem();
newTab.Header = "New Tab!";
itemsTab.Items.Add(newTab);
}
public void newTab(string current)
{
TabItem newTab = new TabItem();
itemsTab.Items.Add(newTab);
}
}

Silverlight InvalidOperationException when clicking a link

I have a dynamically generated hyperlink which when clicked should open a lotus notes document. I do it using the code below.
HyperlinkButton hlb = new HyperlinkButton();
hlb.SetBinding(HyperlinkButton.ContentProperty, new Binding("Properties[" + col.DisplayField + "]"));
hlb.SetBinding(HyperlinkButton.NavigateUriProperty, new Binding("Properties[" + col.LinkField + "]"));
hlb.Click += new RoutedEventHandler(hlb_Click);
RootGrid.Children.Add(hlb);
this is the code that fires when the link is clicked.
static void hlb_Click(object sender, RoutedEventArgs e)
{
HyperlinkButton hlb = (HyperlinkButton)sender;
var hostingWindow = HtmlPage.Window;
hostingWindow.Navigate(hlb.NavigateUri);
}
the lotus notes document opens correctly but I get a System.InvalidOperationException, the details of which are given below
Description: Failed to navigate to notes://<path to the document>
Stacktrace:
at MS.Internal.NavigationHelper.Navigate(Boolean checkUserInitiatedAction)
at System.Windows.Controls.HyperlinkButton.OnClick()
at System.Windows.Controls.Primitives.ButtonBase.OnMouseLeftButtonUp(MouseButtonEventArgs e)
at System.Windows.Controls.Control.OnMouseLeftButtonUp(Control ctrl, EventArgs e)
at MS.Internal.JoltHelper.FireEvent(IntPtr unmanagedObj, IntPtr unmanagedObjArgs, Int32 argsTypeIndex, Int32 actualArgsTypeIndex, String eventName)
Another interesting thing to note is that it is raised on another thread and hence is not caught when the hostingWindow.Navigate method is fired.
Any ideas ?
Using Silverlight 5, I wrapped the call to open the Lotus Notes doc link within a task and was able to open the link without generating an error.
private void TryOpenDocLink()
{
TaskScheduler ts = TaskScheduler.Default;
Task<bool> task = OpenDocLink();
task.ContinueWith(t =>
{
if (t.Exception != null)
{
this.SetError(t.Exception.Message, enMessageLevel.Error);
}
});
}
private Task<bool> OpenDocLink()
{
TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>();
try
{
var hostWindow = HtmlPage.Window;
hostWindow.Navigate(new Uri(DocLinkPath));
tcs.SetResult(true);
}
catch (Exception)
{
tcs.SetResult(false);
}
return tcs.Task;
}
Try marking the click event as handled:
static void hlb_Click(object sender, RoutedEventArgs e)
{
e.Handled = true;
HyperlinkButton hlb = (HyperlinkButton)sender;
var hostingWindow = HtmlPage.Window;
hostingWindow.Navigate(hlb.NavigateUri);
}
I'm not sure that this will fix the issue. The error is coming from the click event code inside the hyperlink button. You can tell because that code uses the NavigationHelper class while the Window.Navigate method does not.
Is there a reason you're not just letting the hyperlink button do the navigation?

WPF: Button single click + double click issue

I have to handle both the single click and the double click of a button in a WPF application with different reaction.
Unfortunately, on a doubleclick, WPF fires two click event and a double click event, so it's hard to handle this situation.
It tried to solve it using a timer but without success...I hope you can help me.
Lets see the code:
private void delayedBtnClick(object statInfo)
{
if (doubleClickTimer != null)
doubleClickTimer.Dispose();
doubleClickTimer = null;
this.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new VoidDelegate(delegate()
{
// ... DO THE SINGLE CLICK ACTION
}));
}
private void btn_Click(object sender, RoutedEventArgs e)
{
if (doubleClickTimer == null)
doubleClickTimer = new Timer(delayedBtnClick, null, System.Windows.Forms.SystemInformation.DoubleClickTime, Timeout.Infinite);
}
}
}
private void btnNext_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
if (doubleClickTimer != null)
doubleClickTimer.Change(Timeout.Infinite, Timeout.Infinite); // disable it - I've tried it with and without this line
doubleClickTimer.Dispose();
doubleClickTimer = null;
//.... DO THE DOUBLE CLICK ACTION
}
The problem is that the 'SINGLE CLICK ACTION' called after the 'DOUBLE CLICK ACTION' on doubleclick. It's strange that I set thedoubleClickTimer to null on double click but in the delayedBtnClick it's true :O
I've already tried to use longer time, a bool flag and lock...
Do you have any ideas?
Best!
If you set the RoutedEvent's e.Handled to true after handling the MouseDoubleClick event then it will not call the Click Event the second time after the MouseDoubleClick.
There's a recent post which touches on having different behaviors for SingleClick and DoubleClick which may be useful.
However, if you are sure you want separate behaviors and want/need to block the first Click as well as the second Click, you can use the DispatcherTimer like you were.
private static DispatcherTimer myClickWaitTimer =
new DispatcherTimer(
new TimeSpan(0, 0, 0, 1),
DispatcherPriority.Background,
mouseWaitTimer_Tick,
Dispatcher.CurrentDispatcher);
private void Button_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
// Stop the timer from ticking.
myClickWaitTimer.Stop();
Trace.WriteLine("Double Click");
e.Handled = true;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
myClickWaitTimer.Start();
}
private static void mouseWaitTimer_Tick(object sender, EventArgs e)
{
myClickWaitTimer.Stop();
// Handle Single Click Actions
Trace.WriteLine("Single Click");
}
You could try this:
Button.MouseLeftButtonDown += Button_MouseLeftButtonDown;
private void Button_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
e.Handled = true;
if (e.ClickCount > 1)
{
// Do double-click code
}
else
{
// Do single-click code
}
}
If neccessary, you could require mouse click and wait until mouse up to perform the action.

Resources