I have an wpf app that I want to use to open another wpf app.
Call them image viewer (Gallery) and image storage (AppToAppCommunication).
Image storage app shows a list of available images.
Then, on ListBox selection changed I have this code:
private async void lbImages_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var options = new LauncherOptions();
options.ContentType = "image/jpg";
var filePath = Environment.CurrentDirectory + "\\Images\\" +
((ListBoxItem)((ListBox)sender).SelectedItem).Content;
var file = await StorageFile.GetFileFromPathAsync(filePath);
var token = SharedStorageAccessManager.AddFile(file);
ValueSet inputData = new ValueSet();
inputData.Add("Token", token);
Uri uri = new Uri("myprotocol:");
//await Launcher.LaunchUriAsync(uri); // #works
//await Launcher.LaunchUriAsync(uri, options, inputData); // #doesn't
}
Now, when I use the line at #works, it works, with no image shown, as expected.
But, when instead I use line at #desn't, it gives me this error:
Now I tried clicking OK on the popup and running a new VS instance an waiting for it to load, but it never does.
I've tried running both applications from the same solution and I can get to a breakpoint in override void OnActivated in image viewer app (Gallery) when using the #works line in image storage app (AppToAppCommunication), but I can't get to that same breakpoint when using the #doesn't line.
I don't know what the problem is and I am not able to debug it.
How could I go about finding a way to debug this properly?
There is a link behind button with PDF file on web page that I would like to access. PDF link has API key and can't be accessed directly. Button has ID company_report_link.
If I do reportDownloadButton.Click(); PDF gets opened in separate tab of browser but I can't figure out how to download it.
I have tried right click the button and select Save As? I am able to open Chrome Context menu with this one, but can't select Save link As..
// click the link to download
var reportDownloadButton = driver.FindElementById("company_report_link");
// reportDownloadButton.Click();
// if clicking does not work, get href attribute and call GoToUrl() -- this may trigger download
// var href = reportDownloadButton.GetAttribute("href");
// driver.Navigate().GoToUrl(href);
InputSimulator s = new InputSimulator();
Actions action1 = new Actions(driver);
action1.ContextClick(reportDownloadButton);
s.Keyboard.KeyPress(VirtualKeyCode.DOWN);
Thread.Sleep(2000);
s.Keyboard.KeyPress(VirtualKeyCode.DOWN);
Thread.Sleep(2000);
s.Keyboard.KeyPress(VirtualKeyCode.DOWN);
Thread.Sleep(2000);
s.Keyboard.KeyPress(VirtualKeyCode.DOWN);
Thread.Sleep(2000);
s.Keyboard.KeyPress(VirtualKeyCode.RETURN);
I have tried to do the trick with WebClient
var reportDownloadButton = driver.FindElementById("company_report_link");
var text = reportDownloadButton.GetAttribute("href");
// driver.Manage().Timeouts().ImplicitWait = System.TimeSpan.FromSeconds(15);
WebClient client = new WebClient();
// Save the file to desktop for debugging
var desktop = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Desktop);
string fileName = desktop + "\\myfile.pdf";
client.DownloadFile(text, fileName);
but it does not work because of API. Web site is giving:
System.Net.WebException: 'The remote server returned an error: (401)
Unauthorized.'
I want open a URL using Microsoft Edge in my UWP. Searching, I found this code:
using System.Diagnostics;
using System.ComponentModel;
private void button_Help_Click(object sender, RoutedEventArgs e)
{
Process.Start("microsoft-edge:http://www.bing.com");
}
But it shows the following error:
The name Process do not exist in the current context
If I press Ctrl+., it only shows generate class options.
Any help is appreciated.
Process.Start is a traditional method used in .NET Framework which can't be used in UWP apps directly. To open web URI with Microsoft Edge in UWP, we can use
Launcher.LaunchUriAsync method. For example:
// The URI to launch
string uriToLaunch = #"http://www.bing.com";
// Create a Uri object from a URI string
var uri = new Uri(uriToLaunch);
// Launch the URI
async void DefaultLaunch()
{
// Launch the URI
var success = await Windows.System.Launcher.LaunchUriAsync(uri);
if (success)
{
// URI launched
}
else
{
// URI launch failed
}
}
However this will open the URI with the default web browser. To always open it with Microsoft Edge, we can use Launcher.LaunchUriAsync(Uri, LauncherOptions) method with specified LauncherOptions.TargetApplicationPackageFamilyName property. TargetApplicationPackageFamilyName property can specify the target package that should be used to launch a file or URI. For Microsoft Edge, its Package Family Name is "Microsoft.MicrosoftEdge_8wekyb3d8bbwe". Following is an example shows how to use this.
// The URI to launch
string uriToLaunch = #"http://www.bing.com";
var uri = new Uri(uriToLaunch);
async void LaunchWithEdge()
{
// Set the option to specify the target package
var options = new Windows.System.LauncherOptions();
options.TargetApplicationPackageFamilyName = "Microsoft.MicrosoftEdge_8wekyb3d8bbwe";
// Launch the URI
var success = await Windows.System.Launcher.LaunchUriAsync(uri, options);
if (success)
{
// URI launched
}
else
{
// URI launch failed
}
}
You can do it, but Microsoft Edge must be your default browser. See the code bellow
private async void launchURI_Click(object sender, RoutedEventArgs e)
{
// The URI to launch
var uriBing = new Uri(#"http://www.bing.com");
// Launch the URI
var success = await Launcher.LaunchUriAsync(uriBing);
}
I have tried this and it works for me without setting Edge as default browser:
await Launcher.LaunchUriAsync(new Uri("microsoft-edge:https://www.bing.com"));
I am looking for a way to implement Internet explorer - a desktop version in my Winodws 8 app . This is caused by my c# application- i need to run javascript page but its impossible in metro version of IE. Is there any method to do this?
I `ll describe my problem: when i want to load html of DOM page(rendered by javascript) i cant because javascript can run (I use WebView). I tried to open this page using Desktop version and it worked perfectly. Unfortunately Metro IE10 cant show the content and my WebView too.
Thanks for help.
You can sure inject in the c# webview a javascript file:
This is the action for a button:
private async void Lamp_Click(object sender, RoutedEventArgs e)
{
Uri uri = new Uri("ms-appx:///js/injected.js");
StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(uri);
string text = await FileIO.ReadTextAsync(file); //reading content as string
var script = "(function(){" + text + "})()";
}
try
{
var result = wv.InvokeScript("eval", new string[] { script });
}
catch (Exception) { }
wv is you id name for the webview element in the xaml
I am designing a small C# application and there is a web browser in it. I currently have all of my defaults on my computer say google chrome is my default browser, yet when I click a link in my application to open in a new window, it opens internet explorer. Is there any way to make these links open in the default browser instead? Or is there something wrong on my computer?
My problem is that I have a webbrowser in the application, so say you go to google and type in "stack overflow" and right click the first link and click "Open in new window" it opens in IE instead of Chrome. Is this something I have coded improperly, or is there a setting not correct on my computer
===EDIT===
This is really annoying. I am already aware that the browser is IE, but I had it working fine before. When I clicked a link it opened in chrome. I was using sharp develop to make the application at that time because I could not get c# express to start up. I did a fresh windows install and since I wasn't too far along in my application, I decided to start over, and now I am having this problem. That is why I am not sure if it is my computer or not. Why would IE start up the whole browser when a link is clicked rather than simply opening the new link in the default browser?
You can just write
System.Diagnostics.Process.Start("http://google.com");
EDIT: The WebBrowser control is an embedded copy of IE.
Therefore, any links inside of it will open in IE.
To change this behavior, you can handle the Navigating event.
For those finding this question in dotnet core. I found a solution here
Code:
private void OpenUrl(string url)
{
try
{
Process.Start(url);
}
catch
{
// hack because of this: https://github.com/dotnet/corefx/issues/10361
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
url = url.Replace("&", "^&");
Process.Start(new ProcessStartInfo(url) { UseShellExecute = true });
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
Process.Start("xdg-open", url);
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
Process.Start("open", url);
}
else
{
throw;
}
}
}
After researching a lot I feel most of the given answer will not work with dotnet core.
1.System.Diagnostics.Process.Start("http://google.com"); -- Will not work with dotnet core
2.It will work but it will block the new window opening in case default browser is chrome
myProcess.StartInfo.UseShellExecute = true;
myProcess.StartInfo.FileName = "http://some.domain.tld/bla";
myProcess.Start();
Below is the simplest and will work in all the scenarios.
Process.Start("explorer", url);
public static void GoToSite(string url)
{
System.Diagnostics.Process.Start(url);
}
that should solve your problem
Did you try Processas mentioned here: http://msdn.microsoft.com/de-de/library/system.diagnostics.process.aspx?
You could use
Process myProcess = new Process();
try
{
// true is the default, but it is important not to set it to false
myProcess.StartInfo.UseShellExecute = true;
myProcess.StartInfo.FileName = "http://some.domain.tld/bla";
myProcess.Start();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
My default browser is Google Chrome and the accepted answer is giving the following error:
The system cannot find the file specified.
I solved the problem and managed to open an URL with the default browser by using this code:
System.Diagnostics.Process.Start("explorer.exe", "http://google.com");
I'm using this in .NET 5, on Windows, with Windows Forms. It works even with other default browsers (such as Firefox):
Process.Start(new ProcessStartInfo { FileName = url, UseShellExecute = true });
Based on this and this.
Try this , old school way ;)
public static void openit(string x)
{
System.Diagnostics.Process.Start("cmd", "/C start" + " " + x);
}
using : openit("www.google.com");
Am I the only one too scared to call System.Diagnostics.Process.Start() on a string I just read off the internet?
public bool OnBeforeBrowse(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IRequest request, bool userGesture, bool isRedirect)
{
Request = request;
string url = Request.Url;
if (Request.TransitionType != TransitionType.LinkClicked)
{ // We are only changing the behavoir when someone clicks on a link.
// Let the embedded browser handle this request itself.
return false;
}
else
{ // The user clicked on a link. Something like a filter icon, which links to the help for that filter.
// We open a new window for that request. This window cannot change. It is running a JavaScript
// application that is talking with the C# main program.
Uri uri = new Uri(url);
try
{
switch (uri.Scheme)
{
case "http":
case "https":
{ // Stack overflow says that this next line is *the* way to open a URL in the
// default browser. I don't trust it. Seems like a potential security
// flaw to read a string from the network then run it from the shell. This
// way I'm at least verifying that it is an http request and will start a
// browser. The Uri object will also verify and sanitize the URL.
System.Diagnostics.Process.Start(uri.ToString());
break;
}
case "showdevtools":
{
WebBrowser.ShowDevTools();
break;
}
}
}
catch { }
// Tell the browser to cancel the navigation.
return true;
}
}
This code was designed to work with CefSharp, but should be easy to adapt.
Take a look at the GeckoFX control.
GeckoFX is an open-source component
which makes it easy to embed Mozilla
Gecko (Firefox) into any .NET Windows
Forms application. Written in clean,
fully commented C#, GeckoFX is the
perfect replacement for the default
Internet Explorer-based WebBrowser
control.
dotnet core throws an error if we use Process.Start(URL). The following code will work in dotnet core. You can add any browser instead of Chrome.
var processes = Process.GetProcessesByName("Chrome");
var path = processes.FirstOrDefault()?.MainModule?.FileName;
Process.Start(path, url);
This opened the default for me:
System.Diagnostics.Process.Start(e.LinkText.ToString());
I tried
System.Diagnostics.Process.Start("https://google.com");
which works for most of the cases but I run into an issue having a url which points to a file:
The system cannot find the file specified.
So, I tried this solution, which is working with a little modification:
System.Diagnostics.Process.Start("explorer.exe", $"\"{uri}\"");
Without wrapping the url with "", the explorer opens your document folder.
In UWP:
await Launcher.LaunchUriAsync(new Uri("http://google.com"));
Open dynamically
string addres= "Print/" + Id + ".htm";
System.Diagnostics.Process.Start(Path.Combine(Environment.CurrentDirectory, addres));
update the registry with current version of explorer
#"Software\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION"
public enum BrowserEmulationVersion
{
Default = 0,
Version7 = 7000,
Version8 = 8000,
Version8Standards = 8888,
Version9 = 9000,
Version9Standards = 9999,
Version10 = 10000,
Version10Standards = 10001,
Version11 = 11000,
Version11Edge = 11001
}
key.SetValue(programName, (int)browserEmulationVersion, RegistryValueKind.DWord);
This works nicely for .NET 5 (Windows):
ProcessStartInfo psi = new ProcessStartInfo {
FileName = "cmd.exe",
Arguments = $ "/C start https://stackoverflow.com/",
WindowStyle = ProcessWindowStyle.Hidden,
CreateNoWindow = true
};
Process.Start(psi);
to fix problem with Net 6
i used this code from ChromeLauncher
,default browser will be like it
internal static class ChromeLauncher
{
private const string ChromeAppKey = #"\Software\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe";
private static string ChromeAppFileName
{
get
{
return (string) (Registry.GetValue("HKEY_LOCAL_MACHINE" + ChromeAppKey, "", null) ??
Registry.GetValue("HKEY_CURRENT_USER" + ChromeAppKey, "", null));
}
}
public static void OpenLink(string url)
{
string chromeAppFileName = ChromeAppFileName;
if (string.IsNullOrEmpty(chromeAppFileName))
{
throw new Exception("Could not find chrome.exe!");
}
Process.Start(chromeAppFileName, url);
}
}
I'd comment on one of the above answers, but I don't yet have the rep.
System.Diagnostics.Process.Start("explorer", "stackoverflow.com");
nearly works, unless the url has a query-string, in which case this code just opens a file explorer window. The key does seem to be the UseShellExecute flag, as given in Alex Vang's answer above (modulo other comments about launching random strings in web browsers).
You can open a link in default browser using cmd command start <link>, this method works for every language that has a function to execute a system command on cmd.exe.
This is the method I use for .NET 6 to execute a system command with redirecting the output & input, also pretty sure it will work on .NET 5 with some modifications.
using System.Diagnostics.Process cmd = new();
cmd.StartInfo.FileName = "cmd.exe";
cmd.StartInfo.RedirectStandardInput = true;
cmd.StartInfo.RedirectStandardOutput = true;
cmd.StartInfo.CreateNoWindow = true;
cmd.StartInfo.UseShellExecute = false;
cmd.Start();
cmd.StandardInput.WriteLine("start https://google.com");
cmd.StandardInput.Flush();
cmd.StandardInput.Close();
cmd.WaitForExit();