VB.NET - GetWindowText() returns ZERO for "edit" class - vb.net

I am trying to retreive text from another application by app's control handle. I have no problem if control is "static" but my code seems not working for "edit" control. As MSDN says, GetWindowText cannot retreive text from EDIT control but maybe you know another way of achieving this?
My current code is here:
Dim newHwnd As IntPtr = Handler.GetClassByPosition(ParentHwnd, cls, classPosition)
Dim length As Integer = Handler.GetWindowTextLength(newHwnd)
Dim sb As New String(" ".Chars(0), length + 1)
If cls = "edit" Then
Handler.GetWindowText(newHwnd, sb, sb.Length)
End If
where GetClassByPosition returns control's handle by specifying parent handle, class name (static,edit or button) and classPosition (used in loop - not important for now)
As I said, it works great with STATIC (labels etc) but it returns 0 if I'm retreiving text from EDIT (textbox) control of that external application.
UPDATE:
I have tried the following solution which success in returning data if data is integer but if it contains any letter, result is 0:
Dim tmpstr As IntPtr = Marshal.AllocHGlobal(100)
Dim NumText = API.SendMessage(Hwnd, API.WM_GETTEXT, 200, tmpstr )
NumText = Marshal.PtrToStringAnsi(tmpstr )
Return NumText
Thanks in advance,
Nikola

try this:
Private Function GetText(ByVal hWnd As IntPtr) As String
Dim ReturnValue As String = Nothing
If hWnd.ToInt32 > 0 Then
Dim Length As Integer = GetWindowTextLength(hWnd)
If Length > 0 Then
Dim sb As New System.Text.StringBuilder("", Length + 1)
GetWindowText(hWnd, sb, sb.Capacity)
ReturnValue = sb.ToString
sb = Nothing
End If
End If
Return ReturnValue
End Function

Related

VB.NET - Randomize() with a function call in a string.replace method

I have a chat system and i want to put a "random string generator".
In my chat i have to write "%random%" and it is replaces with a random string.
I have a problem though, if i type "%random%%random%%random%" for example, it will generate the same string 3 times.
• Here is my function:
Public Function getRandomString(ByVal len As Integer) As String
Randomize()
Dim stringMap as string = "abcdefghijklmnopqrstuwvxyz0123456789"
Dim rndString As String = ""
Dim rnd As New Random()
For i As Integer = 0 To len - 1
Randomize()
rndString &= stringMap.Substring(rnd.Next(0, stringMap.Length), 1)
Next
Return rndString
End Function
• And here is my function call:
Dim msg As String = "Random string: %random%%random%%random%"
msg = msg.Replace("%random%", getRandomString(8))
MsgBox(msg)
The output for example: Random string: 5z15if725z15if725z15if72
I guess this is because it keeps the 1st return value in memory and pastes it, how can i fix that ?
Do i have to make a string.replace function myself ? Thanks
Oh no! You shouldn't call Randomize() here at all! Random is used in combination with the Rnd() function of VB. Creating a new Random object is enough here.
The reason you are getting the same results every time is because you are creating a new Random every time. You should reuse the same object to get different results.
'Create the object once
Private Shared rnd As New Random()
Public Function getRandomString(ByVal len As Integer) As String
Dim stringMap as string = "abcdefghijklmnopqrstuwvxyz0123456789"
Dim rndString As String = ""
For i As Integer = 0 To len - 1
rndString &= stringMap.Substring(rnd.Next(0, stringMap.Length), 1)
Next
Return rndString
End Function
EDIT: I realize that in addition to the above changes, you need to call the getRandomString function for every "%random%". String.Replace only calls the function once and pastes the result everywhere. With Regex, you could do something like this:
msg = new Regex("%random%").Replace(input, Function (match) getRandomString(8))
An easy way to do it is to find the first occurrence of "%random%", replace that, then repeat as necessary.
Written as a console application:
Option Infer On
Module Module1
Dim rand As New Random
Public Function getRandomString(ByVal len As Integer) As String
Dim stringMap As String = "abcdefghijklmnopqrstuwvxyz0123456789"
Dim rndString As String = ""
For i As Integer = 0 To len - 1
rndString &= stringMap.Substring(rand.Next(0, stringMap.Length), 1)
Next
Return rndString
End Function
Function ReplaceRandoms(s As String) As String
Dim stringToReplace = "%random%"
Dim r = s.IndexOf(stringToReplace)
While r >= 0
s = s.Remove(r, stringToReplace.Length).Insert(r, getRandomString(stringToReplace.Length))
r = s.IndexOf(stringToReplace)
End While
Return s
End Function
Sub Main()
Dim msg As String = "Random string: %random%%random%%random%"
msg = ReplaceRandoms(msg)
Console.WriteLine(msg)
Console.ReadLine()
End Sub
End Module

How to convert a string to a vb expression which includes control name in it

