Home | Index | Dotnet4all Snippets | Submit resources
About | Mail us 





System.OutOfMemoryException when showing form (Saturday, August 28, 2004)

Found the following interesting discussion in the Newsgroups:

System.OutOfMemoryException when showing form
by:Baz

Hi.

I'm new to this VB.Net mullarkey, and I must say it is proving to be a very
trying experience. Here is the latest in a long line of problems:

The Scenario
=========

I am building an MDI application. The first thing it does is to pop up a
little logon form which gathers and authenticates an SQL Server
username/password. It then whacks these into a couple of global variables
so they are available for any subsequent database access. Here are the
declarations of those variables (they are simply in a regular module):

Friend gstrUserName As String
Friend gstrPassword As String

Now, I have another form which is launched from a menu on the mdi parent.
Here is the code which does that:

Private Sub mnuCountries_Click(ByVal sender As Object, ByVal e As
System.EventArgs) Handles mnuCountries.Click

Dim frmCountry As New frmCountry

frmCountry.MdiParent = Me
frmCountry.Show()

End Sub

BUT, one of the first things frmCountry does is to grab itself a middle-tier
object (a class) so as to populate the lists in some combo boxes, and in
order to do this it needs to pass in the SQL Server credentials mentioned
above i.e. it needs to refer to the two global variables. Hence, I have a
Form Load event procedure as follows (where cfrMain is a user control I have
created which has the combo boxes on it):

Private Sub frmCountry_Load(ByVal sender As Object, ByVal e As
System.EventArgs) Handles MyBase.Load

Dim objCountries As New midCountry

With objCountries
.UserName = gstrUserName
.Password = gstrPassword
End With
cfrMain.DataSource = objCountries

End Sub

Please feel free to criticise/comment on the general approach I have adopted
here, or any specifics in these code snippets (I am, after all, trying to
learn). However, the particular problem I have is that the statement
frmCountry.Show() throws a System.OutOfMemoryException error. HOWEVER, and
here's the weird bit, if I comment out the following two statements in
frmCountry_Load, then frmCountry shows OK:

.UserName = gstrUserName
.Password = gstrPassword

frmCountry also shows OK if I replace the references to the global variables
with literals e.g.

.UserName = "myuser"
.Password = "mypassword"

It also shows OK if it's not a child form.

So what's going on here? Why does something as apparently trivial as
referencing a couple of global variables result in an out-of-memory error?
And what can I do about it? And should I give up on the mdi application (a
trawl through Google groups shows a LOT of out-of-memory problems when
showing a child form, but no answers that I can find)?

Thanks for listening!

Baz


 Reply:
by:Charles Law

 Hi Baz

The first thing I noticed was that you define a variable with the same name
as a class. Whilst not forbidden, I would personally avoid this as it can
cause no end of problems when referencing the instance.

I would be inclined to change your click handler to something like

<code>
Private Sub mnuCountries_Click(ByVal sender As Object, ByVal e As
System.EventArgs) Handles mnuCountries.Click

Dim frm As New frmCountry

frm.MdiParent = Me
frm.Show()

End Sub
</code>

then there is no confusion regarding which object is being referenced. This
may even resolve your problem.

HTH



 Reply:
by:Baz

 Thx for the reply Charles. Good point about the naming.

I have changed the design so that UserName and Password, instead of being
properties of the middle tier object, are instead arguments of it's methods.
This involved moving the code that references the global variables, so that
it is now done by the user control, cfrMain, rather than in the Load event
of the form. It still gets done when the form loads, but it's a couple of
calls further down the stack, as it were. And...the problem went away.

Seems to be (yet another) bug in .Net. A few days ago I wasted a couple of
hours discovering the unreliability of setting the SelectedIndex for a bound
combo box to -1. Is programming in VB.Net always this frustrating?

Baz




Posted by Xander Zelders
0 Comments



Listview and context menu question

Found the following interesting discussion in the Newsgroups:

Listview and context menu question
by:Sameh Ahmed

Hello there
i have a context menu linmked to a listview control.
I want the context mnu to appear ONLY when i right click on an item and not
any place in listview.
any ideas?
Thanks in advance.
PS: i want the same with treeviews
Regards
Sameh


 Reply:
by:Brian Henry

 I do it by checking the selecteditems.count property of the listview.. but I
am sure there are better ways of doing it

if selecteditems.count > 0
' show menu
end if

or if you have multi select on and want right click on only one selected

if selected items.count = 1
' show menu
end if

just an idea


 Reply:
by:Sameh Ahmed

 Thanks for ur time
this is what i use
but the context menu appears even if u right click on a different item
i don't want it to appear when u select an item then move in an empty space


 Reply:
by:sawhar@hotmail-dot-com.no-spam.invalid (carmen)

 Sameh,

You can include an If ....Else statement to check whether there is any
selected item in your list view. If no item is selected, then set the
visible property of your context menu item(s) to false.

Carmen


 Reply:
by:sawhar@hotmail-dot-com.no-spam.invalid (carmen)

 example:

Private Sub ListView1_SelectedIndexChanged(ByVal sender As
System.Object, ByVal e As System.EventArgs) Handles
ListView1.SelectedIndexChanged
ControlContextMnu()
End Sub

Protected Overrides Sub OnLoad(ByVal e As System.EventArgs)
ControlContextMnu()
End Sub

Private Sub ControlContextMnu()
Dim ctmtem As MenuItem
If Me.ListView1.SelectedItems.Count = 0 Then
For Each mnuitem In ContextMenu1.MenuItems
mnuitem.Visible = False
Next
Else
For Each mnuitem In ContextMenu1.MenuItems
mnuitem.Visible = True
Next
End If
End Sub



Posted by Xander Zelders
0 Comments



How to use GetFiles

Found the following interesting discussion in the Newsgroups:

How to use GetFiles
by:yxq

Hi,
I only can get one file type using GetFiles function,

GetFiles(path, "*.txt")

But if i want to get two or more file types, how to do?

Thanks


 Reply:
by:yEaH rIgHt

 
Dim str() as String

str = GetFiles(path, "*.*")

For i = 0 to str.Length -1

If Path.GetExtension(str(i)) = ".txt" or Path.GetExtension(str(i)) = ".doc" then
'--- Do whatever
End if

Next


 Reply:
by:Phill. W

 

Imports System.IO
.. . .
For Each eFile As String In Directory.GetFiles(path, "*.*")
Select Case Path.GetExtension(eFile).ToLower()
Case ".doc", ".txt"
' Do Something
End Select
Next

HTH,
Phill W.


 Reply:
by:yxq

 Thank you



