【问题标题】:How to add Tick event to System::windows::Forms::Timer in unmanaged class如何在非托管类中将 Tick 事件添加到 System::windows::Forms::Timer
【发布时间】:2011-10-28 09:30:45
【问题描述】:

我正在尝试像我在某些示例中找到的那样:

TimerID = gcnew System::Windows::Forms::Timer(); 
TimerID->Tick += gcnew System::EventHandler(this, &Bridge::timer1_Tick);

System::Void Bridge::timer1_Tick(System::Object^  sender, System::EventArgs^  e) 
{
    Bridge::DoUpdate();
}

但由于错误无法创建事件处理程序:

错误 C3364:“System::EventHandler”:委托的参数无效 构造函数;委托目标需要是指向成员的指针 功能

Bridge 是非托管类。 所以我以这种方式声明 TimerID:

gcroot<System::Windows::Forms::Timer ^> TimerID;

我在这里做错了什么?如何正确添加 Tick 事件?

【问题讨论】:

  • 你为什么要这样做?如果您使用托管计时器,请使用托管类型。

标签: .net visual-c++ event-handling timer c++-cli


【解决方案1】:

您没有发布足够的代码来诊断错误。这样编译:

public ref class Bridge : public System::Windows::Forms::Form
{
    Timer^ TimerID;
public:
    Bridge(void) {
        InitializeComponent();
        TimerID = gcnew System::Windows::Forms::Timer(); 
        TimerID->Tick += gcnew System::EventHandler(this, &Bridge::timer1_Tick);        
    }
private:
    void Bridge::timer1_Tick(System::Object^  sender, System::EventArgs^  e) {
    }
    void InitializeComponent(void) {
        // etc...
    }
};

【讨论】:

  • 应该是,Bridge 是非托管类,我正在使用 gcroot for Timer
  • 嗯,这就解释了。您如何设法编译采用托管对象的本机方法有点神秘。您需要使用 Marshal::GetDelegateForFunctionPointer() 来获取针对本机函数的委托对象。目标函数必须是静态的,不能是类的实例方法。或者只是将计时器设置为调用托管方法,然后再调用本机方法。
  • 你的意思是我的 System::Void Bridge::timer1_Tick(System::Object^ sender, System::EventArgs^ e) 也是不受管理的,不能被调用?我必须让它 gcroot 吗?
猜你喜欢
  • 2018-03-19
  • 1970-01-01
  • 2015-12-12
  • 1970-01-01
  • 2018-05-03
  • 1970-01-01
  • 2019-01-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多