I'm trying to create an app to open a local PDF file using web browser in WPF. However the file doesn't open properly, instead displays a grey blank screen. The code works perfectly fine when used to open a HTML file. Please help!
Code: webBrowser1.Navigate(#"file:///C:/Working/sample.pdf");
Note: I have adobe reader installed in my PC, if that is necessary. Is it?
WPF by default uses IE-based WebBrowser. In order to be able to view PDF-files, you must have a plugin installed into IE which can display PDF-files.
In addition to grey background, this is what can happen with a PC where IE doesn't have a PDF-plugin (Acrobat Reader etc) installed:
If you don't want to install plugins, one option to get around this issue is to use Windows 10 APIs to draw the PDF.
Other option is a 3rd party library, like CefSharp. Here's steps for using CefSharp:
First install Nuget CefSharp.WPF
Second, change XAML from the default WebBrowser to:
<wpf:ChromiumWebBrowser Loaded="ChromiumWebBrowser_Loaded" x:Name="Browser"></wpf:ChromiumWebBrowser>
Then create custom resolvers for CefSharp:
public class CustomProtocolSchemeHandler : ResourceHandler
{
public CustomProtocolSchemeHandler()
{
}
public override bool ProcessRequestAsync(IRequest request, ICallback callback)
{
return true;
}
}
public class CustomProtocolSchemeHandlerFactory : ISchemeHandlerFactory
{
public const string SchemeName = "customFileProtocol";
public IResourceHandler Create(IBrowser browser, IFrame frame, string schemeName, IRequest request)
{
return new CustomProtocolSchemeHandler();
}
}
Almost lastly, register the resolvers in App.xaml.cs:
public partial class App : Application
{
protected override void OnLoadCompleted(NavigationEventArgs e)
{
var settings = new CefSettings();
settings.RegisterScheme(new CefCustomScheme
{
SchemeName = CustomProtocolSchemeHandlerFactory.SchemeName,
SchemeHandlerFactory = new CustomProtocolSchemeHandlerFactory(),
IsCSPBypassing = true
});
settings.LogSeverity = LogSeverity.Error;
Cef.Initialize(settings);
}
}
Now everything should work:
More information about using CefSharp: https://www.codeproject.com/Articles/881315/Display-HTML-in-WPF-and-CefSharp-Tutorial-Part
I'll probably add a few changes to #Mikael's code (In case something didn't work out for you)
public class CustomProtocolSchemeHandler : ResourceHandler
{
public CustomProtocolSchemeHandler()
{
}
public override CefSharp.CefReturnValue ProcessRequestAsync(IRequest request, ICallback callback)
{
return CefSharp.CefReturnValue.Continue;
}
}
public class CustomProtocolSchemeHandlerFactory : ISchemeHandlerFactory
{
public const string SchemeName = "customFileProtocol";
public IResourceHandler Create(IBrowser browser, IFrame frame, string schemeName, IRequest request)
{
return new CustomProtocolSchemeHandler();
}
}
Related
I am using a WPF Desktop app with BlazorWebView. I would like to open up file explorer and have the user select a folder to get the path selected. I can use the browser input to select files but as I understand it is a limitation of the browser to allow me to select a folder path. Is there a Folder Picker for native access?
The Process.Start only seem to open the file explorer and won't let me choose the folder.
<blazor:BlazorWebView HostPage="wwwroot\index.html" Services="{DynamicResource services}">
<blazor:BlazorWebView.RootComponents>
<blazor:RootComponent Selector="#app" ComponentType="{x:Type shared:App}" />
</blazor:BlazorWebView.RootComponents>
</blazor:BlazorWebView>
#using System.Diagnostics
<button #onclick="OnClickOpenNativeFileExplorer">Open</button>
#code {
private void OnClickOpenNativeFileExplorer(MouseEventArgs e)
{
Process.Start("explorer.exe");
}
}
For anyone wondering, I was able to solve it by doing the following.
I added the IFolderPicker interface to my razor class library. Then implement the FolderPicker in the WPF project using a NuGet package.
Install-Package WindowsAPICodePack-Shell -Version 1.1.1
public interface IFolderPicker
{
public string DisplayFolderPicker();
}
public class FolderPicker : IFolderPicker
{
public string DisplayFolderPicker()
{
var dialog = new CommonOpenFileDialog();
dialog.IsFolderPicker = true;
CommonFileDialogResult result = dialog.ShowDialog();
if (result == CommonFileDialogResult.Ok)
return dialog.FileName;
return "";
}
}
I then register the dependency using the DI container within the MainWindow.xaml.cs file.
public MainWindow()
{
InitializeComponent();
Application.Current.MainWindow.WindowState = WindowState.Maximized;
var serviceCollection = new ServiceCollection();
serviceCollection.AddWpfBlazorWebView();
serviceCollection.AddTransient<IFolderPicker, FolderPicker>();
Resources.Add("services", serviceCollection.BuildServiceProvider());
}
Then within the razor component, I have a button that calls the DisplayFolderPicker method.
#inject IFolderPicker _folderPicker
<button #onclick="OnClickOpenNativeFileExplorer">Open</button>
<p>#path</p>
#code {
private string path = "";
private void OnClickOpenNativeFileExplorer(MouseEventArgs e)
{
path = _folderPicker.DisplayFolderPicker();
}
}
Take-away: I suppose not only will this work for FolderPicker but for calling any native component.
I am trying to implement a simple web browser control in one of my apps. This is to help integrate a web app into a toolset i am creating.
The problem is, this web app absolutly loves popup windows....
When a popup is opened, it opens in an IE window which is not a child of the MDI Container form that my main window is part of.
How can i get any and all popups created by clicking links in my WebBrowser to be a child of my MDI container (similar to setting the MDIParent property of a form)?
Thanks in advance.
The web browser control supports the NewWindow event to get notified about a popup window. The Winforms wrapper however does not let you do much with it, you can only cancel the popup. The native COM wrapper permits passing back a new instance of the web browser, that instance will then be used to display the popup.
Taking advantage of this requires some work. For starters, use Project + Add Reference, Browse tab and select c:\windows\system32\shdocvw.dll. That adds a reference to the native COM interface.
Create a form that acts as the popup form. Drop a WebBrowser on it and make its code look similar to this:
public partial class Form2 : Form {
public Form2() {
InitializeComponent();
}
public WebBrowser Browser {
get { return webBrowser1; }
}
}
The Browser property gives access to the browser that will be used to display the web page in the popup window.
Now back to the main form. Drop a WebBrowser on it and make its code look like this:
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
webBrowser1.Url = new Uri("http://google.com");
}
SHDocVw.WebBrowser nativeBrowser;
protected override void OnLoad(EventArgs e) {
base.OnLoad(e);
nativeBrowser = (SHDocVw.WebBrowser)webBrowser1.ActiveXInstance;
nativeBrowser.NewWindow2 += nativeBrowser_NewWindow2;
}
protected override void OnFormClosing(FormClosingEventArgs e) {
nativeBrowser.NewWindow2 -= nativeBrowser_NewWindow2;
base.OnFormClosing(e);
}
void nativeBrowser_NewWindow2(ref object ppDisp, ref bool Cancel) {
var popup = new Form2();
popup.Show(this);
ppDisp = popup.Browser.ActiveXInstance;
}
}
The OnLoad method obtains a reference to the native COM interface, then subscribes an event handler to the NewWindow2 event. I made sure to unsubscribe that event in the FormClosing event handler, not 100% sure if that's necessary. Better safe then sorry.
The NewWindow2 event handler is the crux, note that the first argument allows passing back an untyped reference. That should be the native browser in the popup window. So I create an instance of Form2 and Show() it. Note the argument to Show(), that ensures that the popup is an owned window. Substitute this as necessary for your app, I assume you'd want to create an MDI child window in your case.
Do beware that this event doesn't fire for the window displayed when Javascript uses alert(). The browser doesn't treat that window as an HTML popup and doesn't use a browser window to display it so you cannot intercept or replace it.
I found that the best way to do this was to implement/sink the NewWindow3 event
Add the reference to c:\windows\system32\shdocvw.dll as mentioned in the other answers here.
Add event handler
SHDocVw.WebBrowser wbCOMmain = (SHDocVw.WebBrowser)webbrowser.ActiveXInstance;
wbCOMmain.NewWindow3 += wbCOMmain_NewWindow3;
Event method
void wbCOMmain_NewWindow3(ref object ppDisp,
ref bool Cancel,
uint dwFlags,
string bstrUrlContext,
string bstrUrl)
{
// bstrUrl is the url being navigated to
Cancel = true; // stop the navigation
// Do whatever else you want to do with that URL
// open in the same browser or new browser, etc.
}
Set "Embed Interop Types" for the "Interop.SHDocVw" assembly to false
Set the "local copy" to true.
Source for that help MSDN Post
Refining Hans answer, you can derive the WebBrowser for accessing the COM without adding the reference. It is by using the unpublished Winforms WebBrowser.AttachInterface and DetachInterface methods.
More elaborated here.
Here is the code:
Usage (change your WebBrowser instance to WebBrowserNewWindow2)
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.webBrowser1.NewWindow2 += webBrowser_NewWindow2;
}
protected override void OnFormClosing(FormClosingEventArgs e)
{
webBrowser1.NewWindow2 -= webBrowser_NewWindow2;
base.OnFormClosing(e);
}
void webBrowser_NewWindow2(object sender, WebBrowserNewWindow2EventArgs e)
{
var popup = new Form1();
popup.Show(this);
e.PpDisp = popup.Browser.ActiveXInstance;
}
public WebBrowserNewWindow2 Browser
{
get { return webBrowser1; }
}
}
Code:
using System;
using System.Security.Permissions;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace SHDocVw
{
public delegate void WebBrowserNewWindow2EventHandler(object sender, WebBrowserNewWindow2EventArgs e);
public class WebBrowserNewWindow2EventArgs : EventArgs
{
public WebBrowserNewWindow2EventArgs(object ppDisp, bool cancel)
{
PpDisp = ppDisp;
Cancel = cancel;
}
public object PpDisp { get; set; }
public bool Cancel { get; set; }
}
public class WebBrowserNewWindow2 : WebBrowser
{
private AxHost.ConnectionPointCookie _cookie;
private WebBrowser2EventHelper _helper;
[PermissionSet(SecurityAction.LinkDemand, Name = "FullTrust")]
protected override void CreateSink()
{
base.CreateSink();
_helper = new WebBrowser2EventHelper(this);
_cookie = new AxHost.ConnectionPointCookie(
this.ActiveXInstance, _helper, typeof(DWebBrowserEvents2));
}
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
protected override void DetachSink()
{
if (_cookie != null)
{
_cookie.Disconnect();
_cookie = null;
}
base.DetachSink();
}
public event WebBrowserNewWindow2EventHandler NewWindow2;
private class WebBrowser2EventHelper : StandardOleMarshalObject, DWebBrowserEvents2
{
private readonly WebBrowserNewWindow2 _parent;
public WebBrowser2EventHelper(WebBrowserNewWindow2 parent)
{
_parent = parent;
}
public void NewWindow2(ref object pDisp, ref bool cancel)
{
WebBrowserNewWindow2EventArgs arg = new WebBrowserNewWindow2EventArgs(pDisp, cancel);
_parent.NewWindow2(this, arg);
if (pDisp != arg.PpDisp)
pDisp = arg.PpDisp;
if (cancel != arg.Cancel)
cancel = arg.Cancel;
}
}
[ComImport, Guid("34A715A0-6587-11D0-924A-0020AFC7AC4D"),
InterfaceType(ComInterfaceType.InterfaceIsIDispatch),
TypeLibType(TypeLibTypeFlags.FHidden)]
public interface DWebBrowserEvents2
{
[DispId(0xfb)]
void NewWindow2(
[In, Out, MarshalAs(UnmanagedType.IDispatch)] ref object ppDisp,
[In, Out] ref bool cancel);
}
}
}
I know the question is very old but I solved it this way: add new reference, in COM choose Microsoft Internet Controls and in the code, before the click that opens a new window add the following:
SHDocVw.WebBrowser_V1 axBrowser = (SHDocVw.WebBrowser_V1)webBrowser1.ActiveXInstance;
axBrowser.NewWindow += axBrowser_NewWindow;
and then add the following method:
void axBrowser_NewWindow(string URL, int Flags, string TargetFrameName, ref object PostData, string Headers, ref bool Processed)
{
Processed = true;
webBrowser1.Navigate(URL);
}
I have IDS4 and a Xamarin.Forms app all working fine except one little issue. Every single time the iOS app accesses the IDP server it first gives me this prompt:
"AppName" Wants to Use "" to Sign In
This allows the app and website to share information about you
What is causing this?
I have this error using IdentityModel.OidcClient2. Please see this link for the cause. This is the gist of it:
Cause
This is a system dialog that was added in iOS 11 to SFAuthenticationSession. It is triggered by this code in AppAuth:
SFAuthenticationSession* authenticationVC =
[[SFAuthenticationSession alloc] initWithURL:requestURL
callbackURLScheme:redirectScheme
completionHandler:^(NSURL * _Nullable callbackURL,
NSError * _Nullable error) {
There isn't a way to get rid of the dialog, except to not use SFAuthenticationSession which means you lose Single SignOn, which is worse.
I ended up using SFSafariViewController instead of SFAuthenticationSession by using the method mentioned by MLeech HERE
Solution
Which basically meant add these lines to your AppDelegate.cs
public override UIWindow Window
{
get;
set;
}
public static Action<string> CallbackHandler { get; set; }
public override bool OpenUrl(UIApplication application, NSUrl url, string sourceApplication, NSObject annotation)
{
CallbackHandler(url.AbsoluteString);
CallbackHandler = null;
return true;
}
Then use this code for your SFAuthenticationSessionBrowser.cs
public class SFAuthenticationSessionBrowser : IBrowser
{
public Task<BrowserResult> InvokeAsync(BrowserOptions options)
{
var task = new TaskCompletionSource<BrowserResult>();
var safari = new SFSafariViewController(new NSUrl(options.StartUrl));
AppDelegate.CallbackHandler = async url =>
{
await safari.DismissViewControllerAsync(true);
task.SetResult(new BrowserResult()
{
Response = url
});
};
// https://forums.xamarin.com/discussion/24689/how-to-acces-the-current-view-uiviewcontroller-from-an-external-service
var window = UIApplication.SharedApplication.KeyWindow;
var vc = window.RootViewController;
while (vc.PresentedViewController != null)
{
vc = vc.PresentedViewController;
}
vc.PresentViewController(safari, true, null);
return task.Task;
}
}
I'm trying to load a WebView using Codename One but it does not work on a real Android device (though it worked in the Codename One simulator - the page was loaded).
I've tried both BrowserComponent and WebBrowser and both didn't work. The code are:
public class WebViewScreenOpR implements Runnable {
private String urlString;
public WebViewScreenOpR(String urlString) {
super();
this.urlString = urlString;
}
private Form webViewForm;
private void prepareAsWebBrowser() {
WebBrowser webBrowser = new WebBrowser(urlString);
webViewForm = new Form("Starlent", new BoxLayout(BoxLayout.Y_AXIS));
webViewForm.add(webBrowser);
}
private void prepareAsBrowserComponent() {
webViewForm = new Form("Starlent", new BoxLayout(BoxLayout.Y_AXIS));
BrowserComponent browserComponent = new BrowserComponent();
browserComponent.setURL(urlString);
webViewForm.add(browserComponent);
}
#Override
public void run() {
prepareAsBrowserComponent();
show();
}
private void show() {
webViewForm.show();
}
and to display it:
private class GoLiveButtonActionListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent evt) {
WebViewScreenOpR webViewScreenOpR = new WebViewScreenOpR("http://www.apple.com");
Display.getInstance().callSerially(webViewScreenOpR);
}
}
I've also tried the "reload()" and "setEnabled(true/false)" methods but to no avail.
On testing using a real Android device, it briefly showed a progress dialog box with the text "loading...". The dialog box then disappeared and nothing appears. What's wrong with my code? How can I get it work in a real Android?
Try a BorderLayout center instead your boxlayout the initial size of the browser might just be 0 height
In each view
public partial class View2 : UserControl, IRegionMemberLifetime, INavigationAware
{
public bool KeepAlive
{
get { return false; }
}
bool INavigationAware.IsNavigationTarget(NavigationContext navigationContext)
{
return true;
}
void INavigationAware.OnNavigatedFrom(NavigationContext navigationContext)
{
// Intentionally not implemented.
}
void INavigationAware.OnNavigatedTo(NavigationContext navigationContext)
{
this.navigationJournal = navigationContext.NavigationService.Journal;
}
}
Initialize:
container.RegisterType<object, View1>("View1");
container.RegisterType<object, View2>("View2");
regionManager.RequestNavigate("Window1", new Uri("View1", UriKind.Relative));
regionManager.RequestNavigate("Window2", new Uri("View2", UriKind.Relative));
I am following the developer guide, it does not change the view if view exists.
Are you sure the view gets populated by the container?
I would suggest you to provide a callback for the RequestNavigate method, so you'll be able to track what happens with your view thru the NavigationResult:
regionManager.RequestNavigate
(
"Window1",
new Uri("View2", UriKind.Relative),
(NavigationResult nr) =>
{
var error = nr.Error;
var result = nr.Result;
// put a breakpoint here and checkout what NavigationResult contains
}
);
I have seen that if I implement IConfirmNavigateRequest and do not call continutationCallback(true), the navigation fails quietly.
public void ConfirmNavigationRequest(NavigationContext navigationContext, Action<bool> continuationCallback)
{
//***Should have actual logic here
continuationCallback(true);
}
While this may not be your case, I figured this out by debugging through the Prism code. I would suggest you do this to figure out your issue. Delete the references to the following in each relevant project.
Microsoft.Practices.Prism
Microsoft.Practices.Prism.Interactivity
Microsoft.Practices.Prism.MefExtensions
Microsoft.Practices.Prism.UnityExtensions
Then add the projects from the PrismLibrary DeskTop, Silverlight or Phone directory (where you installed PRISM). Then reference these projects.
This is your problem:
bool INavigationAware.IsNavigationTarget(NavigationContext navigationContext) => true;
If you want a new view to be created and added to your region each time you call RequestNavigate(), IsNavigationTarget() must return false instead of true.