Invoke Click Cefsharp VB - vb.net

I would like to simulate a click or keypresses to a web browser element that is on my visual studio vb project.
I have found ways to do it for the webbrowser object built-in to visual studio, but I am using the cefsharp browser, so
weBrowser.Document.GetElementById('id').InvokeMember("Click") would not work, because cefsharp doesn't allow .Document. So my question, to reiterate, is, how would I use vb to simulate a click on my cefsharp webbrowser? Any help is appreciated, and have a nice day.
EDIT: I've been working on this code:
Dim elementID As String = "myBtn"
Dim click As String = "Click"
browser.ExecuteScriptAsync("Document.All(elementID).InvokeMember(click)")
but I am not sure if it will work or how to use the elementID part (I am not sure what kind of web elements can go here). Maybe this extra information will help.

Using ExecuteScriptAsync will execute JavaScript against the Chrome engine, so you would have to send valid JavaScript to this function. The following code shows how you could start a search using DuckDuckGo
Imports System.Threading
Imports CefSharp
Imports CefSharp.WinForms
Public Class Form1
Private _browser As New ChromiumWebBrowser()
Sub New()
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
_browser.Top = 10
_browser.Left = 10
_browser.Width = 600
_browser.Height = 400
Controls.Add(_browser)
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
_browser.Load("https://duckduckgo.com/")
'for simplicity just wait until page is downloaded, should be handled by LoadingStateChanged
Thread.Sleep(3000)
Dim jsScript As String = <js><![CDATA[
document.all("q").value = "stack overflow";
document.all("search_button_homepage").click();
]]></js>.Value
_browser.ExecuteScriptAsync(jsScript)
End Sub
End Class

Related

Is there a way to input a text from textbox1.text to input box of a website? I'm using a chromium browser in Visual Basic

I'm trying to make a program in which I can input my username from my Visual basic project Textbox1 to facebook input box username. I'm using chromium from CefSharp for webbrowser. I got the id through 'view page source' which is 'email'. but what I'm not sure if my line of code is correct.
Here are my code so far:
Imports CefSharp
Imports CefSharp.Web
Imports CefSharp.JavascriptBinding
Imports CefSharp.Event
Public Class Form2
Private WithEvents browser As ChromiumWebBrowser
Sub New()
InitializeComponent()
InitializeChromium()
End Sub
Private Sub InitializeChromium()
Dim settings As New CefSettings()
CefSharp.Cef.Initialize(settings)
Dim browser As New ChromiumWebBrowser("https://www.facebook.com")
Panel1.Controls.Add(browser)
browser.Dock = DockStyle.Fill
End Sub
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
browser.ExecuteScriptAsync("document.getElementById('email').value='ansdew#gmail.com'")
End Sub
When I run this, I get the error message
Object reference not set to an instance of an object.'
The line of code which this exception
browser.ExecuteScriptAsync("document.getElementById('email').value='ansdew#gmail.com'")
I don't know if the inside of this
ExecuteScriptAsync
is correct and I need to find the correct script so I can input my username/email using my VB project.
Let me know also if I need to include some lines of code.
Thanks!

vb.net Parameters Startup Form not hiding?

