Closing WebBrowser form opens URL in standard browser - c#

After some actions I use this.Close(); in C#, which should close form with WebBrowser element. But after closing it my standard installed browser(Chrome) opens with the last URL from WebBrowser element. How can I avoid this?
Code I'm using
public Vk_connect()
{
string url = "https://oauth.vk.com/authorize?client_id=" + appID + "&scope=friends,photos,audio,video,docs,notes,wall,messages&redirect_uri=https://oauth.vk.com/blank.html&display=popup&response_type=token";
this.Text = "Connect to VK";
InitializeComponent();
this.vkconnect.Navigate(url);
vkconnect.Navigated += vkconnect_Navigated;
}
void vkconnect_Navigated(object sender, WebBrowserNavigatedEventArgs e)
{
token = vkconnect.Url.ToString();
if (token.Contains("#access_token"))
{
token = token.Split('#')[1];
id = token.Split('=')[3];
token = token.Split('&')[0];
token = token.Split('=')[1];
config.token = token;
config.userid = id;
vkconnect.Stop();
this.Close();
}
}

I am checking whether browser has finished all redirections by looking at webBrowser1.StatusText.
private void webBrowser1_Navigated(object sender, WebBrowserNavigatedEventArgs e)
{
if (webBrowser1.StatusText.Equals("Done"))
{
this.Close();
}
}

Related

How to implement new tab in CefSharp with correct address and title change?

I am using CefSharp to create a browser. It is working, I can navigate to various websites by using new tab. But when I click on previous tabs, all the tab shows same URL in the address bar and all of them has exactly same title. Here is my code:
private void FormBrowser_Load(object sender, EventArgs e)
{
CefSettings settings = new CefSettings();
Cef.Initialize(settings);
ChromiumWebBrowser browser = new ChromiumWebBrowser(toolStripTextBoxAddress.Text);
browser.Parent = tabControl.SelectedTab;
browser.Dock = DockStyle.Fill;
browser.AddressChanged += Browser_AddressChanged;
browser.TitleChanged += Browser_TitleChanged;
}
// new tab function
public void addNewTab()
{
TabPage tpage = new TabPage();
tpage.Text = "New Tab";
tabControl.Controls.Add(tpage);
tabControl.SelectTab(tabControl.TabCount - 1);
toolStripTextBoxAddress.Text = "";
ChromiumWebBrowser browser = new ChromiumWebBrowser(toolStripTextBoxAddress.Text);
browser.Parent = tpage;
browser.Dock = DockStyle.Fill;
browser.AddressChanged += Browser_AddressChanged;
browser.TitleChanged += Browser_TitleChanged;
}
private void Browser_TitleChanged(object sender, TitleChangedEventArgs e)
{
this.Invoke(new MethodInvoker(() =>
{
tabControl.SelectedTab.Text = e.Title;
}));
}
private void Browser_AddressChanged(object sender, AddressChangedEventArgs e)
{
this.Invoke(new MethodInvoker(() =>
{
toolStripTextBoxAddress.Text = e.Address;
}));
}
// navigate method
private void toolStripTextBoxAddress_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
if (!string.IsNullOrEmpty(toolStripTextBoxAddress.Text))
{
if (!toolStripTextBoxAddress.Text.Contains("."))
{
getCurrentBrowser().Load("http://www.google.com/search?q=" + toolStripTextBoxAddress.Text);
}
else
{
getCurrentBrowser().Load(toolStripTextBoxAddress.Text);
}
}
}
}
// get current browser
private ChromiumWebBrowser getCurrentBrowser()
{
return (ChromiumWebBrowser)tabControl.SelectedTab.Controls[0];
}
// new tab button
private void toolStripButtonNewTab_Click(object sender, EventArgs e)
{
addNewTab();
}
Here is what I have tried:
private void tabControl_SelectedIndexChanged(object sender, EventArgs e)
{
ChromiumWebBrowser currentBrowser = getCurrentBrowser();
toolStripTextBoxAddress.Text = currentBrowser.Address;
}
When i try to open a new tab it is giving me an error in this line return (ChromiumWebBrowser)tabControl.SelectedTab.Controls[0];
How can I solve this problem? Thanks in advance.
I wrote my multi-tab cefsharp code in a very similar fashion to yours, and encountered the same error.
It was cause by the default number of tab pages. (When you drag tabcontrol to your form, it by default comes with 2 tabpages to start with). From the property panel, I removed those two tabpages, so that the browser starts wit zero tabpage. Any tabpage is only added when you start browsing, by inputting url or clicking favorites.
If you do not set the initial number of tabpages to zero, those two "empty" tabpages have no browser attached to them. Therefore the getcurrentbrowser() function fails to find any browser on those empty tabpages and errors occur.

