How to launch the user's default browser with search criteria? - c#

I found this link:
C# Launch default browser with a default search query
But with FireFox as my default browser, it tries to find a file named as whatever is in the quotes in the selected Answer there.
Code;
//ToolStripMenu Click event to launch default browser and search internet for the value in a particular cell
private void tsmSearch_Click(object sender, EventArgs e)
{
int key = mp.GetRowAt(gdcErrorLogDefaultView, rowX, rowY);
if (key < 0)
return;
string ex = gdcErrorLogDefaultView.GetRowCellValue(key, "Exception").ToString();
string name = GetDefaultBrowser();
Process.Start(name, "\"?" + ex + "\"");
}
//Gets default browser from registry
private string GetDefaultBrowser()
{
string name;
RegistryKey regKey = null;
try
{
//set the registry key we want to open
regKey = Registry.ClassesRoot.OpenSubKey("HTTP\\shell\\open\\command", false);
//get rid of the enclosing quotes
name = regKey.GetValue(null).ToString().ToLower().Replace("" + (char)34, "");
//check to see if the value ends with .exe (this way we can remove any command line arguments)
if (!name.EndsWith("exe"))
//get rid of all command line arguments (anything after the .exe must go)
name = name.Substring(0, name.LastIndexOf(".exe") + 4);
}
catch (Exception ex)
{
name = string.Format("ERROR: An exception of type: {0} occurred in method: {1} in the following module: {2}", ex.GetType(), ex.TargetSite, this.GetType());
}
finally
{
//check and see if the key is still open, if so
//then close it
if (regKey != null)
regKey.Close();
}
return name;
}
I found the GetDefaultBrowser() code somewhere on StackOverflow yesterday but I can't find the link now. The weird thing is though, I have Chrome set as my default browser but that registry key still says FireFox.
Is there a more simple way to launch the default browser and use their default search provider to look up a term?

Try this:
string searchQuery = "this is a search";
Process.Start("https://www.google.com/search?q=" + Uri.EscapeDataString(searchQuery));
Edit: Now using correct Google link

Related

Programmatically open a page in IIS/IIS Express in the default browser on click of a button