Posted by Xander Zelders
0 Comments



Custom treeview question

Found the following interesting discussion in the Newsgroups:

custom treeview question
by:WStoreyII

Is there a way to add a custom control to a tree view? or the node itself? Like in the datagrid column you can add a control during the edit mode. I looked but could not find a way to do this does anyone have any ideas?

WStoreyII


 Reply:
by:Ken Tucker [MVP]

 Hi,

http://www.thecodeproject.com/vb/net/vbnettreelistview.asp

Ken



Posted by Xander Zelders
0 Comments



Error Using Webbrowser Control on Form

Found the following interesting discussion in the Newsgroups:

Error Using Webbrowser Control on Form
by:Selden McCabe

I'm trying to display some HTML on a form in a VB.Net project. I've referenced the COM WebBrowser control, and put an instance of it on my form.

But during the Form_Load, I'm getting the following error:

The code generator inserted the following line of code in the form (wbReport is the name of the WebBrowser control)

CType(Me.wbReport, System.ComponentModel.ISupportInitialize).EndInit()

When the form gets loaded, this line of code generates a InteropServices.ComException ("Unknown Error").

This is driving me crazy, since I downloaded a simple example of using the WebBrowser in VB.Net, and it works without this error.

A couple of points:
The webbrowser control is hosted on a Tab control, which is on a form that is an MDI Child.
Could either of these be the culprit?

How can I display HTML on a form in VB.Net?

Thanks!
---Selden McCabe



 Reply:
by:Charles Law

 Hi Selden

It does that! I have exactly the same scenario and it has always done it to me too. It is not a fatal error though, so your app should continue.

You will also get the same non-fatal exception when you call AxWebBrowser1.Navigate(...)

I am interested in the sample you downloaded that does not have this problem. Can you post a link as I would like to see what it does differently, and then perhaps I can solve this little conundrum for both of us.

Charles


 Reply:
by:Selden McCabe

 The sample I found that works fine without these errors can be found at:
www.lcss.net/vbnet/vbnet.htm

From reading the newsgroups suggested in this thread, it appears that the answer may be to create a user control that contains a WebBrowser control, and use methods to add it to the form (controls.add) and remove it at the appropriate times.

If I get this working, I'll post the results here.

Thanks, everyone, for your replies!

---Selden McCabe


 Reply:
by:Cor

 Hi Selden

There is not any problem using the axwebbrowser on a normal form, the problem is with a MDI form, the sample I saw is in my opinion with a normal form.

Cor


 Reply:
by:Charles Law

 Hi Selden

I wouldn't hold your breath regarding user controls. My application has the WebBrowser control on a user control which is then placed on a tab control which then goes on a windows mdi child form, and I get this problem. But good luck ...

Charles


 Reply:
by:Cor

 Hi Selden

That is I think a known problem with MDI, see the messages in this newsgroup for this.

http://tinyurl.com/ywy7o

I hope this helps?

Cor



Posted by Xander Zelders
2 Comments



Regular Expressions

Found the following interesting discussion in the Newsgroups:

Regular Expressions
by:masoodadnan@hotmail.com (Sehboo)

Hi,

I have several regular expressions that I need to run against documents. Is it possible to combine several expressions in one expression in Regex object. So that it is faster, or will I have to use all the expressions seperately?

Here are my regular expressions that check for valid email address and link


Dim Expression As String =
"([\w\-]+\.)*[\w\-]+@([\w\-]+\.)+([\w\-]{2,5})"
EmailRegex = New Regex(Expression, RegexOptions.IgnoreCase _
Or RegexOptions.Compiled)

Dim HrefPattern As String =
"href\s*=\s*(?:""(?<match>[^""]*)""|(?<match>\S+))"
HrefRegex = New Regex(HrefPattern, RegexOptions.IgnoreCase _
Or RegexOptions.Compiled)

so can I combine both regular expressions in one?

Thanks


 Reply:
by:Jay B. Harlow [MVP - Outlook]

 Sehboo,
Using Alternation you can combine regular expressions.

Dim regex As New Regex(Expression & "|" & HrefPattern,
RegexOptions.IgnoreCase Or
> RegexOptions.Compiled)

You may want to also use a grouping construct with a name so you know which expression you matched...

Also you may want to use Match & NextMatch to walk the matches found, however I do not have a good example of this...
I find both of the following sites invaluable when working with regular expressions.

A tutorial & reference on using regular expressions:
http://www.regular-expressions.info/

The MSDN's documentation on regular expressions:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpgenref/html/cpconRegularExpressionsLanguageElements.asp

Hope this helps
Jay



Posted by Xander Zelders
0 Comments



forms Control collections

Found the following interesting discussion in the Newsgroups:

forms Control collections
by:VJ

I have a bunch of controls in my Form. Is there a way to locate a control by using its name? , something like in ASP where they use Controls.FindControl(string name). I know using ForEach to loop through and locate a control is a option, but that seems to be slow when I have like 40
controls on a form.

Thanks
VJ


 Reply:
by:Klaus Löffelmann

 VJ,

it shouldn't be slow for "only" 40 controls. Try starting the program with "start without debugging" (don't know the exact caption of the menue entry in the "debug" menue, since I use the German version), and see how the speed turns out then.

Klaus


 Reply:
by:VJ

  I am testing in Release build.. I was just saying 40 Controls for a example.. But we actually don't know the run-time controls numbers.. my test case was about 40 controls.. and it took about 20sec to find the control, and I am on P-4 512 Dell Laptop.. Is this normal?


 Reply:
by:Klaus Löffelmann

 VJ,

don't mix up start (also as "release build") and "start without debugging". The release build in the vs dev environment is still debuggable (even if only with the disassembler), and therefore slower. If you start without debugging, how fast (or slow) is it then? Could you also post some code to see, if we can speed things up there? What is the time, when you run the program on its own (without the environment)? By the way: Are you catching and possible exception in the loop? If so, then you should really try to run the program in not-debug-mode, since exceptions, while running the program in the environment, take about 15 seconds to come up - no matter if you catch them, or not.

Klaus

PS: It's already half one, here, so I will only come back to you in the morning (GMT+1).


 Reply:
by:Cor

 Hi VJ,

> I am testing in Release build.. I was just saying 40 Controls for a
> example.. But we actually don't know the run-time controls numbers.. my
test
> case was about 40 controls.. and it took about 20sec to find the control,
> and I am on P-4 512 Dell Laptop.. Is this normal?

No, if you want us to help you, show than some code you are using.

Cor



Posted by Xander Zelders
0 Comments



Jump Menu (DropDown Menu) in ASP.net.

