Hope you don't mind some questions from an interop newbie ('m not even sure
what questions to ask, but I want to learn) ...
I'm trying to access a COM object (the MS Agent server) in VB.Net 2005. I
can create the object that represents the server, access its methods and
properties, and more. So far so good.
But at one point I need to obtain a reference to an interface the server
object supports, then call a method on that interface. Here's some sample
code that some VB6 MS Agent folks think should work:
----------
dim AgentEx as IAgentEx
(code that creates and initializes AgentEx)
Dim ps As IAgentPropertySheet
ps = AgentEx ' this object should support the IAgentPropertySheet interface
(or)
ps = CType(objServer, IAgentPropertySheet)
----------
Both my attempts to assign a valueto ps fail with
System.InvalidCastException.
One oddity is that the code that initializes AgentEx uses a similar
technique:
Dim objServer = new AgentServer
Dim objAgentEx = objServer
And that works. It's just the attempt to gain access to the
IAgentPropertySheet that fails.
Any ideas or suggestions?
Is there a way to query a COM object to find what Interfaces it supports (to
be sure IAgentPropertySheet is actually supposed to work)?
I don't know if this is a problem with my understanding of COM interop
(extremely limited to non-existent!). Or with MS Agent.
Karen Kenworthy - 28 Sep 2005 03:33 GMT
Turns out this was known problem with COM objects that use the STA
(Single-Threaded Apartment) threading model
(http://support.microsoft.com/Default.aspx?kbid=309330). One of the
workarouds (the one I've chosen) is to perform the object access on a new
STA thread. So now, where I had originally planned to execute this code:
Dim ps as IAgentPropertySheet
ps = objAgentEx ' type = IAgentEx
ps.SetVisible(True)
I now run this code:
Dim t As New Threading.Thread(AddressOf DispPropSheet)
t.SetApartmentState(Threading.ApartmentState.STA)
t.Start()
Threading.Thread.Sleep(0)
t.Join()
The orginal code is in the DispPropSheet sub.
Voila! I can now display the property sheet. And the character, and my main
program, continue to run alongside it!
Karen Kenworthy
http://www.karenware.com/