В моем аналогичном случае SubclassWindow
в OnHandleCreated
по какой-то причине не сработало. После некоторой борьбы я заработал (без C ++ / CLI):
Сначала получите HWND от Form#Handle
и передайте его в свою MFC DLL.
class GuestControl : Control
{
private IntPtr CWnd { get; set; }
public GuestControl()
{
CWnd = attach(Handle);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
detach(CWnd);
}
base.Dispose(disposing);
}
[DllImport("your_mfc_dll")]
private static extern IntPtr attach(IntPtr hwnd);
[DllImport("your_mfc_dll")]
private static extern void detach(IntPtr hwnd);
}
Затем в вашей DLL CWnd::Attach
до полученного HWND и инициализируйте управление. Очистить с помощью CWnd::Detach
при утилизации.
/** Attach to C# HWND and initialize */
extern "C" __declspec(dllexport) CWnd* PASCAL attach(HWND hwnd) {
auto w = std::make_unique<CWnd>();
if (!w->Attach(hwnd)) { return nullptr; }
// ... initialize your MFC control ...
return w.release();
}
/** Detach and delete CWnd */
extern "C" __declspec(dllexport) void PASCAL detach(CWnd *cwnd) {
auto w = std::unique_ptr<CWnd>(cwnd);
w->Detach();
}
См. Полный пример GuestControl.cs / guest.cpp *.
Редактировать: Код в этот связанный вопрос также использовать Attach
/ Detach
.
* Пример - моя работа. (Лицензия MIT)