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.

722 ❘ ChaPTer 26 interOp<br />

The main method now needs a change to advise the component of the existence of the event sink object,<br />

so that the component can call back into the sink. This can be done with the method DispEventAdvise()<br />

of the CEventH<strong>and</strong>ler class by passing an IUnknown interface pointer. The method DispEventUnadvise()<br />

unregisters the sink object again.<br />

int _tmain(int argc, _TCHAR* argv[])<br />

{<br />

HRESULT hr;<br />

hr = CoInitialize(NULL);<br />

try<br />

{<br />

IWelcomePtr spWelcome;<br />

hr = spWelcome.CreateInstance("Wrox.DotnetComponent");<br />

IUnknownPtr spUnknown = spWelcome;<br />

cout < < spWelcome- > Greeting("Bill") < < endl;<br />

CEventH<strong>and</strong>ler* eventH<strong>and</strong>ler = new CEventH<strong>and</strong>ler();<br />

hr = eventH<strong>and</strong>ler- > DispEventAdvise(spUnknown);<br />

IMathPtr spMath;<br />

spMath = spWelcome; // QueryInterface()<br />

long result = spMath- > Add(4, 5);<br />

cout < < "result:" < < result < < endl;<br />

eventH<strong>and</strong>ler- > DispEventUnadvise(spWelcome.GetInterfacePtr());<br />

delete eventH<strong>and</strong>ler;<br />

}<br />

catch (_com_error& e)<br />

{<br />

cout < < e.ErrorMessage() < < endl;<br />

}<br />

}<br />

CoUninitialize();<br />

return 0;<br />

PlaTform inVoKe<br />

Not all the features of Windows API calls are available from the .<strong>NET</strong> Framework. This is not only true<br />

for old Windows API calls but also for very new features from Windows 7 or Windows Server 2008 R2.<br />

Maybe you ’ ve written some DLLs that export unmanaged methods, <strong>and</strong> you would like to use them from<br />

<strong>C#</strong> as well.<br />

You can read about specifi c features of Windows 7 <strong>and</strong> Windows Server 2008 R2 in<br />

Appendix A, “Guidelines for Windows 7 <strong>and</strong> Windows Server 2008 R2.”<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!