15.02.2015 Views

C# 4 and .NET 4

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

712 ❘ ChaPTer 26 interOp<br />

//.<br />

public:<br />

BEGIN_CONNECTION_POINT_MAP(CCOMDemo)<br />

CONNECTION_POINT_ENTRY(__uuidof(_ICompletedEvents))<br />

END_CONNECTION_POINT_MAP()<br />

};<br />

code snippet COMServer/COMDemo.h<br />

Finally, the method Fire_Completed() from the proxy class can be called inside the methods Add() <strong>and</strong><br />

Sub() in the file COMDemo.cpp:<br />

STDMETHODIMP CCOMDemo::Add(LONG val1, LONG val2, LONG* result)<br />

{<br />

*result = val1 + val2;<br />

Fire_Completed();<br />

return S_OK;<br />

}<br />

STDMETHODIMP CCOMDemo::Sub(LONG val1, LONG val2, LONG* result)<br />

{<br />

*result = val1 - val2;<br />

Fire_Completed();<br />

return S_OK;<br />

}<br />

code snippet COMServer/COMDemo.cpp<br />

After rebuilding the COM DLL, you can change the .<strong>NET</strong> client to use these COM events just like a normal<br />

.<strong>NET</strong> event:<br />

static void Main()<br />

{<br />

COMDemo obj = new COMDemo();<br />

IWelcome welcome = obj;<br />

Console.WriteLine(welcome.Greeting("Stephanie"));<br />

obj.Completed += () => Console.WriteLine("Calculation completed");<br />

IMath math = (IMath)welcome;<br />

int result = math.Add(3, 5);<br />

Console.WriteLine(result);<br />

}<br />

Marshal.ReleaseComObject(math);<br />

code snippet DotnetClient/Program.cs<br />

As you can see, the RCW offers automatic mapping from COM events to .<strong>NET</strong> events. COM events can be<br />

used similarly to .<strong>NET</strong> events in a .<strong>NET</strong> client.<br />

tsing a .neT ComPonenT from a Com ClienT<br />

So far, you have seen how to access a COM component from a .<strong>NET</strong> client. Equally interesting is to find a<br />

solution for accessing .<strong>NET</strong> components on an old COM client that is using Visual Basic 6.0, or C++ with<br />

MFC (Microsoft Foundation Classes), or ATL.<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!