.. eg: have a stri ng
strResult="controlName1.value * controlName2.value"
.. I need to change it to just controlName1.value * controlName2.value so that i can get the output as double value
Please reply
Thanks
If you're using Windows Forms, there is an indexer property that accepts the name of a sub-control as a string and returns the control if a match is found. See: Control.ControlCollection.Item Property (String).aspx
The straightforward alternative in all UI frameworks is to map Strings to Controls like such:
Function MapStringToControl(ctlName As String) As Control
Select Case ctlName
Case "controlName1"
Return controlName1
Case "controlName2"
Return controlName2
Case Else
Return Nothing
End Function
Of course note that there is no .Value property in Windows Forms--you need to do something like Integer.Parse(ctl.Text).
It depends what type of control it is. For example a textbox has a .Text property. A NumericUpDown control has a .Value property.
All you need to do is to convert the appropriate property to the appropriate type. So for TextBoxes:
Dim result as Double = CDbl(txtFoo.Text) * CDbl(txtBar.Text)
For a NumericUpDown:
Dim result as Double = CDbl(nudFoo.Value) * CDbl(numBar.Value)
Hi guys thanks for your updates.. I wrote my own function by using your concepts and some other code snippets .I am posting the result
Function generate(ByVal alg As String, ByVal intRow As Integer) As String
Dim algSplit As String() = alg.Split(" "c)
For index As Int32 = 0 To algSplit.Length - 1
'algSplit(index) = algSplit(index).Replace("#"c, "Number")
If algSplit(index).Contains("[") Then
Dim i As Integer = algSplit(index).IndexOf("[")
Dim f As String = algSplit(index).Substring(i + 1, algSplit(index).IndexOf("]", i + 1) - i - 1)
Dim grdCell As Infragistics.Win.UltraWinGrid.UltraGridCell = dgExcelEstimate.Rows(intRow).Cells(f)
Dim dblVal As Double = grdCell.Value
algSplit(index) = dblVal
End If
Next
Dim result As String = String.Join("", algSplit)
'Dim dblRes As Double = Convert.ToDouble(result)
Return result
End Function
Thanks again every one.. expecting same in future

Count occurance of specific words in a text file in vb.net

I'm trying to count the number of an item in a text file, by counting each instance the item was entered into the file earlier on in the program.
I already have the text read from the file and in a text box. The problem is that my current code was just counting the characters in the textbox and not the number of times my desired word was in the file.
For Each desiredword As String In txtContentofFile.Text
intdesiredword = intdesiredword + 1
txtdesiredwordcount.Text = intdesiredword
Next
This counts the characters in the textbox instead of counting the number of desired words. I tried repeatedly before asking help and searched extensively, but I just don't understand what's wrong with my code. Please help :)
You can use Split Function :
C#:
int count = txtContentofFile.Text.Split(desiredword).Length - 1;
VB.net:
Dim count As Integer = txtContentofFile.Text.Split(desiredword).Length - 1
I prefer to use Regular Expressions in this type of situation. They are very tricky to understand but they are extremely powerful and typically faster than other string manipulation techniques.
Dim AllMatchResults As MatchCollection
Try
Dim RegexObj As New Regex(desiredword)
AllMatchResults = RegexObj.Matches(txtContentofFile.Text)
If AllMatchResults.Count > 0 Then
' Access individual matches using AllMatchResults.Item[]
Else
' Match attempt failed
End If
Catch ex As ArgumentException
'Syntax error in the regular expression
End Try
In your case you are looking for the value from AllMatchResults.Count.
Using a great Regular Expression tool like RegexBuddy to build and test the expressions is a great help too. (The above code snippet was generated by RegexBuddy!)
Try this:
Dim text As String = IO.File.ReadAllText("C:\file.txt")
Dim wordsToSearch() As String = New String() {"Hello", "World", "foo"}
Dim words As New List(Of String)()
Dim findings As Dictionary(Of String, List(Of Integer))
'Dividing into words
words.AddRange(text.Split(New String() {" ", Environment.NewLine()}, StringSplitOptions.RemoveEmptyEntries))
findings = SearchWords(words, wordsToSearch)
Console.WriteLine("Number of 'foo': " & findings("foo").Count)
Function used:
Private Function SearchWords(ByVal allWords As List(Of String), ByVal wordsToSearch() As String) As Dictionary(Of String, List(Of Integer))
Dim dResult As New Dictionary(Of String, List(Of Integer))()
Dim i As Integer = 0
For Each s As String In wordsToSearch
dResult.Add(s, New List(Of Integer))
While i >= 0 AndAlso i < allWords.Count
i = allWords.IndexOf(s, i)
If i >= 0 Then dResult(s).Add(i)
i += 1
End While
Next
Return dResult
End Function
You will have not only the number of occurances, but the index positions in the file, grouped easily in a Dictionary.
Try the following code
Function word_frequency(word_ As String, input As String) As Integer
Dim ct = 0
Try
Dim wLEN = word_.Length
Do While input.IndexOf(word_) <> -1
Dim idx = input.IndexOf(word_) + wLEN
ct += 1
input = input.Substring(idx)
Loop
Catch ex As Exception
End Try
Return ct
End Function

How can I make this function not generate a "doesn't return a value on all paths" warning?