Multiple conditions in Windows Phone Silverlight development

I am beginning Windows Phone development with Silverlight and web services. I have a web services for User Login where I have two checks before the user is Allowed to log in. I am unable to perform both checks. Only one check is called. My code:
private void login_action(object sender, RoutedEventArgs e)
{
string _username = txtUser.Text;
string _password = txtPass.Password;
kollserviceClient client = new kollserviceClient();
client.validUserCredentialAsync(_username, _password);
client.validUserCredentialCompleted += Client_validUserCredentialCompleted;
client.isStudentUserAsync(_username);
client.isStudentUserCompleted += Client_isStudentUserCompleted;
}
private void Client_isStudentUserCompleted(object sender, isStudentUserCompletedEventArgs e)
{
if (!e.Result)
{
MessageBox.Show("User is Not a Student. Unable to Login", "Error", MessageBoxButton.OK);
return;
}
}
private void Client_validUserCredentialCompleted(object sender, validUserCredentialCompletedEventArgs e)
{
if (e.Result)
{
IsolatedStorageSettings.ApplicationSettings["lgusername"] = txtUser.Text;
NavigationService.Navigate(new Uri("/Home.xaml", UriKind.RelativeOrAbsolute));
}
}
If the Credentials are valid the user is able to log in whether he/she is a student user or not. How can I make both check to be executed?
The way this is coded, I don't believe that you can guarantee the order in which the service calls will return. Therefore, you could store the results from each call, then call a 3rd method that evaluates that both calls have returned. Another option would be to chain the calls so that it does not check if the user is a student until it returns from the credential check and passes, then you can navigate from the return of that call.
First option example:
private void login_action(object sender, RoutedEventArgs e)
{
string _username = txtUser.Text;
string _password = txtPass.Password;
kollserviceClient client = new kollserviceClient();
client.validUserCredentialAsync(_username, _password);
client.validUserCredentialCompleted += Client_validUserCredentialCompleted;
client.isStudentUserAsync(_username);
client.isStudentUserCompleted += Client_isStudentUserCompleted;
}
private bool? isStudent = null;
private bool? isAuthenticated = null;
private void Client_isStudentUserCompleted(object sender, isStudentUserCompletedEventArgs e)
{
isStudent = e.Result;
EvaluateAndNavigate();
}
private void Client_validUserCredentialCompleted(object sender, validUserCredentialCompletedEventArgs e)
{
isAuthenticated = e.Result;
if (isAuthenticated)
{
IsolatedStorageSettings.ApplicationSettings["lgusername"] = txtUser.Text;
}
EvaluateAndNavigate();
}
private void EvaluateAndNavigate()
{
if(isStudent.HasValue && isAuthenticated.HasValue) //both calls have returned
{
if(isStudent.Value && isAuthenticated.Value)
{
NavigationService.Navigate(new Uri("/Home.xaml", UriKind.RelativeOrAbsolute));
}
else
{
MessageBox.Show(string.Format("{0}Unable to Login", isStudent.Value ? "" : "User is Not a Student. " ), "Error", MessageBoxButton.OK);
}
}
}

How to navigate to new url after login to instagram using c#

hi i'm trying to build an app that allow to login to instagram using c#
when i run my application and logged in , i need to be redirected to fixed page
without any reaction from me
here's my code :
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
HtmlDocument doc = web.Document;
HtmlElement username = doc.GetElementById("id_username");
HtmlElement password = doc.GetElementById("id_password");
username.SetAttribute("value", "test");
password.SetAttribute("value", "test");
StringBuilder sb = new StringBuilder();
foreach (HtmlElement elm in web.Document.All)
if (elm.GetAttribute("value") == "Log in")
{
sb.Append(elm.InnerHtml);
Thread.Sleep(3000);
elm.InvokeMember("click");
web.Navigate(#"https://instagram.com/accounts/edit/"); // it navigate me but required to login again
}
}
private void web_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
if (web.Document.Url.AbsoluteUri.Equals(#"https://instagram.com"))
{
MessageBox.Show("logged in");
}
}
}
}
You need to keep session cookies. Better to use some component that allow you to connect to instagram, like: https://www.nuget.org/packages/InstaSharp/

