• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1106
  • Last Modified:

C++ delegate to update GUI textbox

I'm moving from C# where I know how to do things to C++ where I'm unfamiliar with the syntax.

I have a simple C++ winforms application with a textbox named textBox1, and I want to write a delegate so I can update the text from other threads.
    delegate void UpdateTextBox1delegate(System::String^ someText);

  public: 
    void Update(System::String^ someText) {

        if (this->textBox1->InvokeRequired) {

            UpdateTextBox1delegate^ d = gcnew UpdateTextBox1delegate(this, &Form1::UpdateTextBox1delegate);
            this->Invoke(d,someText);
        }
        else {
            textBox1->Text = someText;
        }
    }

Open in new window

Gives me this error complaining about line 8:
error C2275: 'DelegateTest::Form1::UpdateTextBox1delegate' : illegal use of this type as an expression
error C3350: 'DelegateTest::Form1::UpdateTextBox1delegate' : a delegate constructor expects 2 argument(s)
(I'm also surprised I can't find any sample C++ code that does this.)
0
deleyd
Asked:
deleyd
1 Solution
 
Robert SchuttSoftware EngineerCommented:
I think "the standard example" for this is: http://msdn.microsoft.com/en-us/library/vstudio/ms171728(v=vs.90).aspx?cs-save-lang=1&cs-lang=cpp#code-snippet-2

There are some user comments that complain about missing info but it seems it only needs a delegate definition from a later example on the same page. You already have that defined so should be able to use:
    delegate void UpdateTextBox1delegate(System::String^ someText);

  public: 
    void Update(System::String^ someText) {

        if (this->textBox1->InvokeRequired) {

            UpdateTextBox1delegate^ d = gcnew UpdateTextBox1delegate(this, &Form1::Update);
            this->Invoke(d, gcnew array<Object^> { someText });
        }
        else {
            this->textBox1->Text = someText;
        }
    }

Open in new window

So 2 changes:
1) refer to the class method, not the delegate when creating the delegate.
2) pass an object array instead of the argument directly

Note I'm not a C++.NET programmer myself (so please double check syntax), but have made mistakes like this in several languages in the past ;-)
0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now