Found the following interesting discussion in the Newsgroups:

Jump Menu (DropDown Menu) in ASP.net. Can someone help me out?
by:Miguel Dias Moura

Hello,

i have a drop down menu in ASP.net with 5 options. I want to redirect to a certain page when a certain option is selected.
I want to be redirected without having to click a button. Does anyone know how to make this?

Thank You,
Miguel


 Reply:
by:Cor

 Hi Miguel,
The four from webcontrol derived listControls from which the dropdownmenu is one have an autopostback property that has to be set to true for this.

I hope this helps?

Cor





Posted by Xander Zelders
0 Comments



Shutdown / Restart

Found the following interesting discussion in the Newsgroups:

Shutdown / Restart
by:Fabio

How Can I ShutDown and Restart the system with VB.net

Anyone have a example???

Thanks in advance,
Fabio


 Reply:
by:Ken Tucker [MVP]

 Hi,

http://www.mentalis.org/soft/class.qpx?id=7

Ken



Posted by Xander Zelders
0 Comments



Printing in .NET

Found the following interesting discussion in the Newsgroups:

Print
by:=?Utf-8?B?V2lsbA==?=

Hey guys,

i have 2 PC (called PC1, PC2). The printer is connected to PC1 and i want to be able to print from PC2 since the printer is shared. I've tried :
PrintDocument1.PrinterSettings.PrinterName = "\\PC1\iDP3210" .. but did not work .. any suggestions ?

NEED CODE PLEASE
THANX IN ADVANCE



 Reply:
by:CJ Taylor

 Yeah, dumb question, but it is shared properly isn't it?


 Reply:
by:CJ Taylor

 Last thing...

try this to see what printers are availible.

For i = 0 To Printing.PrinterSettings.InstalledPrinters.Count - 1

Debug.Writeline(Printing.PrinterSettings.InstalledPrinters()(i))

Next


 Reply:
by:strchild

  Hey, was trying to figure out if any printers were installed on a
computer or not, and voila, ran across your reply here.

Just wanted to write in and say thanks, CJ, and the rest of you guys!
Your vast plethora of knowledge is much appreciated, even if you aren't
thanked enough.

Keep up the great work,
Brian



Posted by Xander Zelders
0 Comments



VB.Net Output

Found the following interesting discussion in the Newsgroups:

VB.Net Output
by:erios

I have seen discussions about outputting from VB.NET in different formats. My question, is it possible to output say a report in .pdf format and if so, how do I go about it.
Thanks..


 Reply:
by:William Ryan eMVP

 There are some third party tools that will do it directly and Crystal Reports for instance has that functionality build into it. I've heard good things about Dynamic PDF but haven't used it. The other alternative is to write a driver but that's not going to be fun...



Posted by Xander Zelders
0 Comments



How to load an object's property which is an array list

Found the following interesting discussion in the Newsgroups:

How to load an object's property which is an array list?
by:Derek Martin

I have an object which I set up like this:


Public Class Person
....
Protected m_timelists as ArrayList
....
Property timelists() as ArrayList
Get
timelists = m_timelists
End Get
Set (ByVal Value as ArrayList)
m_timelists = Value
End Set
End Property


Is this legal and valid??? If yes, keep going:
Now I want to set it with some objects:


'Time object is previously created and valid
PersonList.addtimeobject(myUserid, time)

Public Class PersonList
'To hold all the person objects
Dim personlist as new ArrayList
....
Public Function addtimeobject(ByVal userid _
as string, ByVal time as object)
Dim i as integer = 0
For i = 0 to personlist.count-1
if personlist(i).userid = userid then
personlist(i).timelists.add(time)
end if
Next
End Function


Error returned: Object variable or With block variable not set. This is
occurring on the timelists Arraylist Property Get and Set areas.

Can someone assist???? Thanks!


 Reply:
by:Armin Zingler

 

In the example you never assign anything to the timelists property,
so m_timelists is still Nothing and you get...

> Error returned: Object variable or With block variable not set.
> This is occurring on the timelists Arraylist Property Get and Set
> areas.

.... this error.


Declare
Protected m_timelists as NEW ArrayList


or assign an arraylist to the timelists property.
--
Armin



 Reply:
by:Derek Martin

 AHHHHHHHH - many many thanks, wonderful and thanks again!

Derek



Posted by Xander Zelders
0 Comments



System.Diagnostics.Debug

Found the following interesting discussion in the Newsgroups:

System.Diagnostics.Debug
by:Mike

In my Smart Device Project, I'm trying to show a message only when debugging. We used to be able to do this with Debug.Print in VB 6. I've tried System.Diagnostics.Debug.WriteLine and this doesn't seem to do anything - I can't see it writing anywhere.

I also tried Debug.Assert and Debug.Fail and both of these do show the message on the Pocket PC device, but then when I click on Continue or Debug at the bottom of the message on the device, I get a NullReferenceException in Visual Studio.

Can someone explain what is going on here?


 Reply:
by:Ken Tucker [MVP]

 Hi,

Debug.writeline will send it output to the ide's output window when the application in running in debug mode.

Ken
--------------


 Reply:
by:Mike

 It's not. Has anyone tried Debug.WriteLine in a Smart Device project?


 Reply:
by:jimmyzh@online.microsoft.com (Jimmy Zhu)

 Hi Mike,

The initial release of the Visual Studio.NET debugger for the .NET Compact Framework does not implement this feature. However, you can define your own listener classes within your application to handle the debug messages.

Jimmy Zhu


 Reply:
by:Mike

 Thanks.



Posted by Xander Zelders
0 Comments



How to select columns in DataGrid

Found the following interesting discussion in the Newsgroups:

How to select columns in DataGrid?
by:Terry Olsen

I've got my datgrid loaded (finally). I can select rows & delete them.
But I can't select columns to delete them. When I click on a column header, all that happens is the grid is resorted by that column. How can I change it so I can select the column to delete it?

Thanks!


 Reply:
by:Cor

 Hi Terry,

You cannot, the only thing that could be done is that you delete (disable) a columnstyle from your datagridstyles. However because of that the datagrid is only the view on the screen of table(s). that means not that the column is actualy deleted, but that it is only not shown.

I hope this makes it a little bit clear?

Cor



Posted by Xander Zelders
0 Comments



Listview and label display

Found the following interesting discussion in the Newsgroups:

listview and label display
by:Anonymous

Hello,
I have a listview that displays a list of choices.
When the mouse moves over each item, I would like text (the name of the item that is being hovered over) to show up in a seperate label or textbox.
How do I set this?
Thanks,
Amber


 Reply:
by:Simon Jefferies

 Hello,

