从C++引发事件的问题将在C#中处理
本文关键字:处理 问题 C++ 事件 | 更新日期: 2023-09-27 18:28:04
我正在尝试编写一个使用C++DLL的基于C#的WPF应用程序。C#应用程序是用于用户界面的,它具有WPF的所有优点。C++DLL使用Win32函数(例如枚举窗口)。
现在我希望C++DLL引发可以在C#应用程序中处理的事件。这是我尝试过的(基于本文):
//cpp file
#using <System.dll>
using namespace System;
struct WIN {
HWND Handle;
char ClassName;
char Title;
};
delegate void wDel(WIN);
event wDel^ wE;
void GotWindow(WIN Window) {
wE(Window);
}
当我试图编译此代码时,会抛出以下错误:
C3708:"wDel":"event"的使用不正确;必须是兼容事件源的成员
C2059:语法错误:"event"
C3861:"wE":找不到标识符
您的事件需要是某个托管类的成员,可能是静态的。例如:
#include "stdafx.h"
#include "windows.h"
using namespace System;
struct WIN {
HWND Handle;
char ClassName;
char Title;
};
delegate void wDel(WIN);
ref class WindowEvents abstract sealed // abstract sealed ref class in c++/cli is like a static class in c#
{
public:
static event wDel^ wE;
static void GotWindow(WIN Window) {
wE(Window);
}
};
更新
如果您需要将非托管的HWND
转换为IntPtr
,因为IntPtr
是c#中HWND的标准p/Invoke签名,您可能会考虑以下内容:
#include "stdafx.h"
#include "windows.h"
using namespace System;
#pragma managed(push,off)
struct WIN { // Unmanaged c++ struct encapsulating the unmanaged data.
HWND Handle;
char ClassName;
char Title;
};
#pragma managed(pop)
public value struct ManagedWIN // Managed c++/CLI translation of the above.
{
public:
IntPtr Handle; // Wrapper for an HWND
char ClassName;
char Title;
ManagedWIN(const WIN win) : Handle(win.Handle), ClassName(win.ClassName), Title(win.Title)
{
}
};
public delegate void wDel(ManagedWIN);
public ref class WindowEvents abstract sealed // abstract sealed ref class in c++/cli is like a static class in c#
{
public:
static event wDel^ wE;
internal:
static void GotWindow(WIN Window) {
wE(ManagedWIN(Window));
}
};
这里ManagedWIN
只包含安全的.Net类型。