I am creating a application to be used with a touch panel device. The touch panel device comes with a standard windows OSK (On screen Keyboard). Whilst testing its been concluded that the standard OSK is to large and too complex for what we need it in. So I have built my own OSK. some of the feilds though only requier numeric inputs so I though of futher simplifying the process by creating a new form which hosts a numeric pad. so far this is all working. the idea is then to have the app which ask for diffrent inputs then to trigger the OSK application, say that the user wants to enter a phonenumber in one textbox I then want to start the OSK app using a parameter that trigers the OSK to start the NumericForm form first... this too I have working but the thing I can't get right is to hide the AlphabetForm I have tried the following method but am a little stumpt on how to get this right
In short its the Me.hide which isnt working as expected?
Private Sub AlphabetForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
#Region "Recive startup parameters (if any)"
Try
Dim OSKParameters As String = Command()
If OSKParameters = "OSKNUM" Then
NumericForm.Show()
Me.Hide()
Else
ShiftSelect = 0
End If
Catch ex As Exception
'Do nothing
End Try
#End Region
End Sub
Three possible setups, as described in comments:
► Using the Application Framework, override OnStartup and set Application.MainForm to a Form object determined by a command-line argument:
To generate ApplicationEvents.vb, where Partial Friend Class MyApplication is found, open the Project properties, Application pane, click the View Application Events Button: it will add the ApplicationEvents.vb file to the Project if it's not already there.
Imports Microsoft.VisualBasic.ApplicationServices
Partial Friend Class MyApplication
'[...]
Protected Overrides Function OnStartup(e As StartupEventArgs) As Boolean
Application.MainForm = If(e.CommandLine.Any(
Function(cmd) cmd.Equals("OSKNUM")), CType(NumericForm, Form), AlphabetForm)
Return MyBase.OnStartup(e)
End Function
'[...]
End Class
► Disabling Application Framework, to start the Application from Sub Main().
In the Project->Properties->Application pane, deselect Enable application framework and select Sub Main() from the Startup form dropdown.
If Sub Main() doesn't exist yet, it can be added to a Module file. Here, the Module is named Program.vb.
Module Program
Public Sub Main(args As String())
Application.EnableVisualStyles()
Application.SetCompatibleTextRenderingDefault(True)
Dim startForm as Form = If(args.Any(
Function(arg) arg.Equals("OSKNUM")), CType(New NumericForm(), Form), New AlphabetForm())
Application.Run(startForm)
End Sub
End Module
► If the OSK can be moved to UserControls, similar to what jmcilhinney suggested, run the default container Form and select the UserControl to show using the same logic (inspecting the command-line arguments):
Public Class AlphabetForm
Public Sub New()
InitializeComponent()
Dim args = My.Application.CommandLineArgs
Dim uc = If(args.Any(
Function(arg) arg.Equals("OSKNUM")), CType(New NumericUC(), UserControl), New AlphabetUC())
Me.Controls.Add(uc)
uc.BringToFront()
uc.Dock = DockStyle.Fill
End Sub
End Class

Wait for internet explorer to load everything?

I am scraping a webpage, and waiting for internet explorer to get done loading but for some reason it is not. I'm trying to get a value on the page but the wait part is not waiting therefore the value comes back blank when there should be a value. The IE page has done loading but the value for the elements on the page has not been loaded yet. Is there a way to wait for all elements to get done loading before proceeding to next line of code? Here's my code:
Dim IE As Object
Dim myvalue as string
IE = CreateObject("internetexplorer.application")
IE.navigate("mypage")
While Not IE.ReadyState = WebBrowserReadyState.Complete
Application.DoEvents()
End While
myValue = IE.document.getElementById("theValue").getAttribute("value")
Debug.Print(myValue)
You SHOULD NOT use Application.DoEvents() in order to keep your UI responsive! I really can't stress this enough! More than often using it is a bad hack which only creates more problems than it solves.
For more information please refer to: Keeping your UI Responsive and the Dangers of Application.DoEvents.
The correct way is to use the InternetExplorer.DocumentComplete event, which is raised when the page (or a sub-part of it, such an an iframe) is completely loaded. Here's a brief example of how you can use it:
Right-click your project in the Solution Explorer and press Add Reference...
Go to the COM tab, find the reference called Microsoft Internet Controls and press OK.
Import the SHDocVw namespace to the file where you are going to use this, and create a class-level WithEvents variable of type InternetExplorer so that you can subscribe to the event with the Handles clause.
And voila!
Imports SHDocVw
Public Class Form1
Dim WithEvents IE As New InternetExplorer
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
IE.Navigate("http://www.google.com/")
End Sub
Private Sub IE_DocumentComplete(pDisp As Object, ByRef URL As Object) Handles IE.DocumentComplete
MessageBox.Show("Successfully navigated to: " & URL.ToString())
End Sub
End Class
Alternatively you can also subscribe to the event in-line using a lambda expression:
Imports SHDocVw
Public Class Form1
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim IE As New InternetExplorer
IE.Navigate("http://www.google.com/")
AddHandler IE.DocumentComplete, Sub(pDisp As Object, ByRef URL As Object)
MessageBox.Show("Successfully navigated to: " & URL.ToString())
End Sub
End Sub
End Class

