Shoutbox

VB/Web Help - Printable Version

-Shoutbox (https://shoutbox.menthix.net)
+-- Forum: MsgHelp Archive (/forumdisplay.php?fid=58)
+--- Forum: Skype & Technology (/forumdisplay.php?fid=9)
+---- Forum: Tech Talk (/forumdisplay.php?fid=17)
+----- Thread: VB/Web Help (/showthread.php?tid=51361)

VB/Web Help by DragonX on 10-04-2005 at 07:11 AM

Ok, basically i'm makin an app that will take the string entered, convert it to a web adrs and then send that adrs to the default browser which will open that page. Now the thing i have no idea how to do is how to pass that adrs to the default browser.

Here's ascreenshot of it.
[Image: MiniSearch.jpg]

I was also wondering how to to get a keypress throught the txtBox

code:
Private Sub txtSearch_KeyPress(ByVal sender As Object, ByVal e As_
    System.Windows.Forms.KeyPressEventArgs)
        If key pressed is "return" Then
            call search
        End If
End Sub

Thx in advance for the help.
RE: VB/Web Help by rav0 on 10-04-2005 at 09:44 AM

I'm no coder, but AFAIK you pass the URI to the shell (or whatever). Same way you run an exe, but you give the URI instead of the path to the exe.


RE: VB/Web Help by brian on 10-04-2005 at 10:22 AM

http://www.vb-helper.com/howto_shellexecute.html


RE: VB/Web Help by CookieRevised on 10-04-2005 at 03:52 PM

quote:
Originally posted by DragonX
Ok, basically i'm makin an app that will take the string entered, convert it to a web adrs and then send that adrs to the default browser which will open that page. Now the thing i have no idea how to do is how to pass that adrs to the default browser.

Here's ascreenshot of it.
[Image: MiniSearch.jpg]

I was also wondering how to to get a keypress throught the txtBox
code:
Private Sub txtSearch_KeyPress(ByVal sender As Object, ByVal e As_
    System.Windows.Forms.KeyPressEventArgs)
        If key pressed is "return" Then
            call search
        End If
End Sub

Thx in advance for the help.
That isn't VB code! At first sight that is VB.NET code. VB.NET is not VB !!! Although they are similar, they are completely different languages...


---------


Anyways, for VB (not VB.NET, although it will be similar):

First tip: Don't call the search procedure inside that KeyPress event. You have a "search" button on your form for that. Use it... (otherwise you must write double code, one time in this textbox's KeyPress event and one time in the Click event of that button.)


Second tip: To open an URL you simply execute that URL like you execute any other program (aka you "Shell" it). The URL will then open in your default browser.

What brian linked to is how to use the Windows ShellExecute API to do this.

However, on that page there are a few things which aren't mentionned or are explaned not-so-correctly. eg: When you open a local HTML file, it will NOT be opened with your default browser! It will be opened with the associated program. This can be totally different than your default browser (eg: notepad). The default browser is only used when you have a command string which starts with the "http://" protocol string as it is your browser which is associated with that protocol and thus your browser is called to execute this 'command'. vb-helper is full of these kind of small, but important mistakes.

Also, to know how an API works, _never_ trust only on the explanation of such sites. Check and double check it in the msdn library instead! eg: on vb-helper they constantly speak of/use the handle of a window -hwnd- (as in the form's handle). This parameter can/must be null if you don't have a need for it. Don't set it to Me.hWnd as shown in the example if you want to open an URL as you most likely want the browser window to be independant of your program (aka: not setting it as a child window of your program). Again, this can be found in the msdn library...

Another note on this API and what is not said on vb-helper: If you pass strings in VB to Windows API's, the strings are converted to ANSI (=equivalent of ascii to keep it simple) and thus you can't pass unicode strings explicitly to API's (if you wanna do that you need to convert the unicode string first to unicode again, so VB converts the double unicode to normal unicode when it calls the API. Or, instead, you need to pass the pointer to the unicode string if you don't want to do that stupid unicode to unicode conversion.)