Create a MouseMove event on the listview in question,

Inside this event place the following code:


Dim SelectedItem As ListViewItem _
= lvwFiles.GetItemAt(e.X, e.Y)
If Not SelectedItem Is Nothing Then
MyLabel.Text = SelectedItem.Text
End If


This snippet of code will retrieve the list view item at the position of the mouse and if a valid item was found set a label's text to the text of the item. Change MyLabel to the name of your label etc.

Hope this helps
Cheers
Simon

--
Simon Jefferies
Tools Programmer, Headfirst Productions
mailto:simonj@headfirst.co.uk
-


 Reply:
by:Anonymous

 Thank You!!
It worked great!




Posted by Xander Zelders
0 Comments



Listbox problem

Found the following interesting discussion in the Newsgroups:

Listbox problem
by:=?Utf-8?B?YW1iZXI=?=

Hello,
I'm not sure if I should give up trying to find an answer here...or just keep posting my problem...

I'm having problems with a listbox...
I have a listbox that is populated when a user presses a button (retrieve). There is a textbox on the form, and if the textbox is left blank, and the user presses the button, all records show in the listbox. If the user enters a specific item into the textbox, then presses the button, only that record shows in the listbox. There are fields on the form which are populated by data associated with what is selected in the listbox.
All this works great...my problem is this:
The first time 'retrieve' is clicked, it works great, but then, if something else is entered into the textbox, or it is cleared to retrieve all records, when the button is clicked, the listbox doesn't display it's contents.
The data is there...all fields on the form are filled in correctly, and you can even click on the list box to change what is selected, you just can't see anything in the list box....
I'm baffled.
I'm pasting my code below.
Sorry this is so lengthy! Thanks in advance!!
Amber


Private Sub butRetrieve_Click(ByVal sender As _
System.Object, ByVal e As System.EventArgs) _
Handles butRetrieve.Click

If txtCPMain.Text <> "" Then
get_specific_CP()
Else
get_all_CPs()
End If
End Sub

**

Sub get_specific_CP()
lBoxCP.DataSource = Nothing
lBoxCP.Items.Clear()
lBoxCP.Refresh()
DsCP1.Clear()
SqlDA_CP.Fill(DsCP1)
Dim dtbCP As DataTable
dtbCP = DsCP1.Tables(0)
Dim dtvCP As New DataView(dtbCP)
dtvCP.RowFilter = "STR_CUTTING_PERMIT = _
'" & txtCPMain.Text & "'"
lBoxCP.DataSource = dtvCP
lBoxCP.DisplayMember = "STR_CUTTING_PERMIT"
fill_all_textfields()
End Sub

**

Private Sub get_all_CPs()
lBoxCP.DataSource = Nothing
lBoxCP.Items.Clear()
lBoxCP.Refresh()
DsCP1.Clear()
SqlDA_CP.Fill(DsCP1)
lBoxCP.DataSource = DsCP1.Tables(0)
lBoxCP.DisplayMember = "STR_CUTTING_PERMIT"
End Sub




 Reply:
by:CJ Taylor

 are you sure your row filter is working correctly? the only thing I could see is that yoru dataview isn't working, can you check to see that it has row values.

-CJ


 Reply:
by:Anonymous

 Thanks for the reply CJ.
Yes, the filter is working properly. All the correct data is shown...it's just that the items in the listbox are not visible...
I've been baffled by this for a while...and I'm not sure what to do.
I've tried starting all over again...no luck.
Amber



Posted by Xander Zelders
6 Comments



Passing a DLL vs. Reinstantiating it

Found the following interesting discussion in the Newsgroups:

Passing a DLL vs. Reinstantiating it
by:Tom

I have a main VB.NET program which instantiates a number of other VB.NET DLLs. This DLLs all use routines from a 'base' DLL (which contains a number of common routines); so currently I reinstantiate that 'base' DLL in every one of my called DLLs.

The question is: Would it be better if I instantiated the 'base' DLL in the main program, then passed a reference of the 'base' to each of my other DLLs? Or is .NET smart enough to use same copy of the 'base' DLL when it gets instantiated in each of my DLLs? (in other words, even though the same 'base' DLL is instantiated many times in different DLLs, VB.NET keeps only one copy in memory of the 'base' DLL and they all share that copy).

Just wondering if going through the work of passing a reference to my 'base' DLL is worth it.... Thanks.

Tom


 Reply:
by:Marina

 Of course not. All the instances are different. Each one might have different properties set, etc, and that woudl make it behave differently. If all instances of the same class, were actually just one instance internally, then nothing would ever work. Imagine having 2 string variables - but then somehow internally, .NET would treat them as one? How would that work?

If the methods in your class don't depend on class state, and just on the arguments to each of the methods, then you can make them all Shared. This means you call the method through the class name itself, as opposed to through an instance of that class. That means that no instance of the class is ever instantiated, and you are not wasting resources by creating objects that don't really need to be there.



Posted by Xander Zelders
0 Comments



NetworkStream .Write() method not completing

Found the following interesting discussion in the Newsgroups:

NetworkStream .Write() method not completing
by:jeremyh@bdssc.com (JeremyH)

I'm trying to create a simple, synchronous TCP client program to receive requests and return data. My code very closely resembles the example code provided in the Help files, but I find that the .Write method - when run at full speed - only seems to successfully write data the first time it is called.

For testing purposes, I am using Hyperterminal on another computer to send 4 characters. The program always successfully reads all 4 characters. It is then supposed to reverse them and send the reversed byte array back. Here is the code:


Private tcpLstn As New TcpListener(51112)

Public Sub subMainLoop()
Dim tcpClnt As TcpClient
Dim ns As NetworkStream
Dim buffr(4) As Byte
Dim buffr2(6) As Byte
Dim iRead As Integer

bScan = True
tcpLstn.Start()

While bScan
'--- Code execution pauses here
'--- until TCP connection request
'--- is received.
tcpClnt = tcpLstn.AcceptTcpClient()

ns = tcpClnt.GetStream()

'--- Wait until 4 characters are successfully read
iRead = 0
While iRead < 4
iRead = iRead + ns.Read(buffr, iRead, 4 - iRead)
End While

'--- Create array of characters to send back
buffr2(0) = 13
buffr2(1) = 10
buffr2(2) = buffr(3)
buffr2(3) = buffr(2)
buffr2(4) = buffr(1)
buffr2(5) = buffr(0)

Try
'--- Send requested data over TCP port
ns.Write(buffr2, 0, 6)
ns.Close()
tcpClnt.Close()
Catch e As Exception
Console.WriteLine(e.ToString())
End Try