How to Open console in VB

I currently have a console application by using the setting illustrated in the image bellow. However Now I wish to open multiple forms with the console so I'm wondering if I can somehow open multiple forms or open the console within a Windows Forms Application
#tinstaafl can you share this extra programming or a link to a
solution. Thanks
Here's a couple of links:
Console and WinForm together for easy debugging
Console Enhancements
Here's a conversion of the first one. You'll need a form with a checkbox name "CheckBox1":
Imports System.Runtime.InteropServices
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub CheckBox1_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBox1.CheckedChanged
If CheckBox1.Checked Then
Win32.AllocConsole()
Console.WriteLine("Done!")
Else
Win32.FreeConsole()
End If
End Sub
End Class
Public Class Win32
<DllImport("kernel32.dll")> Public Shared Function AllocConsole() As Boolean
End Function
<DllImport("kernel32.dll")> Public Shared Function FreeConsole() As Boolean
End Function
End Class
Everytime you click the checkbox you show or hide the console. You can write to and read from the same as any console app.
Forms and Console applications are very different. So much so that generally speaking a process either needs to be a form or console application. Forms applications are implemented with a message pump and console applications are command line drive. It is possible to a degree to run a form within a console, and vice versa, but generally not recommended. If you truly need both I would highly encourage you to use 2 processes.
If you could elaborate a bit more on your use case we may be better able to help you out.
So this is very cool. In the designer just add a checkbox using the Toolbox common controls.
Then double click on the new "CheckBox1" and that will automatically insert this sub routine:
Private Sub CheckBox1_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CheckBox1.CheckedChanged
End Sub
Then all you have to do is add this code:
If CheckBox1.Checked Then
Win32.AllocConsole()
Console.WriteLine("Done!")
Else
Win32.FreeConsole()
End If
When you run your windows form program and check the box it will automatically open the window and KEEP it open until you uncheck the box.
Add this class to the bottom of your program:
Public Class Win32
<DllImport("kernel32.dll")> Public Shared Function AllocConsole() As Boolean
End Function
<DllImport("kernel32.dll")> Public Shared Function FreeConsole() As Boolean
End Function
End Class
And be sure to add the Imports statement at the top
Imports System.Runtime.InteropServices
If you want to open a console window to interact with and when you close the console, that action won't terminate your windows program then you can add these two lines of code:
Dim myProcess As Process
myProcess = Process.Start("cmd.exe")

Visual Basic - Web browser load URLs from text

i am not so great with Visual basic, but i need some help on creating a web browser that would load several links import from a text file, and for the web browser to navigate to them. This is what i have so far
Dim link As String = OpenFileDialog2.FileName
Dim links As String = IO.File.ReadAllText(link)
MsgBox(links)
WebBrowser1.Navigate(links)
You help means a lot. Thank You.
The WebBrowser Control either will show the webpage in the Control which will limit you to one page, or you can tell it to open the pages in separate windows which will open an Internet Explorer window for each link. I also used the File.ReadAllLines Method in order to get an array of the Links so that you can iterate through the Web Pages . This works for me but might not be what you are wanting.
Public Class Form1
Dim wb As New WebBrowser
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim filename As String = "C:\temp\links.txt"
Dim links As String() = IO.File.ReadAllLines(filename)
For Each link As String In links
wb.Navigate(link, True)
Next
End Sub
Public Sub New()
InitializeComponent()
Controls.Add(wb)
wb.Dock = DockStyle.Fill
End Sub
End Class
My text file called Links.txt looks like this:
www.google.com
www.msdn.com
www.bing.com