Winforms Webbrowser control URL Validation

I am trying to validate a winform web browser control url when a button is clicked. I would like to see if the web browser's current url matches a certain url. When I try to run this code the program freezes
private void button_Click(object sender, EventArgs e)
{
// Check to see if web browser is at URL
if (webBrowser1.Url.ToString != "www.google.com" || webBrowser1.Url.ToString == null)
{
// Goto webpage
webBrowser1.Url = new Uri("www.google.ca");
}
else {
webBrowser1.Document.GetElementById("first").InnerText = "blah";
webBrowser1.Document.GetElementById("second").InnerText = "blah";
}
}
Here you go.
private void button1_Click(object sender, EventArgs e)
{
webBrowser1.Url = new Uri("https://www.google.ca");
// Check to see if web browser is at URL
if (webBrowser1.Url != null)
{
if (webBrowser1.Url.ToString() != "https://www.google.com" || webBrowser1.Url.ToString() == null)
{
// Goto webpage
webBrowser1.Url = new Uri("www.google.ca");
}
else
{
webBrowser1.Document.GetElementById("first").InnerText = "blah";
webBrowser1.Document.GetElementById("second").InnerText = "blah";
}
}
}
1) Please use the schema with the URL.
2) Use ToString() as a function.

C# - How to save a string entered in Form2 in Form1

