technorabble
technorabble

Reputation: 511

C#.NET Winform in unmanaged C++ via CLI wrapper - thread required?

I am trying to make a program where I call a C#.NET Form from unmanaged C++ via a C++/CLI wrapper class.

The form displays as expected, but any code after launch of the form does not execute. I don't really understand threading, but I feel that may be my issue.

Here's my 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;

}

And here's my CLI Wrapper:

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();
    }   

};

My console, where I enter numbers in order to progress execution, will not allow any input until I close my form. What I'm actually aiming for here is for the form to update while other code is executing, e.g. showing data from the main program thread.

Any ideas?

Upvotes: 0

Views: 453

Answers (1)

Ben Voigt
Ben Voigt

Reputation: 283664

Right now you don't have any multi-threading at all.

The C++ processing thread can't continue until the C# function it calls, returns. So that C# function should start a new thread and return quickly.

The new thread can then activate a message loop (Application::Run) and show UI.

You will need to use Control::Invoke() to access UI from other threads. Hopefully it is the C# portion of the code doing that -- anonymous lambdas and such get it done in a lot less code than you would need with C++.

Upvotes: 1

Related Questions