And again something they forget to mention, if you ant to use API's you first need to declare the API inside a module (note: a form is also a module. In fact, a form is a class module):
code:
Private Declare Function ShellExecute Lib "SHELL32" Alias "ShellExecuteA" (ByVal hWnd As Long, ByVal lpOperation As String, ByVal lpFile As String, ByVal lpParameters As String, ByVal lpDirectory As String, ByVal nShowCmd As Long) As Long



Third tip: The ASCII code for the <enter> key is 13 (this can be looked up in any ascii table on the net or in any book). Use the textbox's keypress event to catch this ascii key and then simulate a click on the search button:
code:
Private Sub Text1_KeyPress(KeyAscii As Integer)
    If KeyAscii = 13 Then
        Command1.Value = True
    End If
End Sub
It is only inside the Click event of the command button that you handle, test, create the full URL string and execute it. No need to do this inside the KeyPress event of the textbox (of course you could add a validation routine when the focus of the textbox is lost or something (=see 'Validate' event and 'CausesValidation' property of the textbox)).


-----------------

Thus:

code:
Private Declare Function ShellExecute Lib "SHELL32" Alias "ShellExecuteA" (ByVal hWnd As Long, ByVal lpOperation As String, ByVal lpFile As String, ByVal lpParameters As String, ByVal lpDirectory As String, ByVal nShowCmd As Long) As Long

Private Sub Text1_KeyPress(KeyAscii As Integer)
    If KeyAscii = 13 Then
        Command1.Value = True
    End If
End Sub

Private Sub Command1_Click()
    Dim URLString As String
    URLString = "http://www.google.com/search?q=" & Text1.Text 
    ShellExecute 0&, vbNullString, URLString, vbNullString, vbNullString, vbNormalNoFocus
End Sub
Note that this VB code does not check on the validity of the text entered in the textbox. eg: it doesn't convert the special characters to entities.

eg: the texbox input "testing" AND "trashing" will be wrongly parsed as
http://www.google.com/search?q="testing" AND "trashing"
instead of:
http://www.google.com/search?q=%22testing%22+AND+%22trashing%22
RE: VB/Web Help by Stigmata on 10-04-2005 at 04:14 PM

just improving on cookies code :)

code:
Private Declare Function ShellExecute Lib "SHELL32" Alias "ShellExecuteA" (ByVal hWnd As Long, ByVal lpOperation As String, ByVal lpFile As String, ByVal lpParameters As String, ByVal lpDirectory As String, ByVal nShowCmd As Long) As Long

Private Sub Command1_Click()
    Dim URLString As String
    URLString = "http://www.google.com/search?q=" & Encode(Text1.Text)
    ShellExecute 0&, vbNullString, URLString, vbNullString, vbNullString, vbNormalNoFocus
End Sub

Private Sub Text1_KeyPress(KeyAscii As Integer)
    If KeyAscii = 13 Then
        Command1_Click
    End If
End Sub

Public Function Encode(ByVal s As String) As String
    Dim sChar As String, sAsc As String, sHex As String, sName As String
    Dim I As Integer

    For I = 1 To Len(s)
        sChar = Mid$(s, I, 1)
        sAsc = Asc(sChar)
        If sAsc = 32 Then
            sHex = "+"
        Else
            sHex = sChar
        End If

        sName = sName & sHex
    Next I

    Encode = sName
End Function




i quickly made a encode function that checks for a space(ascii 32) and then replaces it with a +.

Works perfectly :)

(in vb... )
RE: VB/Web Help by CookieRevised on 10-04-2005 at 04:26 PM

this is totally as a sidenote:

Stigmata's extra encoding function is indeed what I meant with the extra checking/validating that needs to be done (although it misses many other special characters). Anyways, the Encode function as Stigmata posted it, can be made much more efficient and smaller ;)

1) to begin with loose the sAsc variable. Great for explanation, but it is only used once and directly in the IF THEN ELSE, so no need for that.
2) No need for getting the ascii value of the character and comparing it to 32, if you can directly compare the character itself to a space (although, this is some clock ticks slower, the code is much shorter)
3) No need to slowly build a new string again when you're only replacing individual characters. You can directly replace them in the original string.
4) Loose the ByVal. ByVal's are very slow compared to ByRef's (with a ByVal, VB needs to create another instance of the variable). To overcome writing over the original variable you can directly manipulate the function's output string.
5) Longs work faster than Integers (in this case) so declare I as a long...

