VB.NET WebBrowser disable javascript - vb.net

Is there a way to disable javascript webbrowser in vb.net?

works for me:
Private Function TrimScript(ByVal htmlDocText As String) As String
While htmlDocText.ToLower().IndexOf("<script type=""text/javascript"">") > -1
Dim s_index As Integer = htmlDocText.ToLower().IndexOf("<script type=""text/javascript"">")
Dim e_index As Integer = htmlDocText.ToLower().IndexOf("</script>")
htmlDocText = htmlDocText.Remove(s_index, e_index - s_index)
End While
Return htmlDocText
End Function
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim webClient As New System.Net.WebClient
Dim result As String = webClient.DownloadString(yourUrl)
Dim wb As New WebBrowser
wb.Navigate("")
Do While wb.ReadyState <> WebBrowserReadyState.Complete
Application.DoEvents()
Loop
Dim script As String = TrimScript(result)
wb.DocumentText = script
End Sub

The short answer is: No.
The slightly longer answer is: No, the web-browser control API does not allow disabling standard browser functionality.

No really...but if you getting that annoying error message that pops up saying a script is running then you can turn the property of the webbrowser's suppress-errors "true"

Which popup message do you want to disable? If it's the alert message, try this, obviously resolving the window or frame object to your particular needs, I’ve just assumed top-level document, but if you need an iframe you can access it using window.frames(0). for the first frame and so on... (re the JavaScript part)... here is some code, assuming WB is your webbrowser control...
WB.Document.parentWindow.execScript "window.alert = function () { };", "JScript"
You must run the above code only after the entire page is done loading, i understand this is very difficult to do (and a full-proof version hasn't been published yet) however I have been doing it (full proof) for some time now, and you can gather hints on how to do this accurately if you read some of my previous answers labelled "webbrowser" and "webbrowser-control", but getting back to the question at hand, if you want to cancel the .confirm JavaScript message, just replace window.alert with window.confirm (of course, qualifying your window. object with the correct object to reach the document hierarchy you are working with). You can also disable the .print method with the above technique and the new IE9 .prompt method as well.
If you want to disable JavaScript entirely, you can use the registry to do this, and you must make the registry change before the webbrowser control loads into memory, and every time you change it (on & off) you must reload the webbrowser control out and into memory (or just restart your application).
The registry key is \HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\ - the keyname is 1400 and the value to disable it is 3, and to enable it is 0.
Of course, because there are 5 zones under the Zones key, you need to either change it for the active zone or for all zones to be sure. However, you really don't need to do this if all you want to do si supress js dialog popup messages.
Let me know how you go, and if I can help further.

Related

Saving Database issue

So basically, I believe I am using the correct code yet the database will still not update. It will work for the current session, however, when I stop and restart the program, it appears that the data has not been updated in the database.
The really interesting part is that I am using the same method to update the database elsewhere, which when used and session restarted, the database has been updated.
p.s. I also have the same adapters and binding sources set up etc on both forms
I am so confused, help pls
Code that I believe is correct but is not working: (updating on another form so I have one place where all forms update hence FRMMain. etc)
Private Sub btnConfirm_Click(sender As Object, e As EventArgs) Handles btnConfirm.Click
Dim CurrentPoints As Integer
Dim UpdatedPoints As Integer
CurrentPoints = FRMMain.MyDBDataSet.Tables("TBLPupil").Rows(looopcount)(15)
UpdatedPoints = CurrentPoints + stfPoints
FRMMain.MyDBDataSet.Tables("TBLPupil").Rows(looopcount)(15) = UpdatedPoints
FRMMain.TBLPupilTableAdapter.Update(MyDBDataSet.TBLPupil)
FRMMain.TBLPupilTableAdapter.Fill(MyDBDataSet.TBLPupil)
End Sub
Code that I am using in another form that that DOES work:
Private Sub BtnYes_Click(sender As Object, e As EventArgs) Handles BtnYes.Click
Dim Points As Integer = FRMPupil.Pointss
Dim Cost As Integer = FRMPupil.RewardCost
Points = Points - Cost
FRMPupil.LePoints = Points
MyDBDataSet.Tables("TBLPupil").Rows(FRMLogin.DBLocation)(15) = Points
FRMMain.TBLPupilTableAdapter.Update(MyDBDataSet.TBLPupil)
FRMMain.TBLPupilTableAdapter.Fill(MyDBDataSet.TBLPupil)
Me.Hide()
End Sub
My code is correct but is not working.
No, if it is not working, then it is not correct!
There are different things you can do: DRY, Dont Repeat Yourself. You are repeating the code for updating points at several places in your code. This is error prone. Write it once and re-use it, e.g. by applying the the Repository Pattern. It makes it easier to detect errors and correct them. It allows you to re-use code that has already been tested in other scenarios (on another form).
Debug, debug, debug. Place breakpoints in the not working methods and see what happens. Do all the variables have the expected values? E.g., does looopcount have the same value as FRMLogin.DBLocation? There must be a difference somewhere. See: Navigating through Code with the Debugger or the more recent article Debug your Hello World application with Visual Studio 2017.

Visual Studio 2013: Cannot update textbox with event handler

I am building an application using one of our vendors interfaces, which is required to keep a status message box updated.
I have some events which I have handled for testing using a Message box, but now I come to pass these messages to the display box I get nothing.
Public Shared Sub PageAirHandler(ChannelNum As Integer, Index As Integer, ChannelType As CLARITYCOMLib.ChannelType, PageName As String) Handles Status1.AirStatusChanged
MessageBox.Show(PageName)
ControlPanel.AirStatusBox.Text = PageName
End Sub
The messagebox dutifully displays the PageName string, but the textbox does nothing... even if I replace the PageName String variable with "test"
ControlPanel.AirStatusBox.Text = "test"
I get no activity, no errors, nada.
I have googled around, but every example I can find seems to show the same code.
I have recreated the textbox, tried buttons, labels and other objects with the same result.
Setting up a button click handler to update any of these works as expected.
Apologies if this is a noob blunder, but it's driving me nuts!
Using dlg As New Form2
dlg.ShowDialog()
End Using
Things like:
Form2.Show()
Form2.Show(Me)
Form2.ShowDialog()
Form2.ShowDialog(Me)
SHOUL BE AVOIDED but are possible, because Vb.net creates an implicit instance.
But the problem is, this instance gets killed if
the call has be done.
There you can see that a class instance of a project does not interact correctly
in some cases.
As Hans Passant said, your call to set the textbox text
targets the wrong instance.
Invoking to user controls is also possible with:
Me.invoke(sub()
TextBox1.Text = "Blabla"
End sub)

How to set a listview FocusedItem programatically

How can I set the FocusedItem property programatically?
I've tried this so far with no success:
If lvw.FocusedItem Is Nothing Then
If lvw.Items.Count > 0 Then
lvw.Focus()
lvw.HideSelection = False
lvw.Items(0).Selected = True
lvw.Items(0).Focused = True
lvw.FocusedItem = lvw.Items(0)
lvw.Select()
End If
End If
btw the form where the listview is has not called the ShowDialog method yet.
Can this be the reason for this not to work?
You have to understand that each control on the Form and the Form itself is a window and for the window to have focus it must first be created and assigned a handle.
For a basic description of this, I refer you to: All About Handles in Windows Forms The following excerpts are from the referenced article.
What is a Handle?
A handle (HWND) is the return value from CreateWindowEx which the Windows Operating System uses to identify a window. A "window" in win32 is a much broader concept than you may think - each individual button, combobox, listbox etc comprises a window. (For more information see About Window Classes ) NOTE: there are other things known as "Handles" in the Framework - e.g. GDI Handles from a Bitmap or Handles to Device Contexts (HDCs) - this article discusses HWNDs only.
...
When does a Control create its handle? (When does a control call CreateWindowEx?)
A control tries as much as possible to defer creating its handle. This is because setting properties forces chatty interop between the CLR and user32.
Typically the handles for all the controls are created before the
Form.Load event is called. Handles can also be created if the "Handle"
property is called and the handle has not yet been created, or
CreateControl() is called.
So a window's handle is not immediately created when you instantiate a control. However, you can force a control to create its handle by referencing its Handle property.
So if you first get the ListView to create its handle, then when you set those properties that you wanted.
Dim f2 As New Form2
' you do not need this condition, it is here only for demonstration purposes
' so that you can step through the code in the debugger and observe the
' code execution.
If Not f2.ListView1.IsHandleCreated Then
' retrieval of the Handle will cause a handle to be created
' if it has not yet been created
' if you delete the If-Then block, you will need to retain the
' following statement
Dim h As IntPtr = f2.ListView1.Handle
End If
f2.ListView1.FocusedItem = f2.ListView1.Items(2)
f2.ListView1.Items(2).Selected = True
f2.ListView1.Items(2).Focused = True
f2.ActiveControl = f2.ListView1
f2.ShowDialog()
As others have commented, your code should work as written. If all you need is to programmatically access the focused item in your code, you shouldn't be experiencing any difficulties. (If you are, please describe them.)
If you are looking for a visual effect (the row being highlighted), my guess is that your code is in another control's event and the focus is being set back to that control automatically the instant after your code runs. More than likely your code needs to be where it is and trying to move it elsewhere to prevent this issue would be a waste of time.
However, there are other ways to set a row apart visually. When a list view isn't likely to stay focused, my preferred method is to distinguish the selected item with a different fore/back color. (You can use the focused item if you prefer, but I find the selected item more useful. Your call.)
Here is an example which visually highlights the selected row, regardless of focus:
Private Sub lvw_SelectedIndexChanged(sender As Object, e As EventArgs) Handles lvw.SelectedIndexChanged
If lvw.Items Is Nothing Then Exit Sub
For Each lvi As ListViewItem In lvw.Items
If lvi.Selected = True Then
lvi.ForeColor = Color.DarkGray
lvi.BackColor = Color.LightCyan
Else
lvi.ForeColor = Color.Black
lvi.BackColor = Color.White
End If
Next
End Sub
EDIT:
In response to the added information that this form is being displayed using ShowDialog, yes, that is likely the source of your problem.
ShowDialog creates a new instance of the form. Therefore, if you have set any properties of a form or its controls, and later call ShowDialog to display that form, the form displayed is a new copy of the original form and will not reflect the changes you made programatically.
Imagine you sit down at a computer where a blank Word document is already open. You type something in it and then open a new document. The text you typed in the first document is not copied to the second. I think this is the root of your troubles here.

vb.net - redirect output to form textbox

I am trying to read/use the output from a python program in my vb.net project so far I'm not getting any results. What I'd like to see is the python program run (just by itself first) and all of the output get redirected into a textbox.
I've looked at some other posts about this, but I'm either missing something or not understanding something, as all I'm getting is blank output.
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim PythonPath = "C:\Python27\"
Dim strPath As String = Application.StartupPath
MessageBox.Show(PythonPath & "python.exe """ & strPath & "\Resources\import_logs.py"" ")
Dim start_info As New ProcessStartInfo(TextBox1.Text)
' Make the process and set its start information.
Dim process As New Process()
process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden
process.StartInfo.FileName = PythonPath & "\python.exe"
process.StartInfo.Arguments = """" & strPath & "\resources\import_logs.py"""""
process.StartInfo.UseShellExecute = False
process.StartInfo.CreateNoWindow = True
process.StartInfo.RedirectStandardOutput = True
'process.StartInfo.RedirectStandardError = True
AddHandler process.OutputDataReceived, AddressOf proccess_OutputDataReceived
process.Start()
process.BeginOutputReadLine()
End Sub
Public Sub proccess_OutputDataReceived(ByVal sender As Object, ByVal e As DataReceivedEventArgs)
On Error Resume Next
' output will be in string e.Data
' modify TextBox.Text here
'Server_Logs.Text = e.Data ` Does not display anything in textbox
MsgBox(e.Data) 'It works but I want output in text box field
End Sub
End Class
Eventually I'm going to pass arguments to the python script and I'd like to get feedback that I can then use (insert error into a database, email when it's done, etc), so I'd like it to capture the process while running and not just a data dump at the end.
Any help would be much appreciated.
First things first—it's no wonder you aren't sure what's wrong with your code, you're silencing all errors that could possibly help you to diagnose it. That's the only purpose of On Error Resume Next in VB.NET. That unstructured error handling was included only for backwards compatibility with the pre-.NET versions of VB and it's time to forget that it ever existed. You certainly don't want to use it in code. (I would say "in code that you're debugging", but all code is a potential candidate for debugging and ignoring errors is just dumb.)
Anyway, on to the specific problem. We know that the call to MsgBox works, but it doesn't work right when you start interacting with controls on your form. So something is falling apart there.
It turns out that the OutputDataReceived event is raised on an entirely different thread, a different one than was used to create the process and a different one than is running your application's UI. It actually just retrieves a thread from the system thread pool.
And that's where the problem lies: you cannot manipulate UI objects on a thread other than the one that created those objects (at least not without jumping through some hoops), which is precisely what your code tries to do here. In fact, you're probably swallowing an exception that would have rather obtusely informed you of this situation.
The simple fix is to set the SynchronizingObject property of the Process class to one of your UI components (like the form, or the specific control you want to output to). This forces all event handlers to execute on the same thread that created that component. At that point, your code should work fine, because you're not trying to do any cross-thread UI access. (Message boxes are not vulnerable to this because any thread can display a message box. You're not trying to access an existing UI object that is bound to another thread.)
Alternatively, you could handle the marshalling yourself in the event handler method through the use of delegates and the BeginInvoke method, but this seems like unnecessary work to me.

Using Visual Basic to Select a Google Search Result in Internet Explorer

I have VB code that goes to Google, fills in the search bar, and hits the search button. Is there a way to have my program select a particular result after my search? ie. I search for "cheese", I would like for my program to select the 2nd to last result (in this case, it is wwww.chuckecheese.com)
I ended up using Sendkeys to emulate the tab and down arrow keys on the keyboard. You can then navigate to your desired search results using these 2 keys
Or you can bypass using an API and avoid ads or cost using speech recognition to improve your Dictation searches. Programming isn't programming if you aren't thinking outside the box and innovating your own solutions.
Coding comes with creativity and you won't know what that is if you don't try. This site is excellent for this very purpose and many have contributed to innovation in coding.
You will have to add a text file to your project and call it whatever you want, then change the path below in the code to your own path. The text file stays blank. The program will write your spoken search to file and then execute the search, constantly over-writing itself.
For some odd reason, this method greatly improves the fusion of speech recognition and dictation. You can speak an entire phrase and it will conduct the search. A good mic is a must and speaking clearly without background disturbances.
Imports System.Speech.Recognition
'Declarations:
Private ReadOnly Drone As New SpeechRecognitionEngine()
Private ReadOnly Qa As New DictationGrammar()
Private Sub Form1_Load(sender As Object,
e As EventArgs) Handles MyBase.Load
'Dictation Mode | Google Engine
Drone.LoadGrammarAsync(Qa)
Drone.RequestRecognizerUpdate()
Drone.SetInputToDefaultAudioDevice()
Drone.InitialSilenceTimeout = TimeSpan.FromSeconds(2.5)
Drone.BabbleTimeout = TimeSpan.FromSeconds(1.5)
Drone.EndSilenceTimeout = TimeSpan.FromSeconds(1.2)
Drone.EndSilenceTimeoutAmbiguous = TimeSpan.FromSeconds(1.5)
AddHandler Drone.SpeechRecognized, AddressOf Drone_SpeechRecognized
Drone.RecognizeAsync(RecognizeMode.Multiple)
End Sub
Private Sub Drone_SpeechRecognized(sender As Object, e As SpeechRecognizedEventArgs)
Dim google As String = e.Result.Text.ToString
Select Case (google)
Case google
If google <> "+" Then
'This section will take spoken word, write to file then execute search.
Dim sb As New StringBuilder
'Be sure to change the text file path below to your path if you are new to this program.
sb.AppendLine(google)
'Add your own path below here. you can also change google to youtube and conduct youtube searches
File.WriteAllText("C:\Users\justin.ross\source\repos\ScarlettCenturium\Scarlett Centurium\Scarlett Centurium\File.txt", sb.ToString())
google = "https://www.google.com/search?q=" & Uri.EscapeUriString(google)
Dim proc As New Process()
Dim startInfo As New ProcessStartInfo(google)
proc.StartInfo = startInfo
proc.Start()
'This sendkey will close out previous tab on new search
SendKeys.Send($"^{{w}}")
Return
End If
End Select
End Sub
well you can use google api for that
goto http://code.google.com/p/google-api-for-dotnet/
download GoogleSearchAPI_0.4_alpha.zip
extract it and add reference to the dll file in your project ( in folder .net 2)
and you can use it like this
first import the library
Imports Google.API.Search
then in a sub or function put your code as
Dim rf As String = "http://www.google.com"
Dim v As New Google.API.Search.GwebSearchClient(rf)
Dim result = v.Search(TextBox1.Text, 40)
' number (40) is the amount of fetched results ( change it if you want )
For Each item In result
If item.Url.Contains("chuckecheese") Then
' your code goes here
End If
Next