Good way to use native C++ callback as managed C++ delegates / events

L

lallous

Hello

I don't have C++/CLI 2.0 reference handy and the code below was written
after long hours of research and shallow readings. From what I see, the code
works and looks logical to me. Can you please review it and tell me if I
overlooked something.

On the other hand, can you suggest a good C++/CLI 2.0 book for starters?

Code purpose: To use native EnumWindows() and have its callback handled
within any user created delegate.

[begin]
#include "stdafx.h"

using namespace System;

class EnumWindowsProcThunk;

public ref class MyClass
{
private:
EnumWindowsProcThunk *m_thunkEnumWindows;
public:
delegate bool delOnEnum(int h);
delOnEnum ^OnEnum;

void EnumWindows();

MyClass();
};

private class EnumWindowsProcThunk
{
private:
msclr::auto_gcroot<MyClass^> m_clr;
public:
static BOOL CALLBACK fwd(
HWND hwnd,
LPARAM lParam);

EnumWindowsProcThunk(MyClass ^clr);
};

MyClass::MyClass()
{
OnEnum = nullptr;
m_thunkEnumWindows = new EnumWindowsProcThunk(this);
}

void MyClass::EnumWindows()
{
::EnumWindows(&EnumWindowsProcThunk::fwd, (LPARAM)(m_thunkEnumWindows));
}

EnumWindowsProcThunk::EnumWindowsProcThunk(MyClass ^clr)
{
m_clr = clr;
}

BOOL CALLBACK EnumWindowsProcThunk::fwd(HWND hwnd,LPARAM lParam)
{
return static_cast<EnumWindowsProcThunk *>((void
*)lParam)->m_clr->OnEnum((int)hwnd) ? TRUE : FALSE;
}

ref class MyGUI
{
private:
public:
bool OnEnumHandler(int h)
{
Console::WriteLine("MyGUI: {0}", h);
return true;
}
};

int main(array<System::String ^> ^args)
{
MyClass ^mc = gcnew MyClass();

MyGUI ^g = gcnew MyGUI;

mc->OnEnum += gcnew MyClass::delOnEnum(g, &MyGUI::OnEnumHandler);

mc->EnumWindows();

return 0;
}
[end]
 
A

adebaene

Hello

I don't have C++/CLI 2.0 reference handy and the code below was written
after long hours of research and shallow readings. From what I see, the code
works and looks logical to me. Can you please review it and tell me if I
overlooked something.
<snip>

In .NET 2.0, you shall use
System::Runtime::InteropServices::Marshal::GetFunctionPointerForDelegate

Arnaud
MVP - VC
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top