So we get:

code:
Public Function Encode(s As String) As String
    Dim I As Long
    Encode = s
    For I = 1 To Len(Encode)
        If Mid$(Encode, I, 1) = " " Then
            Mid$(Encode, I, 1) = "+"
        End If
    Next I
End Function
But hey, isn't that simply replacing every space with a "+"? Well yes, so... simply use VB's Replace function:
code:
Replace(URLString, " ", "+")

PS: nevertheless, you must make an "Encode" routine anyways, to encode your text into the proper characters and "escape codes" (forgot the correct name for them) so you can use them in URLs...


:D ;)


EDIT: Mike, you're late :XP: hihi ;)

RE: VB/Web Help by Mike on 10-04-2005 at 04:29 PM

quote:
Originally posted by Stigmata

i quickly made a encode function that checks for a space(ascii 32) and then replaces it with a +.
You can easly do it with VB's Replace() function :)
code:
    Dim URLString As String
    URLString = "http://www.google.com/search?q=" & Replace$(Text1.Text, " ", "+")

;)

Edit: Bah, cookie beat me to it, as I was writing it... :P
But cookie's code is slower, because he didn't include an $ in his replace function, so VB thinks that it should be used as a variant :P
Strings are faster than variants, because, variants can be anything, so they use more memory :P (cookie, please correct me on this one :P)
RE: RE: VB/Web Help by CookieRevised on 10-04-2005 at 04:49 PM

quote:
Originally posted by Mike
But cookie's code is slower, because he didn't include an $ in his replace function, so VB thinks that it should be used as a variant :P
Strings are faster than variants, because, variants can be anything, so they use more memory :P (cookie, please correct me on this one :P)
You're absolutely correct. In my haste I forgot the $...
RE: VB/Web Help by DragonX on 10-04-2005 at 07:48 PM

:D Thx so much to all, u guys are the best!! :D

And yes, that is VB.NET.

quote:
Originally posted by CookieRevised
code:
Command1.Value = True

Becomes
code:
cmdSearch.PerformClick()

In .NET ;) (i think)

quote:
Originally posted by CookieRevised
code:
Dim URLString As String
        URLString = "http://www.google.com/search?q=" & Replace$(Text1.Text, " ", "+")

What is the $ used for? I've never used it in a replace() before.

quote:
Originally posted by CookieRevised
code:
Private Declare Function ShellExecute Lib "SHELL32" Alias "ShellExecuteA" (ByVal hWnd As Long, ByVal lpOperation As String, ByVal lpFile As String, ByVal lpParameters As String, ByVal lpDirectory As String, ByVal nShowCmd As Long) As Long

Must i use the API ? Did it that way anyways, for now ;)

code:
ShellExecute(0&, vbNullString, URLString, vbNullString, vbNullString, vbNormalNoFocus)

Converted in .NET

What is '0&' for ?
RE: VB/Web Help by DragonX on 10-04-2005 at 07:52 PM

Sorry for the double post, just thought it would be better this way

Ok, so here is my code

code:
Public Class miniSearch
    Inherits System.Windows.Forms.Form
    Private URLString As String
    Private Declare Function ShellExecute Lib "SHELL32" Alias "ShellExecuteA" (ByVal hWnd As Long, ByVal lpOperation As String, ByVal lpFile As String, ByVal lpParameters As String, ByVal lpDirectory As String, ByVal nShowCmd As Long) As Long

    Private Sub txtSearch_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtSearch.Click
        If txtSearch.Text = "Enter search words here" Then
            txtSearch.Text = ""
        End If
    End Sub

    Private Sub txtSearch_KeyPress(ByVal KeyAscii As Integer)
        If KeyAscii = 13 Then
            cmdSearch.PerformClick()
        ElseIf KeyAscii = 27 Then
            End
        End If
    End Sub

    Private Sub cmdSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdSearch.Click
        URLString = "http://www.google.ca/search?q=" & Replace$(txtSearch.Text, " ", "+")
        ShellExecute(0&, vbNullString, URLString, vbNullString, vbNullString, vbNormalNoFocus)
        MsgBox(URLString)
        End
    End Sub