I get the default path from the registry for the Steam installation. But if someone has their games installed to a different folder, the user has to enter it in the Configure form. When the form gets closed, that path entered(from the folder browser or by typing the path in manually) should get saved to a string in the main form and should enable a different Combobox which turns on different buttons. I somehow managed to do the save to the mainform string, but the 2nd combobox doesn't seem to turn on. How can I do it correctly?
** MAIN FORM **
public string NewPath { get; set; }
private ConfigForm otherForm;
string InstallPath = (string)Registry.GetValue(#"HKEY_CURRENT_USER\SOFTWARE\Valve\Steam", "SteamPath", null);
private void PortalHammerButton_Click(object sender, EventArgs e)
{
Process.Start(InstallPath + #"\SteamApps\common\Portal\bin\hammer.exe");
}
private void Gamedropdown_SelectedIndexChanged(object sender, EventArgs e)
{
if (Gamedropdown.Text == "Portal") // When Portal is selected
{
// Enable the Portal SDK buttons
PortalHammerButton.Visible = true;
PortalModelViewerButton.Visible = true;
PortalFacePoserButton.Visible = true;
// Disable the CS:GO SDK buttons
csgoFacePoserButton.Visible = false;
csgoHammerButton.Visible = false;
csgoModelViewerButton.Visible = false;
}
else if (Gamedropdown.Text == "CS:GO") // When CS:GO is selected
{
// Disable Portal SDK buttons
PortalHammerButton.Visible = false;
PortalModelViewerButton.Visible = false;
PortalFacePoserButton.Visible = false;
// Enable CS:GO SDK buttons
csgoFacePoserButton.Visible = true;
csgoHammerButton.Visible = true;
csgoModelViewerButton.Visible = true;
}
}
private void ConfigureButton_Click(object sender, EventArgs e)
{
var configdialog = new ConfigForm();
configdialog.Show();
}
private void PortalDifferentHammerButton_Click(object sender, EventArgs e)
{
Process.Start(NewPath + #"\SteamApps\common\Portal\bin\hammer.exe");
}
private void NewDropDown_SelectedIndexChanged(object sender, EventArgs e)
{
if (NewDropDown.Text == "Portal") // When Portal is selected
{
// Enable the Portal SDK buttons
PortalDifferentHammerButton.Visible = true;
PortalDifferentModelViewerButton.Visible = true;
PortalDifferentFacePoserButton.Visible = true;
// Disable the CS:GO SDK buttons
DifferentCSGOFaceposerButton.Visible = false;
DifferentCSGOHammerButton.Visible = false;
DifferentCSGOModelViewerButton.Visible = false;
}
else if (NewDropDown.Text == "CS:GO") // When CS:GO is selected
{
// Disable the Portal SDK buttons
PortalDifferentFacePoserButton.Visible = false;
PortalDifferentHammerButton.Visible = false;
PortalDifferentModelViewerButton.Visible = false;
// Enable the CS:GO SDK buttons
DifferentCSGOModelViewerButton.Visible = true;
DifferentCSGOHammerButton.Visible = true;
DifferentCSGOFaceposerButton.Visible = true;
}
}
private void button1_Click(object sender, EventArgs e)
{
this.Close();
ConfigForm cfgfrm = new ConfigForm();
cfgfrm.Close();
}
}
}
**CONFIGURE FORM**
public partial class ConfigForm : Form
{
public ConfigForm()
{
InitializeComponent();
Form1 frm1 = new Form1();
frm1.NewPath = NewPathBox.Text;
}
public void DifferentFolderBrowseButton_Click(object sender, EventArgs e)
{
FolderBrowserDialog fbd = new FolderBrowserDialog();
DialogResult result = fbd.ShowDialog();
string newpath = fbd.SelectedPath;
NewPathBox.Text = newpath;
Form1 frm1 = new Form1();
frm1.NewPath = NewPathBox.Text;
}
public void CloseButton_Click(object sender, EventArgs e)
{
this.Hide();
Form1 frm1 = new Form1();
frm1.Gamedropdown.Visible = false;
frm1.NewDropDown.Visible = true;
}
}
}
Any help would be appriciated.
Look at your ConfigForm. Here's your problem:
public ConfigForm()
{
InitializeComponent();
Form1 frm1 = new Form1();
frm1.NewPath = NewPathBox.Text;
}
What you're doing on your Form1 (which I'm guessing is your Main form) is creating a new instance of your ConfigForm and showing it. What you're doing in your ConfigForm is creating a new main form and setting the NewPath = to the value entered on your config form. The problem is this new Form1 is NOT the Form1 that created the ConfigForm. The Form1 that created your config form is not the one getting updated by your code, some arbitrary new Form1 that you create is the one getting updated. This is why your code isn't working as you expected.
Here's the approach I would take. Add a NewPath variable to your ConfigForm just like you have in Form1. Then, add a FormClosing method to FormConfig. Do something like this:
private void ConfigForm_FormClosing(object sender, FormClosingEventArgs e)
{
NewPath = NewPathBox.Text;
}
Then, change your code on Form1 to this:
private void button1_Click(object sender, EventArgs e)
{
ConfigForm cfgfrm = new ConfigForm();
cfgfrm.ShowDialog();
this.NewPath = cfgfrm.NewPath;
}
What this code is doing is creating and showing a new ConfigForm on your Form1 when you click button1. Then, when your user closes the FormConfig, the form saves the textbox value to the NewPath variable on the FormConfig. Then, once the form is closed, the code on Form1 resumes. Form1 then looks at the NewPath value that was saved when the user closed the FormConfig. Form1 grabs this new NewPath value and puts it in its own NewPath variable.
EDIT
To show/hide comboboxes:
private void button1_Click(object sender, EventArgs e)
{
ConfigForm cfgfrm = new ConfigForm();
cfgfrm.ShowDialog();
this.NewPath = cfgfrm.NewPath;
Gamedropdown.Visible = false;
NewDropDown.Visible = true
}
I'm not sure why you are making the secondary form so complicated. You don't need a pointer to it after you use it and you should be closing instead of hiding. Try this:
class ConfigForm : Form
{
public string newPath = null;
public void CloseButton_Click(object sender, EventArgs e)
{
newPath = NewPathBox.Text;
}
public void CloseButton_Click(object sender, EventArgs e)
{
Close();
}
}
...and in your main form:
public partial class Form1 : Form
{
string steamPath = null; // set to starting path
private void ConfigureButton_Click(object sender, EventArgs e)
{
bool valueChanged = false;
using (ConfigForm form = new ConfigForm())
{
form.newPath = null;
form.ShowDialog();
if (form.newPath != null)
{
steamPath = form.newPath;
valueChanged = true;
}
}
if (valueChanged)
{
// here is where you would handle reloading and changing the ComboBoxes
}
}
}
This will more cleanly return the new string. Whatever you want to do as a result of having changed the path can be done after you have disposed of the config form (bringing it up with the "using" conditional automatically does the disposal for you)

Categories

Resources