'--- Process events
Application.DoEvents()
End While

tcpLstn.Stop()

End Sub


When stepping through in debug mode, the ns.Write(buffr2, 0, 6) command works about 95% of the time, and the returned characters are displayed in HyperTerminal. When running the program with no breaks and no MsgBox calls in the main loop, the program only successfully writes back the 4 characters (plus {LF}{CR}) the first time. From HyperTerminal (and other testing methods) I can tell that the 4 characters I send ARE, in fact, being read by the program EVERY time. The response simply isn't coming through.

Ultimately, the program is only ever going to be communicating with one other computer. So there isn't any need for multi-threading or asynchronous reading/writing.

Am I missing something, though?


 Reply:
by:Anonymous

 I can't believe that in this day in age there are still inherent timing issues/bugs in released development classes. This is RETARDED!!!

The problem, it turns out, is that the NetworkStream .Write() method returns IMMEDIATELY. It does NOT wait until the data has actually been sent. Microsoft claims that it returns after making sure the data was added to the STREAM. This may be the case. However, there is no guarantee that the stream has actually been sent before closing the connection.

My code reads like this:


....
ns.Write(buffr2, 0, 6)
ns.Close()
tcpClnt.Close()
....


Problem was: ns.Close() and tcpClnt.Close() were getting called before the data stream was actually sent - i.e. the underlying socket got closed before completing pending data transmissions. The code is/will be running on a P4 1.8GHz+ processor. The fix was to put in a manual loop delay (which any decent program should NEVER have to resort to) right after the ns.Write() command. This is a sucky solution, but the only one that works.


....
ns.Write(buffr2, 0, 6)
For i = 1 to 1000000
i = i
Next
ns.Close()
tcpClnt.Close()
....


I tried enabling tcpClnt.LingerState, setting tcpClnt.NoDelay = True, raising the tcpClnt.LingerTime, making sure the .SendBuffer was set low since I am only sending 6 bytes at a time - but none of those things made any difference. THE ONLY WAY to avoid the timing limitation on sending data is to create a manual delay or have other code executing before calling the .Close() methods.

Someone needs to put this in a book/article somewhere!




Posted by Xander Zelders
3 Comments



VB Calling a C or C++ Function?

Found the following interesting discussion in the Newsgroups:

VB Calling a C or C++ Function?
by:Anonymous

I have written an Extensive test application in VB and long and detailed Algorithm that the application stresses and tests. The problem is that now that I have the algorithm perfected, I had to re-write it in C++. And since the algorithm, which is a function accepting three values (byval) and returning one, is going to be used in an embedded application I need to test the C function to same degree that I have tested the VB function before I release it.

How do I call a C or C++ function in VB.NET? Doesn't the .NET frame work make this easier without having to write a complicated COM wrapper?
Randy
Randy.york@baesystems


 Reply:
by:yEaH rIgHt

 Is this function in a dll? If so, use Platform Invoke.


 Reply:
by:Anonymous

 No, its a seperte .cpp file.


 Reply:
by:yEaH rIgHt

 It must be put in a dll if you eant to use it.


 Reply:
by:Brian Henry

 a cpp file is an uncompiled file, along with .h header files.. you must compile them first into a windows dynamic link library (DLL) then you can use them by doing PInvoke DLLImport calls in your vb.net application



Posted by Xander Zelders
0 Comments



Getting Information From the Browser...

Found the following interesting discussion in the Newsgroups:

Getting Information From the Browser...
by:Kris Rockwell

Hello,

I have been searching for a few items with little success. I am hoping somebody here can answer my questions...

1. Is it possible to get the title (<title> </title>) of a web page through the axwebbrowser control? Essentially I would like my application to grab the title and save it as a variable.

2. This may not be the correct group for this, but I amgoing to give it a shot...Using a Web Form I have placed a button component on a page (<asp:button>). I would like to use the button to direct the user to a new page. Is it possible to control the actions of this button with Javascript and, if not, can I do so using the CodeBehind? What methods/properties would I access?

Any help with this would be greatly appreciated.

Regards,
Kris


 Reply:
by:Cor

 Hi Kris,

Have a look for mshtml. It is in the normal Net reference box. If you are familiar with javascript it should be very familiar to you because it uses the Document Object Model just as javascript.

Do not set a import but reference direct to it because it has so many interfaces that your IDE slows down to nothing if you set an import.

Try and when you do not succeed using it, message back because I do not have the code I use direct as sample but spread over a lot of different classes. I hope this helps,

Cor



Posted by Xander Zelders
0 Comments



How to use VB.NET to access the "IE history folder in XP"?

Found the following interesting discussion in the Newsgroups:

how to use vb to access the "IE history folder in XP"?
by:nick cheng

I want use vb to write a program. it is used to record the "IE history", i am using WinXP,when i try to access the history directory use this path "C:\Documents and Settings\Nick\Local Settings\History", and then errors occur.
how to solve this problem?

if i want to write a program get the address in the address box of IE how to do this?Can i use API to do? but i don't know use which APIs

thanks!


 Reply:
by:yEaH rIgHt

 Nick,

I can't recreate your error. Here's what I used.


Dim str() As String
Dim dr As Directory