End Class


First off, the "cmdSearch.PerformClick()" doesn't work, in fact the whole KeyPress part doesnt' work. I tried sending my KeyPress into a msgBox and that doesn't even work, could it be because i don't ahve a hangle on it ? :S

Edit: OK, i tried with a handle "Handles txtSearch.KeyPress" and i get this error: "Method 'txtSearch_KeyPress' cannot handle Event 'KeyPress' because they do not have the same signature."

Edit2: Alright, after some digging, i found out the KeyPress was redefined in .NET. And to make it work, u need code that looks like this
code:
Private Sub txtSearch_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtSearch.KeyPress
        Dim KeyAscii As Integer

        KeyAscii = AscW(e.KeyChar)     <-- This is the code to make it work

        If KeyAscii = 13 Then
            cmdSearch.PerformClick()
        ElseIf KeyAscii = 27 Then
            End
        End If
    End Sub

So that thing is solved :)

And second, it doesn't the launch my browser. Maybe i just overlooked something *-)
Edit: Woohoo, i got it wo work :) by bypassing the API too ;) Here's how i did it
code:
System.Diagnostics.Process.Start(URLString)

Well all works now :D Once it'll all finalized and what not i'll post it here, if anyone wants it ;)
RE: VB/Web Help by Ezra on 10-05-2005 at 02:28 PM

quote:
Originally posted by DragonX
code:
System.Diagnostics.Process.Start(URLString)


I just thought about that :P, you were quicker :D
RE: RE: VB/Web Help by CookieRevised on 10-05-2005 at 03:33 PM

quote:
Originally posted by DragonX
What is the $ used for? I've never used it in a replace() before.
Almost every intristic string function in VB (note again: I'm talking about VB, not VB.NET!! It might be different in VB.NET) has two possible ways of use.
1) Firstly (and this is the one mostly used because people don't know any better) most of such functions are able to return a Variant data type.
2) Second, it can directly return a String data type.

Now... A Variant is a special kind of VB data type. It can actually hold all types of data types. In some cases, and used properly at given times, this can be very handy. But mostly, this just slows down your application _and_ is also the cause of many "hidden" errors in applications.

It is much slower because VB constantly needs to check what actual data type the variant is holding and it constantly needs to convert from variant to that data type in calculations, procedures, etc. The variant also uses extra memory (as it needs to hold extra information to identify the actual data type). Furthermore, a variant data type which is holding a number, actually has two data types assigned to it: firstly the number data type (can be integer, long, whatever) and second a string representing that number. Again extra memory and more slowness...

Important: If you have the bad habbit of not declaring variables, VB doesn't know what type you exactly are going to use in your program for that variable and thus reverts back to a variant data type.

The next code is perfect legal in VB:
code:
A = "Hello world"
MsgBox A
A = 1234
MsgBox A
First you assign a string to the variable A, next you assign a number. Since you didn't declare the variable A and thus didn't told VB what data type it is going to be, VB makes it a variant. And thus, that's why that code is valid.... but dead slow...
code:
Dim A As String
A = "Hello world"
MsgBox A
A = 1234
MsgBox A
This will result in an error on the line 'A = 1234' because you explicitly declared variable A as a String. A string can't be a number...

Now that you know what a Variant is and why you should avoid it at all costs, we come to those intristic string functions like Left(), Right(), Mid(), Format(), etc...

As said they have the possebility to return a Variant or directly return a String data type. If you attach $ (the symbol for a String data type) to the function's name, VB knows it should return a String instead of the default Variant data type.

The benefit is that VB doesn't need to convert the Variant (which it returns by default) to a String in calculations, procedures, assignments, etc...