I want to open a html page (in AppData/Roaming folder and not in the project/solution) with IIS/IIS Express in the default browser on click of a button. I have been able to find the default browser using the following:-
//This method is used to get the default browser
private static string GetDefaultBrowserPath()
{
string urlAssociation = #"Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http";
string browserPathKey = #"$BROWSER$\shell\open\command";
RegistryKey userChoiceKey = null;
string absBrowserPath = "";
const string exeSuffix = ".exe";
FileInfo browserPath;
try
{
//reading default browser path from userChoiceLKey
userChoiceKey = Registry.CurrentUser.OpenSubKey(urlAssociation + #"\UserChoice", false);
//If user choice was not found, try machine default
if (userChoiceKey == null)
{
//reading default browser path from Win XP registry key
var browserKey = Registry.ClassesRoot.OpenSubKey(#"HTTP\shell\open\command", false);
//if browser path not found, try Win Vista (and newer) registry key
if (browserKey == null)
{
browserKey =
Registry.CurrentUser.OpenSubKey(
urlAssociation, false);
}
var path = browserKey.GetValue(null);
browserKey.Close();
return path.ToString();
}
else
{
//if user defined browser choice was found
string progId = (userChoiceKey.GetValue("ProgId").ToString());
userChoiceKey.Close();
//looking up the path of the executable
string concreteBrowserKey = browserPathKey.Replace("$BROWSER$", progId);
var kp = Registry.ClassesRoot.OpenSubKey(concreteBrowserKey, false);
try
{
absBrowserPath = kp.GetValue(null).ToString().ToLower().Replace("\"", "");
if (!absBrowserPath.EndsWith(exeSuffix))
{
absBrowserPath = absBrowserPath.Substring(0, absBrowserPath.LastIndexOf(exeSuffix, StringComparison.Ordinal) + exeSuffix.Length);
browserPath = new FileInfo(absBrowserPath);
}
}
catch (Exception)
{
throw;
}
kp.Close();
return absBrowserPath;
}
}
catch(Exception ex)
{
return "";
}
}
After locating the default browser, I want to open a html page located in AppData/Roaming folder with IIS. How can this be achieved?
Edit: I am thinking of first publishing the pages with the IIS using ServerManager class of Microsoft.Web.Administration and then trying to open it.
is this a right approach? Once published, how would it be possible to open that page(a locally published site now) on click of some button?

File.ReadAllText prevents Form from closing on x button click

I have a weird problem. I want to write the visible textBox.Text to an "ini" file on FormClosing (right before the form shuts down), so I double clicked that event under the main form's Properties panel and filled the associated function as follows:
private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
// store the whole content in a string
string settingsContent = File.ReadAllText(settingsPath + "CBSettings");
// replace a name with another name, which truly exists in the ini file
settingsContent.Replace(userName, userNameBox.Text);
// write and save the altered content back to the ini file
// settingsPath looks like this #"C:\pathToSettings\settingsFolder\"
File.WriteAllText(settingsPath + "CBSettings", settingsContent);
}
The form starts up without a problem, but it won't quit by clicking the x button. It only closes correctly when I comment the File.WriteAllText line out. If I just stop debugging, the files content doesn't change either.
EDIT :
The actual problem was the function which I used to find and return the userName from the ini file:
public static string GetTextAfterTextFromTextfile(string path, string file, string fileExtension, string textToLookFor)
{
string stringHolder;
StreamReader sr = File.OpenText(path + file + fileExtension);
while((stringHolder = sr.ReadLine()) != null)
{
if(stringHolder.Contains(textToLookFor))
{
return stringHolder.Replace(textToLookFor, "");
}
}
sr.Close();
return "Nothing found";
}
The content of the ini file:
User Name = SomeName
Bot Name = SomeName
I copied the above function from stackoverflow. I was sure that it worked because it captured 'SomeName' just as I wanted. Now I use another function (also from stackoverflow), that searches the ini file for 'User Name = ' and returns the text that comes right after it.
public static string GetTextAfterTextFromTextfile(string path, string textToSkip)
{
string str = File.ReadAllText(path);
string result = str.Substring(str.IndexOf(textToSkip) + textToSkip.Length);
return result;
}
The problem is, that it returns
SomeNameBot Name = SomeName
Any hint on how to limit string result to only one line? Many thanks in advance!
This is a normal mishap on the 64-bit version of Windows 7, caused by a nasty flaw in that operating system's Wow64 emulator. Not limited to Winforms apps, C++ and WPF apps are affected as well. For .NET apps, this only misbehaves if a debugger is attached. Repro code:
private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
throw new Exception("You will not see this");
}
The debugger won't stop when the exception is thrown and you can't close the window anymore. I wrote a more extensive answer about this problem, including recommended workarounds, in this post.
Quick fix in your case: use Debug + Exceptions, tick the Thrown checkbox. The debugger now stops when the exception is thrown, allowing you to diagnose and fix your bug.

C# code to change browser download options

I am trying to do following with c#.
1) Open Firefox Browser-->Tools-->Options-->General Tab--->Downloads--->Always ask me where to save file.
I want to do this whole process in my application with c#. I want that when download window opens, the radio button in "Always ask me where to save file" option gets checked automatically.
I have tried from various links, but all is in vain.
Here is the full code, console application.
Summary: preferences file is located in application roaming folder, something like this on windows 7:
C:\Users\MYNAME\AppData\Roaming\Mozilla\Firefox\Profiles\d9i9jniz.default\prefs.js
We alter this file so that it includes "user_pref("browser.download.useDownloadDir", false);"
Restart firefox, and done. Only run this application when firefox is not running.
static void Main(string[] args)
{
if (isFireFoxOpen())
{
Console.WriteLine("Firefox is open, close it");
}
else
{
string pathOfPrefsFile = GetPathOfPrefsFile();
updateSettingsFile(pathOfPrefsFile);
Console.WriteLine("Done");
}
Console.ReadLine();
}
private static void updateSettingsFile(string pathOfPrefsFile)
{
string[] contentsOfFile = File.ReadAllLines(pathOfPrefsFile);
// We are looking for "user_pref("browser.download.useDownloadDir", true);"
// This needs to be set to:
// "user_pref("browser.download.useDownloadDir", false);"
List<String> outputLines = new List<string>();
foreach (string line in contentsOfFile)
{
if (line.StartsWith("user_pref(\"browser.download.useDownloadDir\""))
{
Console.WriteLine("Found it already in file, replacing");
}
else
{
outputLines.Add(line);
}
}
// Finally add the value we want to the end
outputLines.Add("user_pref(\"browser.download.useDownloadDir\", false);");
// Rename the old file preferences for safety...
File.Move(pathOfPrefsFile, Path.GetDirectoryName(pathOfPrefsFile) + #"\" + Path.GetFileName(pathOfPrefsFile) + ".OLD." + Guid.NewGuid().ToString());
// Write the new file.
File.WriteAllLines(pathOfPrefsFile, outputLines.ToArray());
}
private static string GetPathOfPrefsFile()
{
// Get roaming folder, and get the profiles.ini
string iniFilePath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + #"\Mozilla\Firefox\profiles.ini";
// Profiles.ini tells us what folder the preferences file is in.
string contentsOfIni = File.ReadAllText(iniFilePath);
int locOfPath = contentsOfIni.IndexOf("Path=Profiles");
int endOfPath = contentsOfIni.IndexOf(".default", locOfPath);
int startOfPath = locOfPath + "Path=Profiles".Length + 1;
int countofCopy = ((endOfPath + ".default".Length) - startOfPath);
string path = contentsOfIni.Substring(startOfPath, countofCopy);
string toReturn = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + #"\Mozilla\Firefox\Profiles\" + path + #"\prefs.js";
return toReturn;
}
public static bool isFireFoxOpen()
{
foreach (Process proc in Process.GetProcesses())
{
if (proc.ProcessName == "firefox")
{
return true;
}
}
return false;
}
What have you tried?
Firefox settings are stored in your profile, so I'd guess you can change the contents of the given file. Type about:config to find the setting you're looking for, I guess it's in the browser.download tree, alter it (after you made sure the browser isn't running) and you should be good to go.

