Adding back and forward button for WebBrowser control - c#

I have a WebBrowser element in a page, to which I would like to add a back and forward buttons, and have those buttons disabled when there's nothing to go back to and nothing to go forward to.
In Cocoa, the UIWebView has methods to easily check that: canGoBack and canGoForward, and you have goBack and goForward methods available (along with reload etc..)
Android has the exact same method names for achieving the same.
I see those methods are available in .Net 4 and 3.5 SP1.
I've found some references about using javascript commands in Silverlight but I find this very cumbersome, plus there's no way to detect if there's anything in the history (unless of course I manage this myself)
Surely, there's something a tad more advanced in Windows Phone ..

Here is how I ended up doing it.
This assumes you have set a backButton and forwardButton; the status of these buttons will be updated accordingly depending on where you are in the navigation stack.
webView is the WebBrowser object
List<Uri> HistoryStack;
int HistoryStack_Index;
bool fromHistory;
// Constructor
public HelpView()
{
InitializeComponent();
HistoryStack = new List<Uri>();
HistoryStack_Index = 0;
fromHistory = false;
webView.Navigated += new EventHandler<System.Windows.Navigation.NavigationEventArgs>(WebView_Navigated);
UpdateNavButtons();
}
private void backButton_Click(object sender, RoutedEventArgs e)
{
if (HistoryStack_Index > 1)
{
HistoryStack_Index--;
fromHistory = true;
webView.Navigate(HistoryStack[HistoryStack_Index-1]);
updateNavButtons();
}
}
private void forwardButton_Click(object sender, RoutedEventArgs e)
{
if (HistoryStack_Index < HistoryStack.Count)
{
HistoryStack_Index++;
fromHistory = true;
webView.Navigate(HistoryStack[HistoryStack_Index-1]);
UpdateNavButtons();
}
}
private void UpdateNavButtons()
{
this.backButton.IsEnabled = HistoryStack_Index > 1;
this.forwardButton.IsEnabled = HistoryStack_Index < HistoryStack.Count;
}
private void WebView_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
{
if (!fromHistory)
{
if (HistoryStack_Index < HistoryStack.Count)
{
HistoryStack.RemoveRange(HistoryStack_Index, HistoryStack.Count - HistoryStack_Index);
}
HistoryStack.Add(e.Uri);
HistoryStack_Index++;
UpdateNavButtons();
}
fromHistory = false;
}

I have a back button added to the applicationbar of a page in one of my apps which contains a webbrowser. I wanted the back button in the app bar to take the web page navigation backward, and wanted the hardware back button to go to the previous xaml page. This way, the user doesn't have to use the hardware back button to navigate backward through all the visited web pages in the webbrowser in order to go back to the prior xaml page. Here is how I did it, and you could easily set up a forward stack and when the user clicks the back (appbar) button, the page pops from that stack and is pushed to the forward stack.
private void NavigateWeb()
{
if (!loaded)
{
NavigationStack.Clear();
try
{
Web.Source = new Uri("http://m.weightwatchers.com/");
loaded = true;
}
catch (Exception ex)
{
MessageBox.Show("Unable to navigate to page.\n" + ex.Message,
"Error", MessageBoxButton.OK);
}
}
}
void Web_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
{
NavigationStack.Push(e.Uri);
}
void btnBack_Click(object sender, EventArgs e)
{
if (NavigationStack.Count > 2)
{
// get rid of the topmost item...
NavigationStack.Pop();
// now navigate to the next topmost item
// note that this is another Pop - as when the navigate occurs a Push() will happen
Web.Navigate(NavigationStack.Pop());
}
}
The reason I check for NavigationStack.Count > 2 is that the particular webpage that I'm showing in the webbrowser always starts with a "click here to continue" link on the first page, and there is no reason to go back to there. That's the downfall of showing other people's sites in your webbrowser - you don't have control over what is shown.

In regards to the javascript solution it is doing something like this:
private void backButton_Click(object sender, RoutedEventArgs e)
{
try
{
webView.InvokeScript("eval", "history.go(-1);");
}
catch
{
// Eat error
}
}
private void forwardButton_Click(object sender, RoutedEventArgs e)
{
try
{
webView.InvokeScript("eval", "history.go(1);");
}
catch
{
// Eat error
}
}
with having the IsScriptingEnabled set to true for the WebBrowser element.
However, this always generates an exception with error 80020006. I read various posts about how the DOCTYPE could have been the culprit, the system caching or IsScriptEnabled being set after the content was loaded... It just never worked...