Consider the next code:
code:
Dim A As String
Dim B As String
A = Mid("Hello World", 7, 1)
B = Mid$("Hello World", 7, 1)
VB performs the next things in the A assignment:
1) create the string "Hello World" in memory
2) jump to the 7th character and copy 1 character from that point on
3) create a new variant data type in memory and assign the previous 1 character string to it
4) try to convert that string to a numerical value and assign that also to the variant in memory
5) convert the variant data type to a string data type again
6) assign that new string to the string variable A

VB performs the next things in the B assignment:
1) create the string "Hello World" in memory
2) jump to the 7th character and copy 1 character from that point on
x) create a new variant data type in memory and assign the previous 1 character string to it
x) try to convert that string to a numerical value and assign that also to the variant in memory
x) convert the variant data type to a string data type again
3) assign that new string to the string variable A


This said, I just found out that the string function Replace() will actually always return a string, wether you use $ or not. At least that is what the syntax help tells me. I need to look deeper into this though, as I find this rather curious... So Mike, for now, you were actually wrong :p (and me too for saying you were totally correct :p)

-----------------------------------------

quote:
Originally posted by DragonX
quote:
Originally posted by CookieRevised
code:
Private Declare Function ShellExecute Lib "SHELL32" Alias "ShellExecuteA" (ByVal hWnd As Long, ByVal lpOperation As String, ByVal lpFile As String, ByVal lpParameters As String, ByVal lpDirectory As String, ByVal nShowCmd As Long) As Long

Must i use the API ? Did it that way anyways, for now ;)
In VB (again, I'm not speaking about VB.NET), yes... VB also knows a Shell() function, but this is a very simplified version of the ShellExecute API and can only run real executables or associations. It can't run protocols like "http://"...

quote:
Originally posted by DragonX
code:
ShellExecute(0&, vbNullString, URLString, vbNullString, vbNullString, vbNormalNoFocus)
What is '0&' for ?
As I explaned in the previous post, when you call the ShellExecute API the first parameter is the handle to the window which will be the parent of the process you're going to start. If you set this parameter the process you're going to start is going to be a child process. In normal use of this API (to start some programs for example), this isn't needed and can even be not wanted. This means you must set this handle parameter to NULL (NULL = not used/nothing/not applicable/no valid data). But VB doesn't know the constant NULL (at least not for this purpose! Important: Do not use vbNull for this!!!!!!! vbNull is _not_ NULL, it is a constant to indicate a variant with no valid data and will actually return the value 1!!!!). In fact what is NULL? NULL is zero, so we set that parameter to 0. The & at the end is the sign for the Long data type. Again, so VB doesn't need to convert the Variant 0 to the Long data type but directly makes it a Long instead.

quote:
Originally posted by DragonX
Edit2: Alright, after some digging, i found out the KeyPress was redefined in .NET. And to make it work, u need code that looks like this[/code]Well, you asked for VB help, you got VB help :p not VB.NET help. Those two languages are different, as you just experienced ;)

quote:
Originally posted by DragonX
code:
(...)
ElseIf KeyAscii = 27 Then
    End
End If

Ohooooh.... Aiaiai... this is an oh-so-frequent error to make... Although it works, try to avoid crashing against the wall to stop the car!!! In plain English :p: do not use the End statement! 'End' immediatly stops your application without the decent cleaning up. This can cause serious errors like memory leaks, crashing, freezes and what not, if you don't know exactly what you're doing and you're using 'advanced' stuff as classes and objects... Instead, UNLOAD your main form _after_ you unloaded all your other (child) forms and have cleared all the used objects and have cleared all the used classes... This clearing up can best be done in the Unload event of a form. And to end your application, simply call/execute the unload event by unloading the main form.

As long as you don't use any asyncronical functions like DoEvents(), you actually do not need to use the End statement at all!!! And in most cases DoEvents is also something which can be avoided and is often a sign of a bad programming scheme. In case you do use DoEvents and thus the End statement, you must know exactly what you're doing. Golden rule: avoid DoEvents, End, (and variants) at all costs...

