2014-10-03 27 views
0

我想通過C++/CLI包裝類從非託管C++調用C#.NET表單的程序。C#.NET Winform通過CLI封裝非託管C++ - 需要線程嗎?

窗體按預期顯示,但表單啓動後的任何代碼都不會執行。我不太瞭解線程,但我覺得這可能是我的問題。

這裏是我的main.cpp:

int main() 
{ 
    int fred; 
    TestFormWrapper testForm; 

    testForm.ShowForm(); 

    std::cin >> fred; // to allow me to see the form before and after label change 

    testForm.ChangeLabel(); 

    std::cin >> fred; // to allow me to see the form before and after label change 

    return 0; 

} 

這是我的CLI包裝:

class __declspec(dllexport) TestFormWrapper 
{ 
private: 
    TestFormWrapperPrivate* _private; 

public: 
    TestFormWrapper() 
    { 
     _private = new TestFormWrapperPrivate(); 
     _private->testForm = gcnew ManagedForms::TestForm(); 

    } 

    ~TestFormWrapper() 
    { 
     delete _private; 
    } 


    void ShowForm() 
    { 
     System::Windows::Forms::Application::Run(_private->testForm); 
    } 

    void ChangeLabel() 
    { 
     _private->testForm->changeLabel(); 
     _private->testForm->Refresh(); 
    } 

}; 

我的控制檯,在那裏我才能進步執行輸入數字,不會允許任何輸入直到我關閉我的表單。我實際上想要的是在其他代碼正在執行時更新表單,例如,顯示來自主程序線程的數據。

任何想法?

+0

您反轉了線程 - UI始終運行在前臺線程(通常被認爲是主線程)上,其他工作發生在後臺線程上。 – 2014-10-03 10:02:52

+0

@PanagiotisKanavos謝謝。我對線程非常不熟悉,有沒有簡單的解決方法? – technorabble 2014-10-03 10:08:58

+0

UI線程是一個UI線程,因爲它運行一個消息循環。該循環是「Application :: Run」。進程主線程變成UI線程還是工作線程並不重要。 – 2014-10-03 16:55:59

回答

1

現在你根本沒有任何多線程。

C++處理線程不能繼續,直到它調用,返回的C#函數。所以C#函數應該啓動一個新線程並且很快返回。

新線程然後可以激活消息循環(Application::Run)並顯示UI。

您將需要使用Control::Invoke()從其他線程訪問UI。希望這是代碼的C#部分 - 匿名lambda表達式,並且使用比C++所需的代碼少得多的代碼。

相關問題