Related

How to disable every navigation in WebBrowser?

I have a WebBrowser control which I dinamically refresh/change url based on user input. I don't want to let the user to navigate, so I set AllowNavigation to false. This seems to be OK, however the below link is still "active":
Close Page
The issue here is: If the user clicks it, and confirms closure in the pop-up window I can't manage WebBrowser anymore. Looks like it is closed though the last page is still visible. Also I can't remove this link as the site is not managed by me.
Disable the control? Nope, I have to allow the user to highlight and copy text from the webpage.
Do I have any other option to disable literally ALL links?
#TaW: here is my code based on yours. So I have to set the url from my code and call a custom one:
button_click()
{
webBrowser1_load_URL("http://website/somecheck.php?compname=" + textBoxHost.Text);
}
Here it is the function:
private void webBrowser1_load_URL(string url)
{
string s = GetDocumentText(url.ToString());
s = s.Replace(#"javascript:window.close()", "");
webBrowser1.AllowNavigation = true;
webBrowser1.DocumentText = s;
}
The rest is exaclty what's in your answer:
private void webBrowser1_DocumentCompleted(object sender,
WebBrowserDocumentCompletedEventArgs e)
{
webBrowser1.AllowNavigation = false;
}
public string GetDocumentText(string s)
{
WebBrowser dummy = new WebBrowser(); //(*)
dummy.Url = new Uri(s);
return dummy.DocumentText;
}
Still it's not working. Please help me to spot the issue with my code.
If you have control over the loading of the pages you could grab the pages' text and change the code to disable rogue scripts. The one you showed can simply be deleted. Of course you might have to forsee more than the one..
Obviously this could be eased if you could do without javascript alltogether, but if that is not an option go for those that do real or pseudo-navigation..
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
webBrowser1.AllowNavigation = false;
}
private void loadURL_Click(object sender, EventArgs e)
{
webBrowser1.AllowNavigation = true;
string s = File.ReadAllText(textBox_URL.Text);
s = s.Replace("javascript:window.close()", "");
webBrowser1.DocumentText = s;
}
If the pages are not in the file system, the same trick should work, for instance by loading the URL into a dummy WebBrowser like this:
private void cb_loadURL_Click(object sender, EventArgs e)
{
string s = GetDocumentText(tb_URL.Text);
s = s.Replace("javascript:window.close()", "");
webBrowser1.AllowNavigation = true;
webBrowser1.DocumentText = s;
}
public string GetDocumentText(string s)
{
WebBrowser dummy = new WebBrowser(); //(*)
dummy.Url = new Uri(s);
return dummy.DocumentText;
}
Note: According to this post you can't set the DocumentText quite as freely as one would think; probably a bug.. Instead of creating the dummy each time you can also move the (*) line to class level. Then, no matter how many changes you had to make, you would always have an unchanged version, th user could e.g. save somewhere..

Need to send two buttons backwards and forwards