How to use registry to refill a text box

How can i refill a textbox with it's previous text after the program was stopped using registry.
I read multiple articles like:
Stack OverFlow1
Stack OverFlow2
Code Project1
Code Project2
So far i have nothing because nothing is working out, all i get are errors D:
public string Read(string KeyName)
{
RegistryKey rk = baseRegistryKey ;
RegistryKey sk1 = rk.OpenSubKey(subKey);
if ( sk1 == null )
return null;
else
{
try
{
return (string)sk1.GetValue(KeyName.ToUpper());
}
catch (Exception ex)
{
}
}
}
says that baseRegistryKey and subKey don't exist. And it says that RegistryKey doesn't exist. How do i fix?
I've had the same problem a couple of days ago, don't use those sights, they are all bad.
there are several things wrong with your code:
baseRegistryKey and subKey need to be set to some sort of a parameter.
if RegisterKey isn't working than you probably didn't do using Microsoft.Win32
The code i used to solve this was:
public WindowsConsoleForm1();
try
{
InitializeComponent();
textBox1.Text = Application.UserAppDataRegistry.GetValue("example").ToString();
}
catch { }
and then where ever you have ex: textbox1.text = Path.GetDirectoryName(saveFileDialoge1.FileName);, under it you post Application.UserAppDataRegistry.SetValue("example", textbox1.text);

How can I launch a URL in the users default browser from my application?

How can I have a button in my desktop application that causes the user's default browser to launch and display a URL supplied by the application's logic.
Process.Start("http://www.google.com");
Process.Start([your url]) is indeed the answer, in all but extremely niche cases. For completeness, however, I will mention that we ran into such a niche case a while back: if you're trying to open a "file:\" url (in our case, to show the local installed copy of our webhelp), in launching from the shell, the parameters to the url were thrown out.
Our rather hackish solution, which I don't recommend unless you encounter a problem with the "correct" solution, looked something like this:
In the click handler for the button:
string browserPath = GetBrowserPath();
if (browserPath == string.Empty)
browserPath = "iexplore";
Process process = new Process();
process.StartInfo = new ProcessStartInfo(browserPath);
process.StartInfo.Arguments = "\"" + [whatever url you're trying to open] + "\"";
process.Start();
The ugly function that you shouldn't use unless Process.Start([your url]) doesn't do what you expect it's going to:
private static string GetBrowserPath()
{
string browser = string.Empty;
RegistryKey key = null;
try
{
// try location of default browser path in XP
key = Registry.ClassesRoot.OpenSubKey(#"HTTP\shell\open\command", false);
// try location of default browser path in Vista
if (key == null)
{
key = Registry.CurrentUser.OpenSubKey(#"Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http", false); ;
}
if (key != null)
{
//trim off quotes
browser = key.GetValue(null).ToString().ToLower().Replace("\"", "");
if (!browser.EndsWith("exe"))
{
//get rid of everything after the ".exe"
browser = browser.Substring(0, browser.LastIndexOf(".exe") + 4);
}
key.Close();
}
}
catch
{
return string.Empty;
}
return browser;
}

Categories

Resources