str = dr.GetDirectories("C:\Documents and Settings\Nick\Local
Settings\History")

Debug.WriteLine(str(0))



 Reply:
by:nick cheng

 i am using vb6
these code is vb.net?


 Reply:
by:james

 Yes, they are VB.NET. You need to ask your questions for VB6 in a VB6
newsgroup.
james



Posted by Xander Zelders
0 Comments



How to print a .rtf File (containing text & graphic)

Found the following interesting discussion in the Newsgroups:

How to print a .rtf File (contains text & graphic)
by:Anonimous

Hi,
I am looking for sample code for printing a .rtf file which contian bot text and graphics.
Thanks so much

Kelly


 Reply:
by:Ken Tucker [MVP]

 Hi,

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnwinforms/html/wnf_RichTextBox.asp

Ken


 Reply:
by:Anonymous

 Thanks it worked!



Posted by Xander Zelders
0 Comments



Is there an HTML web form component?

Found the following interesting discussion in the Newsgroups:

Is there an HTML web form component?
by:Don Nablo

I am looking for a component in VB6 or vb.net that would take simple HTML web form formating strings and populate an space on a windows form. The addtional requirement of this is that when the user clicks on a link on the created form my program can intercept and the URL and posted data, without the component making an HTTP call. It does not have to support graphics.

Does any one know of one? I know you can use a webControl but I have not figured out how to intercept the Http calls to control it.

The base of what I am after is a way to format a windows form with a simple script language like HTML.

Here is an example of the html
<FORM ACTION="./index.asp" METHOD=POST >
<div align="center">
<center>
<TABLE BORDER=0 CELLSPACING=0 CELLPADDING=0 WIDTH=95%>
<TR>
<td width="247"><P align="right"><u><font size="+1" face="Arial">User
ID:</font></u>
<td width="323"><INPUT TYPE="text" NAME="UserID" VALUE="" SIZE=40
MAXLENGTH=50 >
</TR>
<TR>
<td width="247"><P align="right"><u><FONT SIZE="+1"
face="Arial">Password:</FONT></u>
<td width="323"><INPUT TYPE="password" NAME="Password" VALUE="" SIZE=40
MAXLENGTH=50 >
</TR>
<TR>
<td width="285">
<td width="285"><INPUT TYPE="submit" NAME="OK" VALUE="OK"
>    <input type="reset" value="Reset" name="Reset">
</TR>
</TABLE>
</center>
</div>
</FORM>


 Reply:
by:Cor

 Hi Don,

If you already use the axwebbrowser, you needs "mshtml" to handle that, absolute not the nicest thing, it is in the normal .Net reference box, but do not set an import on it, reference it everytime you need because it has so much interfaces everything becomes slow when you try to declare something..

I hope this was the answer you needed?

Cor



Posted by Xander Zelders
0 Comments



Get filenames

Found the following interesting discussion in the Newsgroups:

Get filenames
by:Niels

Hello, i want to read out the file names of a directory.
The previous time, i got this piece of code from someone, but this code counts the number of files in a directory.

My intentions are to get the filenames (without extension) in a combobox....


~~~~~~~~~~
Code
~~~~~~~~~~
Imports System
Imports System.IO

Dim di As DirectoryInfo = New DirectoryInfo("c:\")
Try
Dim dirs As FileSystemInfo() = di.GetDirectories("*p*")
Console.WriteLine("Number of directories with a p: _
{0}", dirs.Length)
Dim diNext As DirectoryInfo
For Each diNext In dirs
Console.WriteLine("The number of files and _
directories " + "in {0} with an e is {1}", diNext, _
diNext.GetFileSystemInfos("*e*").Length)
Next
Catch e As Exception
Console.WriteLine("The process failed: {0}", _
e.ToString())
End Try
~~~~~~~~~~
Code
~~~~~~~~~~


Can anyone help me???


 Reply:
by:Armin Zingler

 
Call di.GetFiles instead of di.GetDirectories. In a loop, call System.IO.Path.GetFileNameWithoutExtension and add the return value to the combobox. Pass the Name property of each FileInfo object returned by di.GetFiles to GetFileNameWithoutExtension.
--
Armin

How to quote and why:
http://www.plig.net/nnq/nquote.html
http://www.netmeister.org/news/learn2quote.html



 Reply:
by:Thom

 Here is the way I do it....

fileNameArray = System.IO.Directory.GetFiles("C:\", "*.")



 Reply:
by:M. Angelo

 
Microsoft.VisualBasic.Compatibility.VB6.FileListBox


 Reply:
by:Cor

 Hi Niels,

That page did gave a lot of samples when you went on in it, but this I added
also to your other question.


\\ Private Sub Button1_Click(ByVal sender As _
System.Object, ByVal e As System.EventArgs) _
Handles Button1.Click
Dim mypath As String
mypath = Application.StartupPath
Dim Dirs As IO.DirectoryInfo = New _
IO.DirectoryInfo(mypath & "\Stamps\")
Dim FileCount As IO.FileSystemInfo() = Dirs.GetFiles
Dim FileNaam As IO.FileInfo
ComboBox1.Items.Clear()
ComboBox1.Items.AddRange(FileCount)
ComboBox1.SelectedIndex = 0
End Sub
///

Cor


 Reply:
by:parth_mca@hotmail-dot-com.no-spam.invalid (parth_mca)

 dim filenames() as string filenames = Directory.getFiles("path u want to get files from","filter u like")

This will give u the filenames array filled with the filenames but each filename will b a full path not just name like c:\aaa\bbb\ccc\zzz.txt instead of just zzz.tzt so u'll have to travers all filename array and for each file name u'll have to split it n get the last element as filename as

dim justname(),longname() as string
for i=0 to filenames.length-1
longname = filenames(i).split("\")
justname(i) = longname(array.length-1) ' the last element of splitted
string which is the filename
next
'' now this justname() is the array that contains filenames u want

good luck....




Posted by Xander Zelders
0 Comments



Simple Datagrid question

Found the following interesting discussion in the Newsgroups:

Simple Datagrid question
by:Rich

Hi

This may be really simple, but I'm just learning! I have a windows form with a datagrid. Can anyone tell me how I can change the datagrid to stop a user adding new rows to it (ie. so they can only edit existing rows)?

Thanks
Richard


 Reply:
by:Cor

 Hi Rich,

The only way I now is do it using a dataview and than set the dataview to AllowNew = False

I hope this answer your questions?

Cor


 Reply:
by:Rich

 Cor, I've tried the dataview and that worked perfectly.

Thanks.
Richard



Posted by Xander Zelders
0 Comments



How to quit an excel object

Found the following interesting discussion in the Newsgroups:

How to quit an excel object?
by:Norton

I type the following code to open/close an excel appz


Dim oExcel As Excel.Application
oExcel = new Excel.Application
....
....
...
If Not oExcel Is Nothing Then oExcel.Quit()
If Not oExcel Is Nothing Then oExcel = Nothing


It returns no error message and the application was shut down, however i still can see it on taskbar and consume many memory

also is there any method to detect if the excel application is opened or not.
I want to open the workbook directly is the excel application has been opened.

Any advise?

Regards,
Norton


 Reply:
by:Cor

 Hi Norton,

I only have some links about this for you.

Office
http://support.microsoft.com/default.aspx?scid=kb;EN-US;311452

http://msdn.microsoft.com/office/

Pia Download
http://www.microsoft.com/downloads/details.aspx?FamilyID=c41bd61e-3060-4f71-a6b4-01feba508e52&displaylang=en
I hope this helps a little bit?

Cor


 Reply:
by:Norton

 Thx Cor.

I traced the problem and i observed that i need to release all Excel related object become run the Excel Object. Like sheet object and workbook object

Again, thx for your help



Posted by Xander Zelders
0 Comments



Saving ANSI Character into SQL Server's varchar field

Found the following interesting discussion in the Newsgroups:

Saving ANSI Character into SQL Server's varchar field
by:Norton

I am trying to type some chinese character into a datagrid then update them into SQL server using SQLDataAdapter, however it always store??? in the database.

As my data type in SQL'server is in Varchar format (i cannot change it into
nvarchar format), what should i do ?

Thx a lot


 Reply:
by:Cor

 Hi Norton,

One of the things that will led to the solution in my idea is asking this too in a more specialized newsgroup.

One of them is

Adonet
<news://msnews.microsoft.com/microsoft.public.dotnet.framework.adonet>

Web interface:
<http://communities2.microsoft.com/communities/newsgroups/en-us/?dg=microsoft.public.dotnet.framework.adonet>

However because you only want the Varchar format, maybe you can ask it too in a newsgroup more specialized in SQL server

I hope you get your results?

Cor


 Reply:
by:Norton


Posted by Xander Zelders
0 Comments



How to play a song with VB.NET

Found the following interesting discussion in the Newsgroups:

About how to play song question !!
by:MingChih Tsai

Dear All,

How should I do if I want to play and stop .mp3 and .wav files in vb.net.

Thanks !!

--
Paul


 Reply:
by:hirf-spam-me-here@gmx.at (Herfried K. Wagner [MVP])

 
<URL:http://www.mentalis.org/soft/class.qpx?id=1>

--
Herfried K. Wagner [MVP]
<URL:http://dotnet.mvps.org/>



Posted by Xander Zelders
0 Comments



Dropdown Form menu.

Found the following interesting discussion in the Newsgroups:

Dropdown Form menu. How to find the tree that the sselected item is from
by:rbrown@edium.com (Robert Brown)

Hi There..

I have a Windows App with a menu. The menu is dynamically created at runtime. This is working perfectly, except.....

I have serveral menus under the one parent. Under each of these menus, there could be menu items with the same text. Of course, when I click the menu item that I want I get the selected text returned to me. Ok.. this is fine, but if the actual menu item I select is not the first one with the same text, how do I know the exact one I selected?

example:

Reports
|
--- Dec-03
| |-> Report 1
| |-> Report 2
|
--- Jan 04
|-> Report 1
|-> Report 2

So in the above example, if I/user selects Report 2 of Jan 04, the select text that is return is "Report 2". How do I find out if that is belonging to Dec 03 or Jan 04? The selected text is used to match the Database to find the report to run, but in the above example, I always get the DEC 03 Report 2. It would be good if I could find the childmenu name (DEC 03 or JAN 04) as well...

This is the statement I use to get the selected item


Public Sub MenuClick(ByVal sender As Object, _
ByVal e As EventArgs)
Dim sSelected as string = CType(sender, MenuItem).Text()
........Blah Blah Blah

End Sub


Any ideas, code examples..

Thanks,
Robert


 Reply:
by:Cor

 Hi Robert,

Try what this very simple and logical sentence can do for you


Dim myItem As String = _
DirectCast(DirectCast(DirectCast(sender, MenuItem).Parent, _
Menu), MenuItem).Text


:-))

Cor



Posted by Xander Zelders
0 Comments



.NET Sockets

Found the following interesting discussion in the Newsgroups:

.NET Sockets Help
by:b.m.

Hi, I'm a beginner to VB.NET ...
I ve been trying to learn .net System.Net.Sockets but i cant seem to figure out a few things... Being that I am an ex-VB6 developer, I am pretty used to Winsock programming.

So far, I have figured out how to accept multiple connections to a single port and send and receive data from the network streams.

What I am having trouble with now, is determining when the socket is closed unexpectedly. WIth Winsock programming, I could just listen in on the Closed event, but there is no such event now..

So my question is how can i determine if the client closes the connection unexpectedly.

Also, does a class exist for VB.NET which more or less simulates a Winsock environment, or at least makes .net sockets a bit easier, at least for a new guy? ;) Any examples would be appreciated.

Thanks in advance,
Bryan


 Reply:
by:Stan Sainte-Rose

 Hi Bryan
I bought the "Peer-To-Peer with vb.net" book, and I found very great samples..
You may check out this url...

http://apress.com/book/bookDisplay.html?bID=174

You can also download some samples..

Stan



Posted by Xander Zelders
0 Comments



Bound Data Class

Found the following interesting discussion in the Newsgroups:

Bound Data Class
by:stevekallal

I seem to remember that VB 6 had a way to bind a data class redirectly to an ADO recordset. Simply put, a the class could be populated with the recordset data without a lot of coding simply by using databinding.

Can this be done in VB .NET. I would like to write Data Classes and populate it from a DataSet.

Thanks in Advance!



 Reply:
by:Cor

 Hi Steve,

When you build everything using the designer it is very simple to do that by just binding the datataset "table" (watch that last) to the datasource (When that is a part of the control. It is by instance in the datagrid, the combobox and the datalist, however not in all controls).

Look for "datasource" in the properties

I hope this helps,

Cor


 Reply:
by:v-phuang@online.microsoft.com (Peter Huang)

 Hi Steve,

What do you mean a Data Class, is Cor's suggestion help you?

As far as I know, when you use drag an dataadapter into the project and generate a dataset, the dataset will have a class.
You can find its class definition under the Dataset1.xsd by clicking the Show All files button on the solution explorer.

If you need to add your customized member into a class which inherits from the class because each time you change the schema of the dataset, the class will be regenerated.

Best regards,

Peter Huang
Microsoft Online Partner Support

Get Secure! - www.microsoft.com/security
This posting is provided "AS IS" with no warranties, and confers no rights.



Posted by Xander Zelders
0 Comments



Using a variable in an expression

Found the following interesting discussion in the Newsgroups:

Using a variable in an expression
by:Derek Martin



Dim what As String = InputBox("What property do you want to get?", "Requested Property")
RichTextBox1.AppendText(PersonList.getpersonbyusername(usernametextbox.Text)
..{what.ToString}.ToString)

How can I do this???? (or is it not possible)

Thanks,
Derek


 Reply:
by:Armin Zingler

 
A user shouldn't deal with property names, but if you need it:

http://msdn.microsoft.com/library/en-us/cpguide/html/cpcondynamicallyloadingusingtypes.asp
--
Armin

How to quote and why:
http://www.plig.net/nnq/nquote.html
http://www.netmeister.org/news/learn2quote.html



 Reply:
by:Nice Chap

 use CallByName


 Reply:
by:Derek Martin

 I agree absolutely, this is more for testing purposes so that I can write some code to pass into a generalized function that returns 'object attribute' based on what is passed in. :-)
Many thanks to you both!



Posted by Xander Zelders
0 Comments



How to hande events to control arrays

Found the following interesting discussion in the Newsgroups:

How to hande events to control arrays?
by:SuperRider

I have ~ 50 comboboxes (in an array) on a form, and I want to run the same subroutine every time any combobox changes. Now, I can get this done by manually editing the "OnChanged" for every one, but surely there is an easier (shorter) way to do it.

TIA!


 Reply:
by:Marina

 Have their onchanged event all go to the same handler. Loop through your array, adding the handler for each combobox.



Posted by Xander Zelders
0 Comments



ArrayList subtract?

Found the following interesting discussion in the Newsgroups:

ArrayList subtract?
by:Craig Buchanan

I have two arraylists, one with a list of groups and one with a list of groups assigned to a user. I would like to subtract the second AL from the first AL to get an AL of groups to which the user *isn't* assigned. Is there an easy way to do this?

Thanks,

Craig


 Reply:
by:drew

 yes, but i'd suggest you move to another data structure such as the dataset with two datatables which will allow you to manage relationships much easier than looping over two arraylists in a nested for loop. one issue if you decide to go the second route it you have to store the elements you wish to remove in a third list and then iterate that list to remove from the second list.... because you can't modify the underlying list while using an ienumerator base on it. datasets look a lot better dont they?


 Reply:
by:Jay B. Harlow [MVP - Outlook]

 Craig,
As Drew suggested, create a third AL that is your result, for each item in the first, if it is not in the second add it to your result.

Something like:


Dim groups As New ArrayList
Dim assigned As New ArrayList
Dim result As New ArrayList

groups.Add("one")
groups.Add("two")
groups.Add("three")

assigned.Add("two")

For Each group As Object In groups
If not assigned.Contains(group) Then
result.Add group
End If
Next


Instead of an ArrayList however I would use a GroupCollection object that contains individual Group objects, where GroupCollection inherits from either DictionaryBase or CollectionBase depending on whether it is a "keyed" collection or not. The above code would be a function of the GroupCollection object.


Public Class GroupCollection
Inherits CollectionBase

...

Public Function GetDifference(...) ...
For Each group As Object In InnerList


Hope this helps
Jay



Posted by Xander Zelders
0 Comments



ComboBox class, CB_INSERTSTRING , VB.NET and marshalling...

Found the following interesting discussion in the Newsgroups:

ComboBox class, CB_INSERTSTRING , VB.NET and marshalling...
by:GianPiero Andreis

Hello All,
let me pose a simple question about combobox and the CB_INSERTSTRING message.
Suppose for instance that I already have a combobox handle, how can I declare and use the SendMessage function just for insert a new item into the combobox ?
Of course, the combo box DO NOT belong to my process, so I can't use the standard properties of that class. In fact, I need to "put" a new entry in the combo box of IExplorer. EnumWindows get me the handle of the IExplorer main window, with EnumChildWindows I can obtain the handle of the "www address" combo. At this point, I would like to put into the combo an "www address" of choice.
I tried ALL the parameters of the MarshalAs attribute related to the string, (with the UnmanagedType enum) but never seems to works, sometime IE crashes.. :-)

