c# - 使用 c++/cli 和在 c# 中使用它的事件处理

标签 c# c++ c++-cli

-我想在调用方法 showmessage 时引发一个事件。我想在 C# 中捕获它 代码。

-我已经为它编写了事件。

-我在 Initialize 函数中所做的将委托(delegate)与关联是否正确 函数显示消息

-如何在c#中使用这个事件

C++/CLI

delegate void progressmsgdisplay(System::String ^ message);
progressmsgdisplay  ^ progressMsgNotify;
void Mclass::ShowMessage(System::String ^ message)
{ 
MessageBox(NULL, m_msg, m_box, NULL);
notify(message);
}
event progressmsgdisplay ^ notify 
{
    void add(progressmsgdisplay ^ d) 
    {
        progressMsgNotify += d;
    }


    void remove(progressmsgdisplay ^ d) 
    {
        progressMsgNotify -= d;
    }


    void raise(System::String ^ msg)
    {
       progressmsgdisplay ^ tmp = progressMsgNotify;
               if (tmp) 
        {
        tmp->Invoke(msg);
        }

    }
}

//void Mclass::Initialize(System::String ^ strProgressMsg)
//{
// progressMsgNotify=gcnew progressmsgdisplay(this,&Mclass::ShowMessage);
//}

-Mclass 是声明和定义上述所有内容的类的名称

C#
void display(string progressnotification)
 {
    Console.Out.WriteLine(progressnotification);
 }
void initialize()
{
 first = new Mclass();
 first.notify()+=display;
}

成功了

最佳答案

为什么不能直接在c++/cli中使用EventHandler类并在C#中订阅它

//C++/CLI
public ref class SomeClass
{
    public:
    event EventHandler^ someEvent;
}

//C#
class Program
{
    static void Main(string[] args)
    {
        SomeClass testclass = new SomeClass();
        testclass.someEvent += someEventHandler;
    }

    private void someEventHandler(Object obj, EventArgs args)
    {

    }
}

我还没有试过这个。但我想它值得一试。

关于c# - 使用 c++/cli 和在 c# 中使用它的事件处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9696714/

相关文章:

C++ 在初始化列表中的基类初始化之前调用函数

c++ - printf 使 setrlimit 不起作用

c++ - Eclipse CDT 语法着色问题

c# - ReadOnlyCollections 的 Xml 序列化

c# - 有 Lambda 脑筋急转弯的好资源吗

c# - Unity C#中 "Missing Reference Exception"和 "Null Reference Exception"的区别

compiler-construction - 混合 C++/CLI TypeLoadException 内部限制 : too many fields

c++ - 在 .cpp 文件中包含头文件时基类未定义

c++ - DataGridView 类 - 错误()

c# - 如何对求和运算进行单元测试以确保该运算实际上是求和?