quote:
Originally posted by DragonX
And second, it doesn't the launch my browser. Maybe i just overlooked something *-)
The example of the ShellExecute API is for VB only, not for VB.NET. In VB.NET the syntax to declare API's is much different.

quote:
Originally posted by DragonX
Edit: Woohoo, i got it wo work :) by bypassing the API too ;) Here's how i did it
code:
System.Diagnostics.Process.Start(URLString)


As you noticed, there are many major differences in VB and VB.NET. VB doesn't know a method to 'execute' an URL, VB.NET does apparently (so indeed, no need for the API there)... (PS: this is indeed the benefit of looking things up by yourself, in the end you'll learn a lot more that way (y)(y))

PS: but the general tips I gave in my previous post (and in this post about variants vs. strings and about the End statemant) are also valid for VB.NET...

RE: VB/Web Help by YottabyteWizard on 10-05-2005 at 04:15 PM

OMG you guys sure know a lot of VB. I can't isntall VB.NET in this computer, maybe the prob is I've Media Center :O


RE: VB/Web Help by segosa on 10-05-2005 at 07:19 PM

Not trying to catch you out or anything CookieRevised, but you said using the 'End' statement which ends your application can cause memory leaks. I thought memory leaks are things which occurr only while your program is running?

YottabyteWIzard: Media Center is just XP afaik, so I don't think that's the reason.


RE: VB/Web Help by Ezra on 10-05-2005 at 07:23 PM

How do you use the unload statement with VB.NET? I can't find anything about it on MSDN


RE: VB/Web Help by YottabyteWizard on 10-05-2005 at 08:08 PM

quote:
Originally posted by segosa
YottabyteWIzard: Media Center is just XP afaik, so I don't think that's the reason.
I know that, but it's my only theory because i reinstalled Media Center and still can't install VB.NET, and when i had XP Pro SP2 and i can. Ideas?
RE: VB/Web Help by DragonX on 10-05-2005 at 09:00 PM

quote:
Originally posted by Ezra
ause serious errors like memory leaks, crashing, freezes and what not, if you don't know exactly what you're doing and you're using 'advanced' stuff as classes and objects...

Here ya go:
code:
Me.Close()

Funny thing is i knew that, i just dunno y i didn't use it lol

quote:
Originally posted by CookieRevised
Golden rule: avoid DoEvents
Do u mean like
code:
Do
i += 1
Loop While (i < 10)


quote:
Originally posted by YottabyteWIzard
I know that, but it's my only theory because i reinstalled Media Center and still can't install VB.NET, and when i had XP Pro SP2 and i can. Ideas?
Do you have the dvd version or the cd version ? Can u atleast launch the install ?

--------

Last thing, is there a way to catch a glodal click, like in Java ? Basically what i wanna do is if the user clicks anywhere in the form (which has only an image and labels) i want it to do a me.Hide().

Thx again for all the help, u guys are the best!! :D
RE: RE: VB/Web Help by CookieRevised on 10-05-2005 at 09:48 PM

quote:
Originally posted by segosa
Not trying to catch you out or anything CookieRevised, but you said using the 'End' statement which ends your application can cause memory leaks. I thought memory leaks are things which occurr only while your program is running?
Indeed, but in some cases VB doesn't clean up everything correctly when you force quit the app, usually it results in a crash though.

quote:
Originally posted by DragonX
quote:
Originally posted by CookieRevised
Golden rule: avoid DoEvents
Do u mean like
code:
Do
i += 1
Loop While (i < 10)

No, DoEvents is a special function/stamement in VB to prospone the execution and to let other processes in the same thread perform its events. Again this is VB, dunno if this also exists in VB.NET, but I do think so (maybe under a different name though)...
RE: VB/Web Help by YottabyteWizard on 10-06-2005 at 04:44 AM

quote:
Originally posted by DragonX
Do you have the dvd version or the cd version ? Can u atleast launch the install ?
I had CD version, and now i have DVD version and still the same problem, i can install though the end but when finishing the installation keep poping out errors.... by the Registry part, not quite sure, i'll try to reintall again tomorrow and post on another thred my problem with screenies and keep out of this thred with another problem.