开发者

Removing Text with an Invoke?

开发者 https://www.devze.com 2023-04-03 11:01 出处:网络
So, the documentation that I\'ve found online so far regarding the Invoke property doesn\'t seem to be particularly good, which is actually kind of annoying, believe it or not. I understand what Invok

So, the documentation that I've found online so far regarding the Invoke property doesn't seem to be particularly good, which is actually kind of annoying, believe it or not. I understand what Invoke does - you can't safely access the GUI directly, so an invoke does it in a safe way. That's fine, but I don't understand the variables that go into the开发者_StackOverflow中文版 method. If I wanted to, for instance, remove text from a listbox, how would I do that? I get about this far before I get a bit lost.

private void DoStuff(string TextIWouldBeRemoving)
{        

if (listboxname.InvokeRequired)
    {
        listboxname.Invoke(SomeMysteriousParamaters, new object[] { TextIWouldBeRemoving )};   
    }
}


The first parameter is the method you want to safely invoke, the second parameter is an object array of the arguments to that method

So you would write:

private void DoStuff(string TextIWouldBeRemoving)
{        
    if (listboxname.InvokeRequired)
    {
        listboxname.Invoke(DoStuff, new object[] { TextIWouldBeRemoving )};   
    }
    else
    {
        // Actually remove the text here!
    }
}


Invoke is all about threading.

You need to do an invoke whenever you have created a separate thread in your code, and you need to update the User Interface elements from withing the code, that is executing in that newly create thread.

You can use a BeginInvoke, instead of a synchronous Invoke method. This article has a good example:

http://msdn.microsoft.com/en-us/library/0b1bf3y3.aspx


  private void button1_Click(object sender, EventArgs e)
  {
     if (listBox1.InvokeRequired)
     {
        Action<string> d = DoAnything;
        listBox1.Invoke(d, new object[] { "Item 1" });
     }
     else
        DoAnything("Item 1");
  }

  void DoAnything(string itemText)
  {
     listBox1.Items.Remove(itemText);
  }
0

精彩评论

暂无评论...
验证码 换一张
取 消