I realize this is a very specific question, and not very helpful outside of this scenario, although I am sure it applies to other questions with the same problem. I have a function to recursively search through windows (and their child windows) to find specific ones, it works exactly as expected, however it causes "function doesn't return a value on all paths" warning. This is the only warning in my entire program, and although it might be silly, I'm interested in knowing if there is a way to stop this error from occurring, but still allowing the function to work properly.
Public Function FindQWidgetWindows() As Integer
Dim hWndStart As Integer = 0
Dim WindowText As String = "*"
Dim Classname As String = "QWidget"
Dim hwnd As Integer
Dim sWindowText As String
Dim sClassname As String
Dim r As Integer
Static level As Integer
If level = 0 Then
If hWndStart = 0 Then hWndStart = GetDesktopWindow()
End If
level = level + 1
hwnd = GetWindow(hWndStart, GW_CHILD)
Do Until hwnd = 0
Call FindQWidgetWindows()
'Get the window text and class name'
sWindowText = Space$(255)
r = GetWindowText(hwnd, sWindowText, 255)
sWindowText = Microsoft.VisualBasic.Left(sWindowText, r)
sClassname = Space$(255)
r = GetClassName(hwnd, sClassname, 255)
sClassname = Microsoft.VisualBasic.Left(sClassname, r)
If (sWindowText Like WindowText) And (sClassname Like Classname) Then
Dim aRECT As RECT
Dim hwndInt As Int32 = hwnd
GetWindowRect(hwndInt, aRECT)
FindQWidgetWindows = hwnd
'uncommenting the next line causes the routine to'
'only return the first matching window.'
'Exit Do'
End If
hwnd = GetWindow(hwnd, GW_HWNDNEXT)
Loop
level = level - 1
End Function
You rely on the fact, that VB automatically declares a return variable with the name of your function. This variable can be used as any other variable in your function. So it also can get a default initialization.
As already mentioned, you only assign a value in a very nested If statement.
You should simply initialize your variable outside and before of your Do-loop with something like
FindQWidgetWindows = Nothing
Yes, you can get rid of this error by ensuring every path returns a value.
This can be done by simply initialising the return value at the top of the function:
FindQWidgetWindows = Nothing
But you have another problem that you're probably not seeing because your desired window is at the top level. If you recurse into your function, the hWndStart will once again be set to the desktop, not the child window.
In your code the below code will be executed only if the If condition is satisfied.
FindQWidgetWindows = hwnd
Which also means if the If condition is not satisfied nothing will be returned.
You have declared the function (Public Function FindQWidgetWindows() As Integer) as returning a integer but the function doesn't return anything. Just ensure that you return an integer using the Return statement.

How to retrieve just unread emails using pop3?

I'm using open source component to retrieve emails from my mail server using vb.net (pop3)
but because i have a lot of messages it gives me response Time out and i think if i just got the new messages it will make reading faster.
this is my code:
Dim popp As New Pop3Client("user#mail.com", "*******", "pop3.mail.com")
popp.AuthenticateMode = Pop3AuthenticateMode.Pop
popp.Port = 110
'popp.Ssl = True
popp.Authenticate()
Dim msglist As New List(Of String)
If popp.State = Pop3ConnectionState.Authenticated Then
Dim totalmsgs As Integer = popp.GetTotalMessageCount()
If totalmsgs > 0 Then
For index As Integer = 1 To totalmsgs
Dim msg As Pop3Message = popp.GetMessage(index)
msglist.Add(msg.Subject)
Next
popp.Close()
End If
End If
Return msglist
please i need some help if i'm using the component in a wrong way or if there is another component do what i'm looking for.
b.s. : my component name is "Higuchi.Mail.dll" or "OpenPOP.dll" and the two are same.
thanks
POP3 does not have the capibility to track whether messages are read or unread. I would suggest you set your limit to a finite number such as 50 or 100. Perhaps you could do some sort of pagination system.
This code needs to be within a function so that you can call it like so:
Sub Main
Dim start As Integer = Integer.parse(Request.QueryString("start"))
Dim count As Integer = Integer.parse(Request.QueryString("count"))
Dim subjects As New List(Of String)
subjects = getSubjects(start, count)
'Do whatever with the results...
'
End Sub
Function getSubjects(ByVal startItem As Integer, ByVal endItem as Integer) As List(Of String)
Dim popp As New Pop3Client("user#mail.com", "*******", "pop3.mail.com")
popp.AuthenticateMode = Pop3AuthenticateMode.Pop
popp.Port = 110
popp.Authenticate()
Dim msglist As New List(Of String)
If popp.State = Pop3ConnectionState.Authenticated Then
Dim totalmsgs As Integer = popp.GetTotalMessageCount()
Dim endItem As Integer = countItems + startItem
If endItem > totalmsgs Then
endItem = totalmsgs
End If
If totalmsgs > 0 Then
For index As Integer = startItem To endItem
Dim msg As Pop3Message = popp.GetMessage(index)
msglist.Add(msg.Subject)
Next
popp.Close()
End If
End If
Return msglist
End Function
Just have the program change the value for startItem to 50 get the next fifty (items 50-100)
POP3 protocol does not have the notion of seen/unseen messages.
Can't you use IMAP?
It would give you more features (like searching, flagging, folder management) than POP3.