Please, don't tell to me to use SendKeys class. .NET SendKeys class works well (do not alter, no more, the numlock and/or capslock status of my keyboard, like the older sendkeys in VB) but I need to use SendMessage because I want to unterstand hot to marshalling correctly the parameters. And last, but not least, I LIKE API's...

Thank You Gentleman for Your precious help.
Best regards
Ing. GianPiero Andreis


 Reply:
by:CJ Taylor

 
Whats your code look like for the SendMessage?
And what part are you marshalling? individual variables or an entire structure?


 Reply:
by:GianPiero Andreis

 Ok,
a piece of code...
This is the function I use for looping over the child windows in IE.
Everything works well except the SendMessageA function


Public Function EnumChildWindowsSub(ByVal _
argl_hChildWnd As IntPtr, ByVal argl_Param _
As Integer) As Boolean
Dim lsb_ClassName As New StringBuilder(256)
Call GetClassNameA(argl_hChildWnd, lsb_ClassName, _
lsb_ClassName.Capacity)
If (lsb_ClassName.ToString = "ComboBox") Then
SendMessageA(argl_hChildWnd.ToInt32, _
CB_INSERTSTRING, 0, "www.thatsite.com")
'This just for see with Spy that the combo handle is correct
Me.Text = "I find combo with handle " & _
Hex(argl_hChildWnd.ToInt32).ToString
Return False
Else
Return True
End If
End Function