I've got the code, and all seems correct, I've had it reviewed and it seems impossible to find out why the button isn't doing what its coded to do. I'm making a Music player, and when I press the play button, it will be sent to the back and the pause button will become visible, when I next click the pause button, nothing happens and its primary function stops working all together. Here is the code for people to examine.
private void btnPlay_Click(object sender, EventArgs e)
{
try
{
if (_mp3Player != null)
_mp3Player.Play();
btnPlay.SendToBack();
btnPause.BringToFront();
}
catch (Win32Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void btnPause_Click(object sender, EventArgs e)
{
if (_mp3Player != null)
_mp3Player.Stop();
btnPause.SendToBack();
btnPlay.BringToFront();
}
Perhaps it would be best to use visibility?
private void btnPause_Click(object sender, EventArgs e)
{
if (_mp3Player != null)
{
_mp3Player.Stop();
}
btnPause.Visible = False;
btnPlay.Visible = True;
}
Or even the enabled property?
... btnPause.Enabled = false; ...
However I feel you could make it better by having it be the same button, with a value, so just have a value on it of true if it's player or false if it's pause and then in the click event check against that value to determine what it is currently and then just execute the relevant functionality and change the text or image that you have on the button.

Windows Phone 8 Back button to go back in WebBrowser

I made a WebBrowser and it works except the back button after pressing the back button the app closes and does not go back one in history. How can I solve the problem? I found solutions in the internet but they don't seem to work.
public MainPage()
{
this.InitializeComponent();
this.webBrowser.Navigate(new Uri("http://www.google.com", UriKind.Absolute));
this.webBrowser.LoadCompleted += webBrowser_LoadCompleted;
this.webBrowser.NavigationFailed += webBrowser_NavigationFailed;
this.webBrowser.IsScriptEnabled = true;
}
protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
{
webBrowser.InvokeScript("eval", "history.go(-1)" );
}
P. S.:that is not the whole script but i think the rest is unneccesary if not tell me :)
P. P. S.:I'm new to Windows Phone programing.
Web browser is just a control inside the page and pressing the device back button navigates back to the previous page or exits the app if it has only one page. So, you would need to stop page navigation on back key press something like this.
protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
{
e.Cancel=true;
}
This prevents a backnavigation
Now rest is to go to the previous page which can be done by
webBrowser.InvokeScript("eval", "history.go(-1)" );
so the event becomes
protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
{
e.Cancel=true;
webBrowser.InvokeScript("eval", "history.go(-1)" );
}
Try to do:
protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
{
WB1.InvokeScript("eval", "history.go(-1)");
e.Cancel = true;
}
When you override OnBackKeyPress, and you don't perform e.Cancel = true; it will do your code, but will also do what normal BackButton does - NavigateBack, Exit App and so on. But you must remember to leave the User an ability to exit your App or Navigate Back, so it will be more suitable to check some conditions (e.g. your webbrowser history is not null) and then do e.Canel, otherwise Exit the App.
To exit the app when you are in the root (so you can approve the cerfitication requirements), and also go back in navigation until you are in the root, try with this
protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
{
if (MiniBrowser.CanGoBack){
e.Cancel = true;
MiniBrowser.InvokeScript("eval", "history.go(-1)");
}
}

C# Tabless Control Previous/Back/Return Button failing?

I am hoping someone here can help me, i have a Tabless Control on my windows forms application and basically because the tabs are purposely hidden i have added 2 buttons to each tab "Next" and "Back".
This is the code snippet i have for my "Next" button:
private void nextbutton1_Click(object sender, EventArgs e)
{
tabControl1.SelectedTab = tabPage3;
this.toolStripStatusLabel8.Text = System.DateTime.Now.ToString();
}
Which works fine, however when i use the exact same theory on the "Back" button it does not work:
private void backbutton1_Click(object sender, EventArgs e)
{
tabControl1.SelectedTab = tabmain;
this.toolStripStatusLabel1.Text = System.DateTime.Now.ToString();
}
So my question is how does one go to a previous tabpage from a button? I have looked through here and tried all of the links that came up but nothing has worked any ideas?
You should use the SelectedIndex property instead of using concrete TabPage instances. This way it will still work when you decide to change the order of the pab pages or add new pages:
private void previousButton_Click(object sender, EventArgs e)
{
if (tabControl1.SelectedIndex > 0)
{
tabControl1.SelectedIndex--;
}
}
private void nextButton_Click(object sender, EventArgs e)
{
if (tabControl1.SelectedIndex < tabControl1.TabCount - 1)
{
tabControl1.SelectedIndex++;
}
}
Since there is no "Tabless" tab control in .NET Framework I can only assume that it works similar to the standard TabControl. If the solution doesn't work you should give us some information about the actual class you use.
BTW: There is no need to repeat the buttons on each page. Why don't you just put the buttons outside the TabControl?
Also: I see that you use a ToolStripStatusLabel to show the current time. Instead of updating it each time the user clicks somewhere add a Timer to your form. Set its Interval to 1000 and handle its Tick event. Update the label there:
private void timer1_Tick(object sender, EventArgs e)
{
toolStripStatusLabel1.Text = DateTime.Now.ToLongTimeString();
}
This way it updates constantly and again there is no need to repeat anything. You need to call timer1.Start() in the form's constructor.

How can I disable a tab inside a TabControl?

Is there a way to disable a tab in a TabControl?
Cast your TabPage to a Control, then set the Enabled property to false.
((Control)this.tabPage).Enabled = false;
Therefore, the tabpage's header will still be enabled but its contents will be disabled.
The TabPage class hides the Enabled property. That was intentional as there is an awkward UI design problem with it. The basic issue is that disabling the page does not also disable the tab. And if try to work around that by disabling the tab with the Selecting event then it does not work when the TabControl has only one page.
If these usability problems do not concern you then keep in mind that the property still works, it is merely hidden from IntelliSense. If the FUD is uncomfortable then you can simply do this:
public static void EnableTab(TabPage page, bool enable) {
foreach (Control ctl in page.Controls) ctl.Enabled = enable;
}
You can simply use:
tabPage.Enabled = false;
This property is not shown, but it works without any problems.
You can program the Selecting event on TabControler to make it impossible to change to a non-editable tab:
private void tabControler_Selecting(object sender, TabControlCancelEventArgs e)
{
if (e.TabPageIndex < 0) return;
e.Cancel = !e.TabPage.Enabled;
}
You could register the "Selecting" event and cancel the navigation to the tab page:
private void tabControl1_Selecting(object sender, TabControlCancelEventArgs e)
{
if (e.TabPage == tabPage2)
e.Cancel = true;
}
Another idea is to put all the controls on the tabpage in a Panel control and disable the panel! Smiley
You could also remove the tabpage from the tabControl1.TabPages collection. That would hide the tabpage.
Credits go to littleguru # Channel 9.
Presumably, you want to see the tab in the tab control, but you want it to be "disabled" (i.e., greyed, and unselectable). There is no built-in support for this, but you can override the drawing mechanism to give the desired effect.
An example of how to do this is provided here.
The magic is in this snippet from the presented source, and in the DisableTab_DrawItem method:
this.tabControl1.DrawMode = TabDrawMode.OwnerDrawFixed;
this.tabControl1.DrawItem += new DrawItemEventHandler( DisableTab_DrawItem );
Extending upon Cédric Guillemette answer, after you disable the Control:
((Control)this.tabPage).Enabled = false;
...you may then handle the TabControl's Selecting event as:
private void tabControl_Selecting(object sender, TabControlCancelEventArgs e)
{
e.Cancel = !((Control)e.TabPage).Enabled;
}
This will remove the tab page, but you'll need to re-add it when you need it:
tabControl1.Controls.Remove(tabPage2);
If you are going to need it later, you might want to store it in a temporary tabpage before the remove and then re-add it when needed.
The only way is to catch the Selecting event and prevent a tab from being activated.
The most tricky way is to make its parent equals null (make the tab alone without parent):
tabPage.Parent = null;
And when you want to return it back (will return it back at the end of pages collection) :
tabPage.Parent = tabControl;
And if you want to return it back in a specific location among the pages you can use :
tabControl.TabPages.Insert(indexLocationYouWant, tabPage);
I had to handle this a while back. I removed the Tab from the TabPages collection (I think that's it) and added it back in when the conditions changed. But that was only in Winforms where I could keep the tab around until I needed it again.
I've removed tab pages in the past to prevent the user from clicking them. This probably isn't the best solution though because they may need to see that the tab page exists.
Using events, and the properties of the tab control you can enable/disable what you want when you want. I used one bool that is available to all methods in the mdi child form class where the tabControl is being used.
Remember the selecting event fires every time any tab is clicked. For large numbers of tabs a "CASE" might be easier to use than a bunch of ifs.
public partial class Form2 : Form
{
bool formComplete = false;
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
formComplete = true;
tabControl1.SelectTab(1);
}
private void tabControl1_Selecting(object sender, TabControlCancelEventArgs e)
{
if (tabControl1.SelectedTab == tabControl1.TabPages[1])
{
tabControl1.Enabled = false;
if (formComplete)
{
MessageBox.Show("You will be taken to next tab");
tabControl1.SelectTab(1);
}
else
{
MessageBox.Show("Try completing form first");
tabControl1.SelectTab(0);
}
tabControl1.Enabled = true;
}
}
}
I've solved this problem like this:
I've got 3 tabs and I want to keep user at the first tab if he didnt log in,
so on the SelectingEvent of TabControl I wrote
if (condition) { TabControl.Deselect("2ndPage"); TabControl.Deselect("3dPage"); }
The user cannot click on tabs to navigate, but they can use the two buttons (Next and Back). The user cannot continue to the next if the //conditions are no met.
private int currentTab = 0;
private void frmOneTimeEntry_Load(object sender, EventArgs e)
{
tabMenu.Selecting += new TabControlCancelEventHandler(tabMenu_Selecting);
}
private void tabMenu_Selecting(object sender, TabControlCancelEventArgs e)
{
tabMenu.SelectTab(currentTab);
}
private void btnNextStep_Click(object sender, EventArgs e)
{
switch(tabMenu.SelectedIndex)
{
case 0:
//if conditions met GoTo
case 2:
//if conditions met GoTo
case n:
//if conditions met GoTo
{
CanLeaveTab:
currentTab++;
tabMenu.SelectTab(tabMenu.SelectedIndex + 1);
if (tabMenu.SelectedIndex == 3)
btnNextStep.Enabled = false;
if (btnBackStep.Enabled == false)
btnBackStep.Enabled = true;
CannotLeaveTab:
;
}
private void btnBackStep_Click(object sender, EventArgs e)
{
currentTab--;
tabMenu.SelectTab(tabMenu.SelectedIndex - 1);
if (tabMenu.SelectedIndex == 0)
btnBackStep.Enabled = false;
if (btnNextStep.Enabled == false)
btnNextStep.Enabled = true;
}
tabControl.TabPages.Remove(tabPage1);
This is an old question, but someone may benefit from my addition. I needed a TabControl that would show hidden tabs successively (after an action was performed on the current tab). So, I made a quick class to inherit from and called HideSuccessive() on Load:
public class RevealingTabControl : TabControl
{
private Action _showNextRequested = delegate { };
public void HideSuccessive()
{
var tabPages = this.TabPages.Cast<TabPage>().Skip(1);
var queue = new ConcurrentQueue<TabPage>(tabPages);
tabPages.ToList().ForEach(t => t.Parent = null);
_showNextRequested = () =>
{
if (queue.TryDequeue(out TabPage tabPage))
tabPage.Parent = this;
};
}
public void ShowNext() => _showNextRequested();
}
There is the XtraTabPage.PageEnabled property allowing you to disable certain pages.
Here the solution that i implement:
private void switchTapPage(TabPage tabPage)
{
foreach(TabPage page in tabControl1.TabPages)
{
tabControl1.TabPages.Remove(page);
}
tabControl1.TabPages.Add(tabPage);
}
Basically, i just call this method sending the tabPage that i currently need to show, the method will remove all the tabPages on the tabControl and after that it will just add the one that i sent it.
So the rest of the tabHeaders will not shown and they will be inaccessible, because they dont even exists in the tabControl.
I took the idea from the #stormenet answer.
You can do it through the tabpages: tabPage1.Hide(), tabPage2.Show() etc.
In the form load event if we write this.tabpage.PageEnabled = false, the tabpage will be disabled.
Assume that you have these controls:
TabControl with name tcExemple.
TabPages with names tpEx1 and tpEx2.
Try it:
Set DrawMode of your TabPage to OwnerDrawFixed;
After InitializeComponent(), make sure that tpEx2 is not enable by adding this code:
((Control)tcExemple.TabPages["tpEx2").Enabled = false;
Add to Selection tcExemple event the code below:
private void tcExemple_Selecting(object sender, TabControlCancelEventArgs e)
{
if (!((Control)e.TabPage).Enabled)
{
e.Cancel = true;
}
}
Attach to DrawItem event of tcExemple this code:
private void tcExemple_DrawItem(object sender, DrawItemEventArgs e)
{
TabPage page = tcExemple.TabPages[e.Index];
if (!((Control)page).Enabled)
{
using (SolidBrush brush = new SolidBrush(SystemColors.GrayText))
{
e.Graphics.DrawString(page.Text, page.Font, brush, e.Bounds);
}
}
else
{
using (SolidBrush brush = new SolidBrush(page.ForeColor))
{
e.Graphics.DrawString(page.Text, page.Font, brush, e.Bounds);
}
}
}
It will make the second tab non-clickable.
I could not find an appropriate answer to the question. There looks to be no solution to disable the specific tab. What I did is to pass the specific tab to a variable and in SelectedIndexChanged event put it back to SelectedIndex:
//variable for your specific tab
int _TAB = 0;
//here you specify your tab that you want to expose
_TAB = 1;
tabHolder.SelectedIndex = _TAB;
private void tabHolder_SelectedIndexChanged(object sender, EventArgs e)
{
if (_TAB != 0) tabHolder.SelectedIndex = _TAB;
}
So, you don't actually disable the tab, but when another tab is clicked it always returns you to the selected tab.
in C# 7.0, there is a new feature called Pattern Matching. You can disable all tabs via Type Pattern.
foreach (Control control in Controls)
{
// the is expression tests the variable and
// assigned it to a new appropriate variable type
if (control is TabControl tabs)
{
tabs.Enabled = false;
}
}
Use:
tabControl1.TabPages[1].Enabled = false;
By writing this code, the tab page won't be completely disabled (not being able to select), but its internal content will be disabled which I think satisfy your needs.
The solution is very simple.
Remove/comment this line
this.tabControl.Controls.Add(this.YourTabName);
in IntializeComponent() method in MainForm.cs
MyTabControl.SelectedTab.Enabled = false;

Categories

Resources