2013-05-17 78 views
1

請看看下面的代碼如何在C++/CLI中創建C#事件處理程序?

private: System::Void button3_Click(System::Object^ sender, System::EventArgs^ e) 
{ 
    System::Speech::Recognition::SpeechRecognizer ^sr = gcnew System::Speech::Recognition::SpeechRecognizer(); 

    array<String ^> ^strs = gcnew array<String ^> {"Hello", "World"}; 

    System::Speech::Recognition::Choices ^colors = gcnew System::Speech::Recognition::Choices(); 
    colors->Add(strs); 

    System::Speech::Recognition::GrammarBuilder ^gb = gcnew System::Speech::Recognition::GrammarBuilder(); 
    gb->Append(colors); 

    System::Speech::Recognition::Grammar ^g = gcnew System::Speech::Recognition::Grammar(gb); 
    sr->LoadGrammar(g); 

    // System::IntPtr ptr = gcnew System::IntPtr(&sr_SpeechRecognized); 
    sr->SpeechRecognized += gcnew System::EventHandler<System::Speech::Recognition::SpeechRecognizedEventArgs>(this,&Form1::sr_SpeechRecognized); 
} 

void sr_SpeechRecognized(System::Object ^sender, System::Speech::Recognition::SpeechRecognizedEventArgs^ e) 
{ 
} 

此代碼生成以下錯誤

1>------ Build started: Project: SpeechTest, Configuration: Debug Win32 ------ 
1> SpeechTest.cpp 
1>c:\users\yohan\documents\visual studio 2010\projects\speechtest\speechtest\Form1.h(144): error C3225: generic type argument for 'TEventArgs' cannot be 'System::Speech::Recognition::SpeechRecognizedEventArgs', it must be a value type or a handle to a reference type 
1>c:\users\yohan\documents\visual studio 2010\projects\speechtest\speechtest\Form1.h(144): error C3352: 'void SpeechTest::Form1::sr_SpeechRecognized(System::Object ^,System::Speech::Recognition::SpeechRecognizedEventArgs ^)' : the specified function does not match the delegate type 'void (System::Object ^,System::Speech::Recognition::SpeechRecognizedEventArgs)' 
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ========== 

在這裏,一切工作正常期望處理器創建sr->SpeechRecognized += gcnew System::EventHandler<System::Speech::Recognition::SpeechRecognizedEventArgs>(this,&Form1::sr_SpeechRecognized);

如果註釋掉此處理程序部分,一切都會好的。這裏的Form表示當前的GUI表單,它是由C++/CLI構建的默認GUI表單。所有這些代碼都在這種形式中。我以我閱讀文章的方式創建了這個處理程序。那麼有人可以幫我糾正這個問題嗎?

回答

4

您錯過了^

sr->SpeechRecognized += gcnew System::EventHandler<System::Speech::Recognition::SpeechRecognizedEventArgs^>(this,&Form1::sr_SpeechRecognized); 
                          // right here^

採取在您收到此錯誤信息仔細一看,與命名空間取出,並用換行符,使事情排隊。

 
    error C3352: 'void SpeechTest::Form1::sr_SpeechRecognized(Object^,SpeechRecognizedEventArgs^)' : 
the specified function does not match the delegate type 'void (Object^,SpeechRecognizedEventArgs)' 
                           ^

你想創建一個委託給帶有SpeechRecognizedEventArgs的方法,但你給它,需要一個SpeechRecognizedEventArgs^的方法的名稱。

+0

無言謝謝..謝謝! –

相關問題