And this is the prototype for the function.


Private Declare Auto Function SendMessageA _
Lib "user32" (ByVal hwnd As Long,
ByVal wMsg As Long, ByVal wParam As Long _
, <MarshalAs(UnmanagedType.LPStr)>
ByVal lParam As String) As Long


There is no need to use System.IntPtr, I don't look for system portability at this time.

Regarding to formatted classes, at this time I don't use it because I see Win32 APi's are working as well without the use of that encapsulation. Maybe this is the cause of the problem, but consider that I use API very very often in .NET (because I wrote automation programs, macro player and so on), and everything works well without formatted classes. I tried also the use of StringBuilder class as fouth parameter in the SendMessageA function, but IE crashes.
If You need other informations, I would be glad to write for You forward. Please excuse my english, is very poor, I know.

Thank You in advance, Sir.

Ing. GianPiero Andreis


 Reply:
by:GianPiero Andreis

 Hey All,
finally this code works. I worked hard over the CB_*** messages, but there are no way (it seems to me) to set an item into the ComboBox, like the old VB instead allow with API.

The only solution I find is to send a message with the edit portion of the combo (i.e. is a child window that belongs to the combo). So You need, once You have the combo handle, to enumerate all the child windows in the combo, and when the class name You find is "Edit", You can send the message WM_SETTEXT with the string You wanted. Below You find the declaration of SendMessage and the line of code that send the string into the combo.

Hope this helps someone.

Best regards


'Declaration
Private Declare Auto Function SendMessageA _
Lib "user32" (ByVal hwnd As
IntPtr, ByVal wMsg As IntPtr, ByVal wParam As IntPtr,
<MarshalAs(UnmanagedType.AnsiBStr)> ByVal _
lParam As String) As IntPtr
'Code (argl_hChildWnd is the handle of the Edit _
window into the combo)
SendMessageA(argl_hChildWnd, New _
IntPtr(WM_SETTEXT), IntPtr.Zero, "www.thatsite.com")


 Reply:
by:M. Angelo

 If you use sendmessage to set the strings in a list control you will not be able to use the framework functions to retrieve it because it deals with objects instead of strings.

The ListBox and the TextBox are not extremely difficult to subclass but I found the ComboBox subclassing not pratical.

I would like to read further from your experience.

Regards



Posted by Xander Zelders