This question already has answers here:
Simulating Key Press C#
(8 answers)
Closed 5 years ago.
I want to open default browser in my computer and then simulate to click the button. I have created a new console application as below:
class Program
{
[STAThread]
static void Main(string[] args)
{
var url = "http://google.com";
Process.Start(url);
Console.ReadKey();
}
}
Now what can I do? I found WebBrowser class but I think it's for browser control in windows forms app..
Get default browser using the below function
private static string GetStandardBrowserPath()
{
string browserPath = string.Empty;
RegistryKey browserKey = null;
try
{
//Read default browser path from Win XP registry key
browserKey = Registry.ClassesRoot.OpenSubKey(#"HTTP\shell\open\command", false);
//If browser path wasn't found, try Win Vista (and newer) registry key
if (browserKey == null)
{
browserKey = Registry.CurrentUser.OpenSubKey(#"Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http", false); ;
}
//If browser path was found, clean it
if (browserKey != null)
{
//Remove quotation marks
browserPath = (browserKey.GetValue(null) as string).ToLower().Replace("\"", "");
//Cut off optional parameters
if (!browserPath.EndsWith("exe"))
{
browserPath = browserPath.Substring(0, browserPath.LastIndexOf(".exe") + 4);
}
//Close registry key
browserKey.Close();
}
}
catch
{
//Return empty string, if no path was found
return string.Empty;
}
//Return default browsers path
return browserPath;
}
Open url in default browser:
string url = "http://google.com";
string browserPath = GetStandardBrowserPath();
if (string.IsNullOrEmpty(browserPath))
{
MessageBox.Show("No default browser found!");
}
else
{
Process.Start(browserPath, url);
}
Related
I am writing an application that is supposed to open a certain process on the click of a button. However, the user has the ability to add new buttons. I'm using the following code for the action that occurs that starts the process on button click:
private void StartProcess(string path)
{
ProcessStartInfo StartInformation = new ProcessStartInfo();
StartInformation.FileName = path;
Process process = Process.Start(StartInformation);
process.EnableRaisingEvents = true;
}
private void ClickFunc(object sender, RoutedEventArgs e)
{
if (File.Exists(ProgramPath))
{
StartProcess(ProgramPath);
}
else
{
MessageBox.Show("Specified path does not exist, please try again.", "Bad File Path Error", MessageBoxButton.OK);
}
}
What I'm trying to accomplish is, when the user creates a button for a webpage, it opens the browser, then the webpage. Any ideas?
Thank you in advance!
To start a process to open the browser with a specific url you can try this:
string url = "http://www.stackoverflow.com";
var process = System.Diagnostics.Process.Start(url);
But sometimes if you have problems with the path of your browser, it cannot work properly. The function bellow gives you the path of the browser in the machine.
public static string GetDefaultBrowserPath()
{
string urlAssociation = #"Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http";
string browserPathKey = #"$BROWSER$\shell\open\command";
RegistryKey userChoiceKey = null;
string browserPath = “”;
try
{
//Read default browser path from userChoiceLKey
userChoiceKey = Registry.CurrentUser.OpenSubKey(urlAssociation + #"\UserChoice", false);
//If user choice was not found, try machine default
if (userChoiceKey == null)
{
//Read default browser path from Win XP registry key
var browserKey = Registry.ClassesRoot.OpenSubKey(#"HTTP\shell\open\command", false);
//If browser path wasn’t found, try Win Vista (and newer) registry key
if (browserKey == null)
{
browserKey =
Registry.CurrentUser.OpenSubKey(
urlAssociation, false);
}
var path = CleanifyBrowserPath(browserKey.GetValue(null) as string);
browserKey.Close();
return path;
}
else
{
// user defined browser choice was found
string progId = (userChoiceKey.GetValue("ProgId").ToString());
userChoiceKey.Close();
// now look up the path of the executable
string concreteBrowserKey = browserPathKey.Replace(“$BROWSER$”, progId);
var kp = Registry.ClassesRoot.OpenSubKey(concreteBrowserKey, false);
browserPath = CleanifyBrowserPath(kp.GetValue(null) as string);
kp.Close();
return browserPath;
}
}
catch(Exception ex)
{
return "";
}
}
And you can use the path of the browser and the url of website, for sample:
string url = "http://www.stackoverflow.com";
var process = System.Diagnostics.Process.Start(GetDefaultBrowserPath(), url);
In the url string you can pass the webpage link. It will open the browser with the url.
See more:
http://www.seirer.net/blog/2014/6/10/solved-how-to-open-a-url-in-the-default-browser-in-csharp
I'm trying to add a registry key through my code on the startup of the program. I'm completely new to this and I don't know how to (and couldn't search for) but I have tried with this code:
RegistryKey HTML5Key = Registry.LocalMachine.OpenSubKey("HKEY_LOCAL_MACHINE\\SOFTWARE\\Wow6432Node\\Microsoft\\Internet Explorer\\MAIN\\FeatureControl\\FEATURE_BROWSER_EMULATION", true);
if (HTML5Key != null)
{
HTML5Key.SetValue("mybrowser.exe", "270f", RegistryValueKind.DWord);
HTML5Key.Close();
}
But it simply does nothing. What am I doing wrong? I have admin rights. I have tried to debug it but I can't even get inside the if bracket.
You use OpenSubKey to open key in registry, so if specified key is not exist in registry it will return null. That is why your code is not working. Check whether sub key exist or not and then open it for writting.
One more mistake in your code you want to open HKEY_CURRENT_USER sub key so write code as follows
Registry.CurrentUser.OpenSubKey("SOFTWARE\\Wow6432Node\\Microsoft\\Internet Explorer\\MAIN\\FeatureControl\\FEATURE_BROWSER_EMULATION", true)
You can use below code for write the value in registry.
private string _subKey = "Microsoft\\Internet Explorer\\MAIN\\FeatureControl\\FEATURE_BROWSER_EMULATION";
private string SubKey
{
get { return _subKey; }
set { _subKey = value; }
}
private RegistryKey _baseRegistryKey = Registry.LocalMachine;
private RegistryKey BaseRegistryKey
{
get { return _baseRegistryKey; }
set { _baseRegistryKey = value; }
}
private bool WriteDbToRegistry(string keyName, object value)
{
try
{
var rk = BaseRegistryKey;
var sk1 = rk.CreateSubKey(SubKey);
if(sk1 != null) sk1.SetValue(keyName.ToUpper(), value);
return true;
}
catch(Exception e)
{
MessageBox.Show("Please run your App as Administrator.", "Administrator");
return false;
}
}
bool results = WriteDbToRegistry("Keyname", "2710");
and get value from registry..
public string GetRegistryValue()
{
var rk = BaseRegistryKey;
var sk1 = rk.OpenSubKey(SubKey);
try
{
return (string)sk1.GetValue("Keyname");
}
catch (Exception e)
{
MessageBox.Show(e.Message, "some message");
return null;
}
}
I put this together with minor changes to the code previously given by JasRaj to create the registry entry:
private string _subKey = "SOFTWARE\\Microsoft\\Internet Explorer\\MAIN\\FeatureControl\\FEATURE_BROWSER_EMULATION";
private string SubKey
{
get { return _subKey; }
set { _subKey = value; }
}
private RegistryKey _baseRegistryKey = Registry.LocalMachine;
private RegistryKey BaseRegistryKey
{
get { return _baseRegistryKey; }
set { _baseRegistryKey = value; }
}
private bool WriteDbToRegistry(string keyName, object value)
{
try
{
var rk = BaseRegistryKey;
var sk1 = rk.OpenSubKey(SubKey,true); //true is required for making it writable
if (sk1 != null)
{
sk1.SetValue(keyName, value,RegistryValueKind.DWord); //dword,qword
rk.Close();
sk1.Close();
return true;
}
else
{
rk.Close();
sk1.Close();
return false;
}
}
catch(Exception e)
{
MessageBox.Show(e.Message);
return false;
}
}
public string GetRegistryValue(string keyname)
{
var rk = BaseRegistryKey;
var sk1 = rk.OpenSubKey(SubKey);
try
{
return sk1.GetValue(keyname).ToString();
}
catch (Exception e)
{
MessageBox.Show(e.Message, "Error");
return null;
}
}
There are two problems with your code:
You likely don't have permissions to write to HKEY_LOCAL_MACHINE
You are not writing to the right location and an invalid value is used
Your problem is that you are writing to HKEY_LOCAL_MACHINE and you most likely don't have permissions to write there under a normal user account. Unless you are an Administrator and running under elevated rights you can't write there. However, for what you are trying to do luckily you don't need to write the HKLM, but you can write to the HKCU registry which is allowed.
Also the "270F" should be a number not a string so 0x270F without quotes should be used.
The following code is what I use in one of my applications to set browser emulation:
using (var rk = Registry.CurrentUser.OpenSubKey(#"SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION",true))
{
dynamic value = rk.GetValue("MarkdownMonster.exe");
if (value == null)
rk.SetValue(exename, (uint) 11001, RegistryValueKind.DWord);
}
I create the code for text to speech.
I want it to open web browser how to do this??
I am using windows 7 OS.
I also download xampp.
using System.Speech.Synthesis;
namespace ConsoleApplication5
{
class Program
{
static void Main(string[] args)
{
SpeechSynthesizer synthesizer = new SpeechSynthesizer();
synthesizer.Volume = 100; // 0...100
synthesizer.Rate = -2; // -10...10
// Synchronous
synthesizer.Speak("Hello World");
// Asynchronous
synthesizer.SpeakAsync("Hello World");
}
}
}
First, add this namespace
using Microsoft.Win32;
using System.Diagnostics;
Then, run this code which will find the default web browser and launch it.
Process p = new Process();
string browser = string.Empty;
RegistryKey key = null;
try
{
key = Registry.ClassesRoot.OpenSubKey(#"HTTP\shell\open\command", false);
//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);
}
}
finally
{
if (key != null) key.Close();
}
p.StartInfo.FileName = browser;
p.StartInfo.Arguments = "http://www.google.com";
p.Start();
I have condition when I display a message when there is upgrade available and as soon as the user clicks on "Upgrade" button the application is redirected to the given Upgrade URL and application is exited.So, when i press the back key, i will be taken to application list screen.
This works fine when I have no longer connected my device to the PC. But, When am testing the same by connecting the device to PC, the redirection happens well, but on back key press am taken to my application's blank screen.
Here is what happens when "Upgrade" is clicked.
case 6:
//APP_MINOR_UPGRADE_CONFIRM
switch (dialogResult)
{
case 1:
try
{
string url;
//url = CacheManager.getInstance().getApplicationSettings(CacheManager.APP_APK_UPGRADE_URI);
url = CacheManager.getInstance().getDataFromConfigFile(CacheManager.APP_APK_UPGRADE_URI);
if (Utils.isNullString(url))
{
url = CacheManager.getInstance().getUpgradeURL();
}
DataManager.getInstance().UpdateBadge(false);
WebBrowserTask browse = new WebBrowserTask();
browse.URL = url;
browse.Show();
game = new Game();
game.Exit();
break;
}
catch (Exception ex)
{
}
finally
{
// DataManager.getInstance().CheckCatalogUpgradeStatus();
}
break;
default:
//delete data from the DB
ProgressBarControl.displayProgressBar(0, 10, AppResources.DOWNLOADING);
try
{
//byte[] data = (byte[])CacheManager.getInstance().getPersistanceData(Utils.MINOR_UPGRADE_DATA);
byte[] data = (byte[])CacheManager.getInstance().getDataFromDataFile();
if (data != null && data.Length > 0)
{
DataManager.getInstance().processMyWidgetResponse(data);
DataManager.getInstance().refresUI();
}
DataManager.getInstance().UpdateBadge(false);
DataManager.getInstance().CheckCatalogUpgradeStatus();
}
catch (Exception ex)
{
}
finally
{
CacheManager.getInstance().deletaFromApplicationCache(Utils.MINOR_UPGRADE_DATA);
}
break;
}
break;
What could be the reason?
Comments and answers appreciated :)
I am trying to build a desktop app to use facebook api and get data from friends.
Anyways I am stuck in the log in stage.
I have used some advice and made the log in to facebook with WebBrowser. It works great.
I am stuck at trying to make it give me status = Failed or success
I tried doing it like this at the end of the button_1 method
if (!w.DocumentText.Contains(#"<div class=""linkWrap noCount"">Messages</div>"))
{
w.Navigate(#"http://www.facebook.com/login.php");
MessageBox.Show("Login error. Wrong username or password!");
}
else
{
MessageBox.Show("Logged in successfully");
}
the < div class=""linkWrap noCount"">Messages< /div> is only shown while logged in so thats why I use it to see if a user is logged in
but the problem is it always gives me an error (wrong user and pass) becasue it reads it before the browser finishes to navigate to the page. I tried threads and thread sleep and even timers but it doesnt seem to work
an ideas?
here is the code:
private void button1_Click(object sender, EventArgs e)
{
Thread thread = new Thread(new ThreadStart(WorkThreadFunction));
thread.Start();
string email = textBox1.Text;
string password = textBox2.Text;
// create a new browser
WebBrowser w = new WebBrowser();
w.Dock = DockStyle.Fill;
this.Controls.Add(w); // you may add the controll to your windows forms if you want to see what is going on
// latter you may not chose to add the browser or you can even set it to invisible...
// navigate to facebook
w.Navigate(#"http://www.facebook.com/login.php");
// wait a little
for (int i = 0; i < 100; i++)
{
System.Threading.Thread.Sleep(10);
System.Windows.Forms.Application.DoEvents();
}
HtmlElement temp=null;
// while we find an element by id named email
while (temp == null)
{
temp = w.Document.GetElementById("email");
System.Threading.Thread.Sleep(10);
System.Windows.Forms.Application.DoEvents();
}
// once we find it place the value
temp.SetAttribute("value", email);
temp = null;
// wiat till element with id pass exists
while (temp == null)
{
temp = w.Document.GetElementById("pass");
System.Threading.Thread.Sleep(10);
System.Windows.Forms.Application.DoEvents();
}
// once it exist set its value equal to passowrd
temp.SetAttribute("value", password);
// if you already found the last fields the button should also be there...
var inputs = w.Document.GetElementsByTagName("input");
int counter = 0;
bool enableClick = false;
// iterate through all the inputs in the document
foreach (HtmlElement btn in inputs)
{
try
{
var att = btn.GetAttribute("tabindex");
var name = btn.GetAttribute("id");
if (enableClick)// button to submit always has a differnt id. it should be after password textbox
{
btn.InvokeMember("click");
counter++;
}
if (name.ToUpper().Contains("PASS") || att=="4")
{
enableClick = true; // button should be next to the password input
}
// try a max of 5 times
if (counter > 5)
{
break;
}
}
catch
{
}
}
}
Checkout the facebook-sharp SDK for Windows forms:
https://github.com/facebook-csharp-sdk/facebook-winforms
I recommend you use Facebook C# SDK. It uses the OAuth protocol, for user-authentication.
Down an code example how to get user friends with Facebook-C#-SDK:
using Facebook; //add reference to facebook dll for it work
declare the fields:
private FacebookOAuthResult result;
private FacebookOAuthClient OAuth;
and
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
if (webBrowser1.Url.AbsolutePath == "/login.php")
{
// do login..
}
if (FacebookOAuthResult.TryParse(e.Url, out result))
{
if (result.IsSuccess)
{
FacebookClient fbClient = new FacebookClient(result.AccessToken);
dynamic friends = fbClient.Get("/me/friends"); //User friends
// do something..
}
else
{
string errorDescription = result.ErrorDescription;
string errorReason = result.ErrorReason;
string msg = String.Format("{0} ({1})", errorReason, errorDescription);
MessageBox.Show(msg, "User-authentication failed!");
}
}
}
and then for start user-authentication:
//..
OAuth = new FacebookOAuthClient();
OAuth.AppId = appId; // see link above,you can find how to get it
OAuth.AppSecret = appSecret; // see link above,you can find how to get it
Uri loginUrl = OAuth.GetLoginUrl(paramenters);
webBrowser1.Navigate(loginUrl.AbsoluteUri);