开发者

simple counter in windows forms application C++

Just practicing my vs 2010 C++ in Windows Form Applications, I haven't done this for a very long time. I am trying to develop a simple applications where a user presses a button and then label1 begins to count everytime users presses that button1. Not sure why label1 is not incrementing by 1. Can someone tell what t开发者_C百科he problem is? Thanks in advance?

EDITED I have found the solution and I have amended the code. I will try to close the thread and if I can't, because of I have low points, I will then try tomorrow.

    namespace Counter 
    {
      int counter = 0;
     //some additional namespaces


    private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e) 
         {
           counter++;
           label1->Text = counter.ToString();
                     }


The reason why this isn't working is twofold.

  1. The way you've written this, you only set the label text once, after you finish your "loop" (*). So the text will only change once.
  2. Even if you move the assignment inside the loop, you're keeping the main thread busy throughout the whole function. What you want is to spawn a second thread and invoke a delegate to change the label text, something like this (C# version):

    void StartCounting()
    {
      var thread=new Thread(()=>
      {
        for(int i=0;i<10;++i)
          label1.Invoke((MethodInvoker)()=>{label1.Text=i.ToString();});
      }
    }
    

(*) As a side note, your entire for loop is equivalent to absolutely nothing. j will never be less than i when i starts as 0.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